Beispiel #1
0
    def summary(self,
                begin=None,
                end=None,
                tenant_id=None,
                service=None,
                groupby=None,
                all_tenants=False):
        """Return the summary to pay for a given period.

        """
        if not begin:
            begin = ck_utils.get_month_start()
        if not end:
            end = ck_utils.get_next_month()

        if all_tenants:
            tenant_id = None
        else:
            tenant_context = pecan.request.context.tenant
            tenant_id = tenant_context if not tenant_id else tenant_id
        policy.enforce(pecan.request.context, 'report:get_summary',
                       {"tenant_id": tenant_id})
        storage = pecan.request.storage_backend

        summarymodels = []
        results = storage.get_total(begin,
                                    end,
                                    tenant_id,
                                    service,
                                    groupby=groupby)
        for result in results:
            summarymodel = report_models.SummaryModel(**result)
            summarymodels.append(summarymodel)

        return report_models.SummaryCollectionModel(summary=summarymodels)
Beispiel #2
0
    def _route(self, args, request):
        try:
            policy.enforce(request.context, 'rating:module_config', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        return super(RatingRestControllerBase, self)._route(args, request)
Beispiel #3
0
    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)
Beispiel #4
0
    def update_invoice(self,
                       invoice_id,
                       total_cost=None,
                       paid_cost=None,
                       balance_cost=None,
                       payment_status=None):
        """
        update the invoice details
        """

        try:
            policy.enforce(pecan.request.context, 'report:update_invoice', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # for admin tenant
        if 'admin' in roles:

            # invoice details
            invoice = storage.update_invoice(invoice_id, total_cost, paid_cost,
                                             balance_cost, payment_status)
        return invoice
Beispiel #5
0
    def list_month_report(self,tenant_id=None,billing_month=None):
        """ Return the month-report of this year

        """
        policy.enforce(pecan.request.context, 'report:list_month_report', {})
        storage = pecan.request.storage_backend
        month_filters = ck_utils.month2str(billing_month)
        subordinate_tenants = self.fetcher.get_subordinate_tenants(tenant_id)
        departs = []
        for subordinate_tenant in subordinate_tenants:
            depart = {}
            entry_all = storage.get_month_report(month_filters,subordinate_tenant['rated_children_tenants'])
            month_reports = []
            for month in month_filters:
                month_report = {}
                res_types = []
                for entry in entry_all:
                    res_type = {}
                    if entry.billing_month == month:
                        res_type['res_type'] = entry.res_type
                        res_type['qty'] = entry.qty
                        res_type['rate'] = entry.rate
                        res_types.append(res_type)
                if res_types:
                    format_month = datetime.datetime.strftime(datetime.datetime.strptime(month,'%Y%m'),'%Y-%m')
                    month_report['month'] = format_month
                    month_report['res_types'] = res_types
                    month_reports.append(month_report)
            depart['month_reports'] = month_reports
            depart['tenant_id'] = subordinate_tenant['tenant_id']
            depart['tenant_name'] = subordinate_tenant['tenant_name']
            departs.append(depart)
        report_dict = {}
        report_dict['departs'] = departs
        return report_dict
Beispiel #6
0
    def list_resource_rate(self, begin=None, end=None, tenant_id=None, service=None):
        """Return the amount to pay for each resource within a special service type.

        """
        policy.enforce(pecan.request.context, 'report:show_service_rate', {})
        storage = pecan.request.storage_backend
        resources_rate = storage.list_resource_rate(begin, end, tenant_id, service)
        resources_rate_list = []
        for resource_rate in resources_rate:
            raw_resource = self._conn.resources.get(resource_rate['resource_id'])
            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'])
                
            resources_rate_list.append(report_models.CloudkittyResourceRate(**resource_rate))
            
        #return report_models.CloudkittyResourceRateCollection.sample()
        return report_models.CloudkittyResourceRateCollection(resourcesRate=resources_rate_list)
Beispiel #7
0
    def add_invoice(self, invoice_id, invoice_date, invoice_period_from,
                    invoice_period_to, tenant_id, invoice_data, tenant_name,
                    total_cost, paid_cost, balance_cost, payment_status):
        """Add the Invoice details.
        """

        try:
            policy.enforce(pecan.request.context, 'report:add_invoice', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # for admin tenant
        if 'admin' in roles:

            # invoice details
            invoice = storage.add_invoice(invoice_id, invoice_date,
                                          invoice_period_from,
                                          invoice_period_to, tenant_id,
                                          invoice_data, tenant_name,
                                          total_cost, paid_cost, balance_cost,
                                          payment_status)
Beispiel #8
0
    def _route(self, args, request):
        try:
            policy.enforce(request.context, 'rating:module_config', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        return super(RatingRestControllerBase, self)._route(args, request)
Beispiel #9
0
    def list_invoice(self, all_tenants=None):
        """Return the Invoice details.

        """
        policy.enforce(pecan.request.context, 'report:list_invoice', {})
        storage = pecan.request.storage_backend
        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # fetch tenant name
        tenant_name = pecan.request.context.__dict__['tenant']

        # for admin tenant
        if 'admin' in roles:
            invoice = storage.list_invoice(tenant_name, all_tenants)

        # For producing result for non-admin tenant if all-tenants arg not used
        elif 'admin' not in roles and all_tenants is None:
            invoice = storage.list_invoice(tenant_name, all_tenants)

        # For non-admin tenant to restrict the use of all-tenants arg
        elif 'admin' not in roles and all_tenants is not None:
            pecan.abort(403, six.text_type())

        return invoice
Beispiel #10
0
    def list_invoice(self, all_tenants=None):
        """Return the Invoice details.

        """
        policy.enforce(pecan.request.context, 'report:list_invoice', {})
        storage = pecan.request.storage_backend
        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # fetch tenant name
        tenant_name = pecan.request.context.__dict__['tenant']

        # for admin tenant
        if 'admin' in roles:
                invoice = storage.list_invoice(tenant_name, all_tenants)

        # For producing result for non-admin tenant if all-tenants arg not used
        elif 'admin' not in roles and all_tenants is None:
                invoice = storage.list_invoice(tenant_name, all_tenants)

        # For non-admin tenant to restrict the use of all-tenants arg
        elif 'admin' not in roles and all_tenants is not None:
                pecan.abort(403, six.text_type())

        return invoice
Beispiel #11
0
    def total(self,
              begin=None,
              end=None,
              tenant_id=None,
              service=None,
              all_tenants=False):
        """Return the amount to pay for a given period.

        """
        if not begin:
            begin = ck_utils.get_month_start()
        if not end:
            end = ck_utils.get_next_month()

        if all_tenants:
            tenant_id = None
        else:
            tenant_context = pecan.request.context.tenant
            tenant_id = tenant_context if not tenant_id else tenant_id
        policy.enforce(pecan.request.context, 'report:get_total',
                       {"tenant_id": tenant_id})

        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
        total = storage.get_total(begin, end, tenant_id, service)

        # TODO(Aaron): `get_total` return a list of dict,
        # Get value of rate from index[0]
        total = total[0].get('rate', decimal.Decimal('0'))
        return total if total else decimal.Decimal('0')
Beispiel #12
0
    def add_invoice(self, invoice_id, invoice_date, invoice_period_from, invoice_period_to, tenant_id, invoice_data, tenant_name, total_cost, paid_cost, balance_cost, payment_status ):
        """Add the Invoice details.
        """

        try:
            policy.enforce(pecan.request.context, 'report:add_invoice', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # for admin tenant
        if 'admin' in roles:

                # invoice details
                invoice = storage.add_invoice(invoice_id, 
                                              invoice_date, 
                                              invoice_period_from, 
                                              invoice_period_to, 
                                              tenant_id, 
                                              invoice_data, 
                                              tenant_name, 
                                              total_cost, 
                                              paid_cost, 
                                              balance_cost, 
                                              payment_status)
Beispiel #13
0
    def update_invoice(self, invoice_id, total_cost=None, paid_cost=None, balance_cost=None, payment_status=None ):
        """
        update the invoice details
        """

        try:
            policy.enforce(pecan.request.context, 'report:update_invoice', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # for admin tenant
        if 'admin' in roles:

                # invoice details
                invoice = storage.update_invoice(invoice_id,
                                              total_cost,
                                              paid_cost,
                                              balance_cost,
                                              payment_status)
        return invoice
Beispiel #14
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)
Beispiel #15
0
    def get_all(self):
        """Return the list of every services mapped.

        :return: List of every services mapped.
        """
        policy.enforce(pecan.request.context, 'collector:list_mappings', {})
        return [mapping.service for mapping in self._db.list_services()]
Beispiel #16
0
    def reload_modules(self):
        """Trigger a rating module list reload.

        """
        policy.enforce(pecan.request.context, 'rating:module_config', {})
        self.modules.reload_extensions()
        self.module_config.reload_extensions()
        self.module_config.expose_modules()
Beispiel #17
0
    def reload_modules(self):
        """Trigger a rating module list reload.

        """
        policy.enforce(pecan.request.context, 'rating:module_config', {})
        self.modules.reload_extensions()
        self.module_config.reload_extensions()
        self.module_config.expose_modules()
Beispiel #18
0
    def tenants(self, begin=None, end=None):
        """Return the list of rated tenants.

        """
        policy.enforce(pecan.request.context, 'report:list_tenants', {})
        storage = pecan.request.storage_backend
        tenants = storage.get_tenants(begin, end)
        return tenants
Beispiel #19
0
    def tenants(self, begin=None, end=None):
        """Return the list of rated tenants.

        """
        policy.enforce(pecan.request.context, 'report:list_tenants', {})
        storage = pecan.request.storage_backend
        tenants = storage.get_tenants(begin, end)
        return tenants
Beispiel #20
0
    def state(self, collector):
        """Query the enable state of a collector.

        :param collector: Name of the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:get_state', {})
        return self._db.get_state('collector_{}'.format(collector))
Beispiel #21
0
    def post_state(self, collector, state):
        """Set the enable state of a collector.

        :param collector: Name of the collector.
        :param state: New state for the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:update_state', {})
        return self._db.set_state('collector_{}'.format(collector), state)
Beispiel #22
0
    def post(self, collector, service):
        """Create a service to collector mapping.

        :param collector: Name of the collector to apply mapping on.
        :param service: Name of the service to apply mapping on.
        """
        policy.enforce(pecan.request.context, 'collector:manage_mapping', {})
        new_mapping = self._db.set_mapping(service, collector)
        return collector_models.ServiceToCollectorMapping(
            service=new_mapping.service, collector=new_mapping.collector)
Beispiel #23
0
    def delete(self, service):
        """Delete a service to collector mapping.

        :param service: Name of the service to filter on.
        """
        policy.enforce(pecan.request.context, 'collector:manage_mapping', {})
        try:
            self._db.delete_mapping(service)
        except db_api.NoSuchMapping as e:
            pecan.abort(400, six.text_type(e))
Beispiel #24
0
    def get_one(self, service):
        """Return a service to collector mapping.

        :param service: Name of the service to filter on.
        """
        policy.enforce(pecan.request.context, 'collector:get_mapping', {})
        try:
            return self._db.get_mapping(service)
        except db_api.NoSuchMapping as e:
            pecan.abort(400, str(e))
Beispiel #25
0
    def get(self, name):
        """Query the enable state of a collector.

        :param name: Name of the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:get_state', {})
        enabled = self._db.get_state('collector_{}'.format(name))
        collector = collector_models.CollectorInfos(name=name, enabled=enabled)
        return collector
Beispiel #26
0
    def count_resource_rate(self, begin=None, end=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, 'report:count_resource_rate', {})
        
        storage = pecan.request.storage_backend
        resources_usage_rate_count = storage.count_resource_rate(begin, end, tenant_id, resource_id)
        
        return resources_usage_rate_count
Beispiel #27
0
    def delete(self, service):
        """Delete a service to collector mapping.

        :param service: Name of the service to filter on.
        """
        policy.enforce(pecan.request.context, 'collector:manage_mapping', {})
        try:
            self._db.delete_mapping(service)
        except db_api.NoSuchMapping as e:
            pecan.abort(404, six.text_type(e))
Beispiel #28
0
    def get(self, name):
        """Query the enable state of a collector.

        :param name: Name of the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:get_state', {})
        enabled = self._db.get_state('collector_{}'.format(name))
        collector = collector_models.CollectorInfos(name=name,
                                                    enabled=enabled)
        return collector
Beispiel #29
0
    def show_resource_rate(self, begin=None, end=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, 'report:show_resource_rate', {})
        
        storage = pecan.request.storage_backend
        resources_usage_rate = storage.show_resource_rate(begin, end, tenant_id, resource_id, offset, limit)
        resources_usage_rate_list = [report_models.CloudkittyResourceUsageRate(**resource_usage_rate) for resource_usage_rate in resources_usage_rate]
        
        return report_models.CloudkittyResourceUsageRateList(resourcesUsageRate=resources_usage_rate_list)
Beispiel #30
0
    def list_service_rate(self, begin=None, end=None, tenant_id=None):
        """Return the amount to pay for a given period, group by service.

        """
        policy.enforce(pecan.request.context, 'report:list_service_rate', {})
        storage = pecan.request.storage_backend
        services_rate = storage.list_service_rate(begin, end, tenant_id)
        services_rate_list = [report_models.CloudkittyServiceRate(**service_rate) for service_rate in services_rate]
            
        #return report_models.CloudkittyServiceRateCollection.sample()
        return report_models.CloudkittyServiceRateCollection(servicesRate=services_rate_list)
Beispiel #31
0
    def total(self, begin=None, end=None, tenant_id=None, service=None):
        """Return the amount to pay for a given period.

        """
        policy.enforce(pecan.request.context, 'report: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
        total = storage.get_total(begin, end, tenant_id, service)
        return total if total else decimal.Decimal('0')
Beispiel #32
0
    def invoice(self,
                tenant_id=None,
                tenant_name=None,
                invoice_id=None,
                payment_status=None):
        """Return the Invoice details.

        """

        # assigning a tenant_name to another variable tenant
        # We already have variable named tenant for making decision on type of user and actions
        # So assigning a new name as tenant
        tenant = tenant_name

        policy.enforce(pecan.request.context, 'report:invoice', {})
        storage = pecan.request.storage_backend

        # role of tenant
        roles = pecan.request.context.__dict__['roles']

        # fetch tenant name
        tenant_name = pecan.request.context.__dict__['tenant']

        # If tenant_id or invoice_id or payment_status exists
        if tenant_id or invoice_id or payment_status or tenant_name:

            # if admin role
            if 'admin' in roles:

                # added facility for fetch using tenant name from user input also
                invoice = storage.get_invoice(tenant_id, tenant, invoice_id,
                                              payment_status)

            # for non-admin roles
            else:

                # for restricting non-admin users to use tenant-name and tenant-id options
                if not (tenant or tenant_id):

                    # Added facility for fetch using tenant name too
                    invoice = storage.get_invoice_for_tenant(
                        tenant_name, invoice_id, payment_status)

                # for generating a warning message if tenant_id arg passed for non-admin
                else:

                    pecan.abort(405, six.text_type())

        # for generating the warning message that invoice-get not supported
        else:

            pecan.abort(405, six.text_type())

        return invoice
Beispiel #33
0
    def post(self, collector, service):
        """Create a service to collector mapping.

        :param collector: Name of the collector to apply mapping on.
        :param service: Name of the service to apply mapping on.
        """
        policy.enforce(pecan.request.context, 'collector:manage_mapping', {})
        new_mapping = self._db.set_mapping(service, collector)
        return collector_models.ServiceToCollectorMapping(
            service=new_mapping.service,
            collector=new_mapping.collector)
Beispiel #34
0
    def total(self, begin=None, end=None, tenant_id=None, service=None):
        """Return the amount to pay for a given period.

        """
        policy.enforce(pecan.request.context, 'report: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
        total = storage.get_total(begin, end, tenant_id, service)
        return total if total else decimal.Decimal('0')
Beispiel #35
0
    def get_all(self, collector=None):
        """Return the list of every services mapped to a collector.

        :param collector: Filter on the collector name.
        :return: Service to collector mappings collection.
        """
        policy.enforce(pecan.request.context, 'collector:list_mappings', {})
        mappings = [collector_models.ServiceToCollectorMapping(
            **mapping.as_dict())
            for mapping in self._db.list_mappings(collector)]
        return collector_models.ServiceToCollectorMappingCollection(
            mappings=mappings)
Beispiel #36
0
    def get_one(self, service):
        """Return a service to collector mapping.

        :param service: Name of the service to filter on.
        """
        policy.enforce(pecan.request.context, 'collector:get_mapping', {})
        try:
            mapping = self._db.get_mapping(service)
            return collector_models.ServiceToCollectorMapping(
                **mapping.as_dict())
        except db_api.NoSuchMapping as e:
            pecan.abort(400, six.text_type(e))
Beispiel #37
0
    def put(self, name, infos):
        """Set the enable state of a collector.

        :param name: Name of the collector.
        :param infos: New state informations of the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:update_state', {})
        enabled = self._db.set_state('collector_{}'.format(name),
                                     infos.enabled)
        collector = collector_models.CollectorInfos(name=name, enabled=enabled)
        return collector
Beispiel #38
0
    def get_one(self, service):
        """Return a service to collector mapping.

        :param service: Name of the service to filter on.
        """
        policy.enforce(pecan.request.context, 'collector:get_mapping', {})
        try:
            mapping = self._db.get_mapping(service)
            return collector_models.ServiceToCollectorMapping(
                **mapping.as_dict())
        except db_api.NoSuchMapping as e:
            pecan.abort(404, six.text_type(e))
Beispiel #39
0
    def get_one(self, service_name):
        """Return a service.

        :param service_name: name of the service.
        """
        policy.enforce(pecan.request.context, 'info:get_service_info', {})
        try:
            info = METADATA[service_name].copy()
            info['service_id'] = service_name
            return info_models.CloudkittyServiceInfo(**info)
        except KeyError:
            pecan.abort(404, six.text_type(service_name))
Beispiel #40
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 #41
0
    def put(self, name, infos):
        """Set the enable state of a collector.

        :param name: Name of the collector.
        :param infos: New state informations of the collector.
        :return: State of the collector.
        """
        policy.enforce(pecan.request.context, 'collector:update_state', {})
        enabled = self._db.set_state('collector_{}'.format(name),
                                     infos.enabled)
        collector = collector_models.CollectorInfos(name=name,
                                                    enabled=enabled)
        return collector
Beispiel #42
0
    def tenants(self, begin=None, end=None):
        """Return the list of rated tenants.

        """
        policy.enforce(pecan.request.context, 'report:list_tenants', {})

        if not begin:
            begin = ck_utils.get_month_start()
        if not end:
            end = ck_utils.get_next_month()

        storage = pecan.request.storage_backend
        tenants = storage.get_tenants(begin, end)
        return tenants
Beispiel #43
0
    def get_all(self, begin=None, end=None, tenant_id=None,
                resource_type=None):
        """Return a list of rated resources for a time period and a tenant.

        :param begin: Start of the period
        :param end: End of the period
        :param tenant_id: UUID of the tenant to filter on.
        :param resource_type: Type of the resource to filter on.
        :return: Collection of DataFrame objects.
        """

        policy.enforce(pecan.request.context, 'storage:list_data_frames', {})

        if not begin:
            begin = ck_utils.get_month_start()
        if not end:
            end = ck_utils.get_next_month()

        begin_ts = ck_utils.dt2ts(begin)
        end_ts = ck_utils.dt2ts(end)
        backend = pecan.request.storage_backend
        dataframes = []
        try:
            frames = backend.get_time_frame(begin_ts,
                                            end_ts,
                                            tenant_id=tenant_id,
                                            res_type=resource_type)
            for frame in frames:
                for service, data_list in frame['usage'].items():
                    frame_tenant = None
                    resources = []
                    for data in data_list:
                        desc = data['desc'] if data['desc'] else {}
                        price = decimal.Decimal(str(data['rating']['price']))
                        resource = storage_models.RatedResource(
                            service=service,
                            desc=desc,
                            volume=data['vol']['qty'],
                            rating=price)
                        frame_tenant = data['tenant_id']
                        resources.append(resource)
                    dataframe = storage_models.DataFrame(
                        begin=ck_utils.iso2dt(frame['period']['begin']),
                        end=ck_utils.iso2dt(frame['period']['end']),
                        tenant_id=frame_tenant,
                        resources=resources)
                    dataframes.append(dataframe)
        except ck_storage.NoTimeFrame:
            pass
        return storage_models.DataFrameCollection(dataframes=dataframes)
Beispiel #44
0
    def get_one(self, module_id):
        """return a module

        :return: CloudKittyModule
        """
        policy.enforce(pecan.request.context, 'rating:get_module', {})

        try:
            module = self.extensions[module_id]
        except KeyError:
            pecan.abort(404, 'Module not found.')
        infos = module.obj.module_info.copy()
        infos['module_id'] = infos.pop('name')
        return rating_models.CloudkittyModule(**infos)
Beispiel #45
0
    def get_all(self):
        """Get the service list.

        :return: List of every services.
        """
        policy.enforce(pecan.request.context, 'info:list_services_info', {})
        services_info_list = []
        for service, metadata in METADATA.items():
            info = metadata.copy()
            info['service_id'] = service
            services_info_list.append(
                info_models.CloudkittyServiceInfo(**info))
        return info_models.CloudkittyServiceInfoCollection(
            services=services_info_list)
Beispiel #46
0
    def invoice(self, tenant_id=None, tenant_name=None, invoice_id=None, payment_status=None):
        """Return the Invoice details.

        """

	# assigning a tenant_name to another variable tenant
	# We already have variable named tenant for making decision on type of user and actions
	# So assigning a new name as tenant
	tenant = tenant_name

        policy.enforce(pecan.request.context, 'report:invoice', {})
        storage = pecan.request.storage_backend

        # role of tenant
        roles = pecan.request.context.__dict__['roles']

        # fetch tenant name
        tenant_name = pecan.request.context.__dict__['tenant']

        # If tenant_id or invoice_id or payment_status exists
        if tenant_id or invoice_id or payment_status or tenant_name:

                # if admin role
                if 'admin' in roles:

			# added facility for fetch using tenant name from user input also
                        invoice = storage.get_invoice(tenant_id, tenant, invoice_id, payment_status)

                # for non-admin roles
                else:

                        # for restricting non-admin users to use tenant-name and tenant-id options
                        if not (tenant or tenant_id):

				# Added facility for fetch using tenant name too
                                invoice = storage.get_invoice_for_tenant(tenant_name, invoice_id, payment_status)

                        # for generating a warning message if tenant_id arg passed for non-admin
                        else:

                                pecan.abort(405, six.text_type())

        # for generating the warning message that invoice-get not supported
        else:

                pecan.abort(405, six.text_type())


        return invoice
Beispiel #47
0
    def get_all(self):
        """return the list of loaded modules.

        :return: name of every loaded modules.
        """
        policy.enforce(pecan.request.context, 'rating:list_modules', {})

        modules_list = []
        for module in self.extensions:
            infos = module.obj.module_info.copy()
            infos['module_id'] = infos.pop('name')
            modules_list.append(rating_models.CloudkittyModule(**infos))

        return rating_models.CloudkittyModuleCollection(
            modules=modules_list)
Beispiel #48
0
    def get_one(self, module_id):
        """return a module

        :return: CloudKittyModule
        """
        policy.enforce(pecan.request.context, 'rating:get_module', {})

        try:
            lock = lockutils.lock('rating-modules')
            with lock:
                module = self.extensions[module_id]
        except KeyError:
            pecan.abort(400, 'Module not found.')
        infos = module.obj.module_info.copy()
        infos['module_id'] = infos.pop('name')
        return rating_models.CloudkittyModule(**infos)
Beispiel #49
0
    def get_all(self):
        """return the list of loaded modules.

        :return: name of every loaded modules.
        """
        policy.enforce(pecan.request.context, 'rating:list_modules', {})

        modules_list = []
        lock = lockutils.lock('rating-modules')
        with lock:
            for module in self.extensions:
                infos = module.obj.module_info.copy()
                infos['module_id'] = infos.pop('name')
                modules_list.append(rating_models.CloudkittyModule(**infos))

        return rating_models.CloudkittyModuleCollection(modules=modules_list)
Beispiel #50
0
    def put(self, module_id, module):
        """Change the state and priority of a module.

        :param module_id: name of the module to modify
        :param module: CloudKittyModule object describing the new desired state
        """
        policy.enforce(pecan.request.context, 'rating:update_module', {})

        try:
            ext = self.extensions[module_id].obj
        except KeyError:
            pecan.abort(404, 'Module not found.')
        if ext.enabled != module.enabled:
            ext.set_state(module.enabled)
        if ext.priority != module.priority:
            ext.set_priority(module.priority)
        pecan.response.location = pecan.request.path
Beispiel #51
0
    def quote(self, res_data):
        """Get an instant quote based on multiple resource descriptions.

        :param res_data: List of resource descriptions.
        :return: Total price for these descriptions.
        """
        policy.enforce(pecan.request.context, 'rating:quote', {})

        client = pecan.request.rpc_client.prepare(namespace='rating')
        res_dict = {}
        for res in res_data.resources:
            if res.service not in res_dict:
                res_dict[res.service] = []
            json_data = res.to_json()
            res_dict[res.service].extend(json_data[res.service])

        res = client.call({}, 'quote', res_data=[{'usage': res_dict}])
        return res
Beispiel #52
0
    def quote(self, res_data):
        """Get an instant quote based on multiple resource descriptions.

        :param res_data: List of resource descriptions.
        :return: Total price for these descriptions.
        """
        policy.enforce(pecan.request.context, 'rating:quote', {})

        client = pecan.request.rpc_client.prepare(namespace='rating')
        res_dict = {}
        for res in res_data.resources:
            if res.service not in res_dict:
                res_dict[res.service] = []
            json_data = res.to_json()
            res_dict[res.service].extend(json_data[res.service])

        res = client.call({}, 'quote', res_data=[{'usage': res_dict}])
        return res
Beispiel #53
0
    def put(self, module_id, module):
        """Change the state and priority of a module.

        :param module_id: name of the module to modify
        :param module: CloudKittyModule object describing the new desired state
        """
        policy.enforce(pecan.request.context, 'rating:update_module', {})

        try:
            lock = lockutils.lock('rating-modules')
            with lock:
                ext = self.extensions[module_id].obj
        except KeyError:
            pecan.abort(404, 'Module not found.')
        if module.enabled != wtypes.Unset and ext.enabled != module.enabled:
            ext.set_state(module.enabled)
        if module.priority != wtypes.Unset and ext.priority != module.priority:
            ext.set_priority(module.priority)
        pecan.response.location = pecan.request.path
Beispiel #54
0
    def delete_invoice(self, invoice_id):
        """
        delete the invoice
        """

        try:
            policy.enforce(pecan.request.context, 'report:delete_invoice', {})
        except policy.PolicyNotAuthorized as e:
            pecan.abort(403, six.text_type(e))

        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # for admin tenant
        if 'admin' in roles:

            # invoice details
            invoice = storage.delete_invoice(invoice_id)
Beispiel #55
0
    def show_invoice(self, invoice_id):
        """Return the Invoice details.

        """
        policy.enforce(pecan.request.context, 'report:show_invoice', {})
        storage = pecan.request.storage_backend

        # Fetch the user role
        roles = pecan.request.context.__dict__['roles']

        # fetch tenant name
        tenant_name = pecan.request.context.__dict__['tenant']

        # for admin tenant
        if 'admin' in roles:
            invoice = storage.show_invoice(invoice_id)

        # For producing result for non-admin tenant
        elif 'admin' not in roles:
            invoice = storage.show_invoice_for_tenant(tenant_name, invoice_id)

        return invoice
Beispiel #56
0
 def config(self):
     """Return current configuration."""
     policy.enforce(pecan.request.context, 'info:get_config', {})
     info = {}
     info["collect"] = {key: value for key, value in CONF.collect.items()}
     return info
Beispiel #57
0
    def route(self, *args):
        route = args[0]
        if route.startswith('/v1/module_config'):
            policy.enforce(pecan.request.context, 'rating:module_config', {})

        super(ModulesController, self).route(*args)