Beispiel #1
0
    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 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))
Beispiel #3
0
    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)
Beispiel #4
0
    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()
Beispiel #5
0
    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 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 post(self, pricing_version):
        """Create a pricing version.

        :param pricing_version: Version about the pricing to create.
        """
        common_db = db_api.get_instance()
        pricing_version.effective_time = ck_utils.get_billing_month_period(cfg.CONF.collect.billing_month_start, 
                                                                                pricing_version.effective_billing_month)[0]
        year_month = pricing_version.effective_billing_month.split('-')
        if len(year_month[1]) == 1:
            year_month[1] = '0' + year_month[1]
        pricing_version.version = 'v'+year_month[0]+year_month[1]

        try:
            pricing_version_db = common_db.create_pricing_version(pricing_version)
            pecan.response.location = pecan.request.path_url
            if pecan.response.location[-1] != '/':
                pecan.response.location += '/'
            pecan.response.location += pricing_version_db['version']
            return pricing_models.PricingVer(**pricing_version_db)
        except db_api.PricingVersionAlreadyExists as e:
            pecan.abort(409, str(e))
Beispiel #8
0
    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
Beispiel #9
0
    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)
Beispiel #10
0
    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)