def consumption_statistics(self, cnxt, user_id=None, filters=None, start_time=None, end_time=None, summary=False, project_safe=True): user_id = user_id or cnxt.project result = {} if start_time is None: start_time = 0 else: start_time = utils.format_time_to_seconds(start_time) start_time = utils.make_decimal(start_time) now_time = utils.format_time_to_seconds(timeutils.utcnow()) now_time = utils.make_decimal(now_time) if end_time is None: end_time = now_time else: end_time = utils.format_time_to_seconds(end_time) end_time = utils.make_decimal(end_time) consumptions = cons_mod.Consumption.load_all(cnxt, user_id=user_id, filters=filters, project_safe=project_safe) for cons in consumptions: if cons.start_time > end_time or cons.end_time < start_time: continue et = min(cons.end_time, end_time) st = max(cons.start_time, start_time) seconds = et - st cost = cons.rate * seconds if summary: if cons.resource_type not in result: result[cons.resource_type] = cost else: result[cons.resource_type] += cost else: if cons.resource_id not in result: tmp = {'resource_type': cons.resource_type, 'cost': cost} result[cons.resource_id] = tmp else: result[cons.resource_id]['cost'] += cost resources = plugin_base.Resource.load_all(cnxt, user_id=user_id, filters=filters, project_safe=project_safe) for res in resources: if res.last_bill > end_time or now_time < start_time: continue et = min(now_time, end_time) st = max(res.last_bill, start_time) seconds = et - st cost = res.rate * seconds if summary: if res.resource_type not in result: result[res.resource_type] = cost else: result[res.resource_type] += cost else: if res.id not in result: tmp = {'resource_type': res.resource_type, 'cost': cost} result[res.id] = tmp else: result[res.id]['cost'] += cost if summary: for key in six.iterkeys(result): result[key] = utils.dec2str(result[key]) return result else: consumptions = [] for key in six.iterkeys(result): consumption = cons_mod.Consumption( user_id, resource_id=key, resource_type=result[key]['resource_type'], cost=result[key]['cost'], start_time=start_time, end_time=end_time) consumptions.append(consumption.to_dict()) return consumptions