def resource_usage_cost(self, billing_month=None, tenant_id=None, resource_id=None, offset=None, limit=None): """Return the amount to pay for each resource within a special service type. """ policy.enforce(pecan.request.context, 'billing:show_resource_rate', {}) storage = pecan.request.storage_backend begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) rated_children_tenants = [] self.fetcher.get_rated_subordinate_tenants(tenant_id, rated_children_tenants) rated_children_tenants = rated_children_tenants if rated_children_tenants else [tenant_id] # resources_usage_rate = storage.show_resource_rate(ck_utils.local2utc(begin), # ck_utils.local2utc(end), # rated_children_tenants, # resource_id, offset, limit) resources_usage_rate = storage.show_aggregated_resource_rate(ck_utils.local2utc(begin), ck_utils.local2utc(end), rated_children_tenants, resource_id) resources_usage_rate_list = [billing_models.CloudkittyResourceUsageRate(**resource_usage_rate) for resource_usage_rate in resources_usage_rate] return billing_models.CloudkittyResourceUsageRateList(resourcesUsageRate=resources_usage_rate_list)
def consumer_trends(self, counter_type='day', back=12, tenant_id=None): """Return the consumer trends for a tenant. """ policy.enforce(pecan.request.context, 'billing:get_consumer_trends', {}) storage = pecan.request.storage_backend subordinate_tenants = self.fetcher.get_subordinate_tenants(tenant_id) rated_tenants = [] for subordinate_tenant in subordinate_tenants: rated_tenants.extend(subordinate_tenant['rated_children_tenants']) consumer_trends_list = [] if counter_type == 'month': months = ck_utils.get_past_months(back) if time.localtime().tm_mday < cfg.CONF.collect.billing_month_start: months = ck_utils.get_past_months(back+1) months = months[:-1] for month in months: kwargs = {'billing_month': ck_utils.reformat_month_style(month)} total = storage.get_total(rated_tenants, True, **kwargs) consumer_trends_list.append(billing_models.CloudkittyConsumerTrends(time=month, cost=total)) elif counter_type == 'day': days = ck_utils.get_past_days(back) for day in days: day_slice = day.split('-') begin = datetime.datetime(int(day_slice[0]), int(day_slice[1]), int(day_slice[2]), 0, 0, 0) end = begin + datetime.timedelta(days=1) kwargs = {'begin': ck_utils.local2utc(begin), 'end': ck_utils.local2utc(end)} total = storage.get_total(rated_tenants, False, **kwargs) consumer_trends_list.append(billing_models.CloudkittyConsumerTrends(time=day, cost=total)) return billing_models.CloudkittyConsumerTrendsCollection(consumerTrends=consumer_trends_list)
def resources_cost(self, billing_month=None, tenant_id=None, service=None, offset=None, limit=None): """Return the amount to pay for each resource within a special service type. """ policy.enforce(pecan.request.context, 'billing:show_service_rate', {}) storage = pecan.request.storage_backend access_monthly_billing_table = ck_utils.access_monthly_billing_table(cfg.CONF.collect.billing_month_start, billing_month) if access_monthly_billing_table: kwargs={'billing_month': ck_utils.reformat_month_style(billing_month)} else: begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) kwargs={'begin': ck_utils.local2utc(begin), 'end': ck_utils.local2utc(end)} if offset>=0 and limit>=0: kwargs['offset'] = offset kwargs['limit'] = limit rated_children_tenants = [] self.fetcher.get_rated_subordinate_tenants(tenant_id, rated_children_tenants) rated_children_tenants = rated_children_tenants if rated_children_tenants else [tenant_id] resources_rate = storage.list_resource_rate(rated_children_tenants, service, access_monthly_billing_table, **kwargs) resources_rate_list = [] for resource_rate in resources_rate: try: raw_resource = self._conn.resources.get(resource_rate['resource_id']) except Exception: #should to be fix resource_rate['resource_name'] = resource_rate['resource_id'] resource_rate['status'] = 'deleted&cleared' resource_rate['unit_price'] = 0 resources_rate_list.append(billing_models.CloudkittyResourceRate(**resource_rate)) continue resource_info= self.t_ceilometer.strip_resource_data(resource_rate['res_type'], raw_resource) resource_rate['resource_name'] = resource_info['name'] #print resource_rate['resource_name'] resource_rate['status'] = resource_info['status'] if resource_info['created_time']: resource_rate['created_time'] = self._str2dt(resource_info['created_time']) if resource_rate['res_type'] == 'network.bw.total': raw_resource = self._conn.resources.get(resource_info['attached_instance_id']) attached_instance_info= self.t_ceilometer.strip_resource_data('compute', raw_resource) resource_rate['resource_name'] = '%s(%s)'%(resource_rate['resource_name'],attached_instance_info['name']) resource_rate['status'] = attached_instance_info['status'] resource_rate['created_time'] = self._str2dt(attached_instance_info['created_time']) resource_rate['unit_price'] = self._get_unit_price(resource_info, resource_rate['res_type']) resources_rate_list.append(billing_models.CloudkittyResourceRate(**resource_rate)) #return billing_models.CloudkittyResourceRateCollection.sample() return billing_models.CloudkittyResourceRateCollection(resourcesRate=resources_rate_list)
def generate_monthly_billing(): #print datetime.now() #print 'Monthly billing task is running. %s'%datetime.datetime.now() now = datetime.datetime.now() billing_month = '%s-%s'%(ck_utils.get_last_month(now).year, ck_utils.get_last_month(now).month) begin,end = ck_utils.get_billing_month_period(CONF.collect.billing_month_start, billing_month) storage.generate_monthly_billing(ck_utils.reformat_month_style(billing_month), ck_utils.local2utc(begin), ck_utils.local2utc(end),ck_utils.local2utc(end))
def resource_usage_cost_count(self, billing_month=None, tenant_id=None, resource_id=None): """Return the total number of the resource rate records, used together with show_resource_rate. """ policy.enforce(pecan.request.context, 'billing:count_resource_rate', {}) storage = pecan.request.storage_backend begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) rated_children_tenants = [] self.fetcher.get_rated_subordinate_tenants(tenant_id, rated_children_tenants) rated_children_tenants = rated_children_tenants if rated_children_tenants else [tenant_id] resources_usage_rate_count = storage.count_resource_rate_show(ck_utils.local2utc(begin), ck_utils.local2utc(end), rated_children_tenants, resource_id) return resources_usage_rate_count
def check_state(self): timestamp = self._storage.get_state(self._tenant_id) if not timestamp: month_start = ck_utils.local2utc(ck_utils.get_month_start()) return ck_utils.dt2ts(ck_utils.iso2dt(month_start)) now = ck_utils.utcnow_ts() if timestamp + self._period + self._wait_time < now: return timestamp return 0
def generate_daily_billing(): #print datetime.now() #print 'Daily billing task is running. %s' % datetime.datetime.now() now = datetime.datetime.now() billing_day_dt = now - datetime.timedelta(days=1) last_count = datetime.datetime(now.year, now.month, now.day, 0, 0, 0) billing_month = '%s-%s' % (billing_day_dt.year, billing_day_dt.month) if billing_day_dt.day < CONF.collect.billing_month_start: billing_month = '%s-%s' % ( ck_utils.get_last_month( billing_day_dt.now()).year, ck_utils.get_last_month( billing_day_dt.now()).month) begin, end = ck_utils.get_billing_month_period( CONF.collect.billing_month_start, billing_month) storage.generate_monthly_billing(ck_utils.reformat_month_style( billing_month), ck_utils.local2utc(begin), ck_utils.local2utc(end), ck_utils.local2utc(last_count))
def resources_cost_count(self, billing_month=None, tenant_id=None, service=None): """Return the amount to pay for each resource within a special service type. """ policy.enforce(pecan.request.context, 'billing:resource_rate_count', {}) storage = pecan.request.storage_backend access_monthly_billing_table = ck_utils.access_monthly_billing_table(cfg.CONF.collect.billing_month_start, billing_month) if access_monthly_billing_table: kwargs={'billing_month': ck_utils.reformat_month_style(billing_month)} else: begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) kwargs={'begin': ck_utils.local2utc(begin), 'end': ck_utils.local2utc(end)} rated_children_tenants = [] self.fetcher.get_rated_subordinate_tenants(tenant_id, rated_children_tenants) rated_children_tenants = rated_children_tenants if rated_children_tenants else [tenant_id] resources_rate_count = storage.count_resource_rate_list(rated_children_tenants, service, access_monthly_billing_table, **kwargs) return resources_rate_count
def aggregate_time_frame(self, begin, end, period_duration, begining_event_type, ending_event_type, tenant_id, unit, qty, res_type, rate, unit_price, resource_id, user_id, desc): """Aggregate a new time frame. """ billing_month = ck_utils.get_billing_month(CONF.collect.billing_month_start, begin) billing_month_begin, billing_month_end = ck_utils.get_billing_month_period(CONF.collect.billing_month_start, billing_month) if res_type == '_NO_DATA_' or begin < datetime.strptime(ck_utils.local2utc(billing_month_begin), "%Y-%m-%d %H:%M:%S"): return session = db.get_session() with session.begin() as transaction: try: results = session.query(models.AggregatedDataFrame ).filter(models.AggregatedDataFrame.resource_id == resource_id ).filter(models.AggregatedDataFrame.begin >= ck_utils.local2utc(billing_month_begin) ).filter(models.AggregatedDataFrame.end <= ck_utils.local2utc(billing_month_end) ).filter(models.AggregatedDataFrame.tenant_id == tenant_id).all() if (results and results[-1]['end'] == begin and begining_event_type == results[-1]['ending_event_type'] == 'period_cutting_event' and results[-1]['unit'] != 'unknown'): results[-1].update({'end': end, 'rate': models.AggregatedDataFrame.rate+rate, 'period_duration': models.AggregatedDataFrame.period_duration+period_duration, 'ending_event_type': ending_event_type}) else: frame = models.AggregatedDataFrame(begin=begin, end=end, period_duration=period_duration, begining_event_type=begining_event_type, ending_event_type=ending_event_type, tenant_id=tenant_id, unit=unit, qty=qty, res_type=res_type, rate=rate, unit_price=unit_price, resource_id=resource_id, user_id=user_id, desc=desc) session.add(frame) except exception as e: print e transaction.rollback()
def total(self, billing_month=None, tenant_id=None): """Return the amount to pay for a given billing month. """ policy.enforce(pecan.request.context, 'billing:get_total', {}) storage = pecan.request.storage_backend # FIXME(sheeprine): We should filter on user id. # Use keystone token information by default but make it overridable and # enforce it by policy engine access_monthly_billing_table = ck_utils.access_monthly_billing_table(cfg.CONF.collect.billing_month_start, billing_month) if access_monthly_billing_table: kwargs={'billing_month': ck_utils.reformat_month_style(billing_month)} else: begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) kwargs={'begin': ck_utils.local2utc(begin), 'end': ck_utils.local2utc(end)} subordinate_tenants = self.fetcher.get_subordinate_tenants(tenant_id) total_list=[] for subordinate_tenant in subordinate_tenants: total = storage.get_total(subordinate_tenant['rated_children_tenants'], access_monthly_billing_table, **kwargs) total_list.append(billing_models.CloudkittyTotal(tenant_id=subordinate_tenant['tenant_id'], tenant_name=subordinate_tenant['tenant_name'], org_name=subordinate_tenant['org_name'], cost=total)) return billing_models.CloudkittyTotalCollection(totals=total_list)
def services_cost(self, billing_month=None, tenant_id=None): """Return the amount to pay for a given period, group by service. """ policy.enforce(pecan.request.context, 'billing:get_services_rate', {}) storage = pecan.request.storage_backend access_monthly_billing_table = ck_utils.access_monthly_billing_table(cfg.CONF.collect.billing_month_start, billing_month) if access_monthly_billing_table: kwargs={'billing_month': ck_utils.reformat_month_style(billing_month)} else: begin, end = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, billing_month) kwargs={'begin': ck_utils.local2utc(begin), 'end': ck_utils.local2utc(end)} rated_children_tenants = [] self.fetcher.get_rated_subordinate_tenants(tenant_id, rated_children_tenants) rated_children_tenants = rated_children_tenants if rated_children_tenants else [tenant_id] services_rate = storage.list_service_rate(rated_children_tenants, access_monthly_billing_table, **kwargs) services_rate_list = [billing_models.CloudkittyServiceRate(**service_rate) for service_rate in services_rate] #return billing_models.CloudkittyServiceRateCollection.sample() return billing_models.CloudkittyServiceRateCollection(servicesRate=services_rate_list)