django-orchestra/orchestra/apps/resources/helpers.py

34 lines
1.3 KiB
Python
Raw Normal View History

2014-07-11 22:08:16 +00:00
import datetime
2014-07-16 15:20:16 +00:00
def compute_resource_usage(data):
2014-07-11 22:08:16 +00:00
""" Computes MonitorData.used based on related monitors """
resource = data.resource
result = 0
has_result = False
2014-11-13 15:34:00 +00:00
for dataset in data.get_monitor_datasets():
2014-07-11 22:08:16 +00:00
if resource.period == resource.MONTHLY_AVG:
2014-11-13 15:34:00 +00:00
last = dataset.latest()
epoch = datetime(
year=today.year,
month=today.month,
day=1,
tzinfo=timezone.utc
)
2014-09-26 15:05:20 +00:00
total = (last.created_at-epoch).total_seconds()
ini = epoch
2014-07-11 22:08:16 +00:00
for data in dataset:
2014-09-26 15:05:20 +00:00
slot = (data.created_at-ini).total_seconds()
2014-07-11 22:08:16 +00:00
result += data.value * slot/total
2014-09-26 15:05:20 +00:00
ini = data.created_at
2015-03-18 21:51:12 +00:00
elif resource.period in (resource.MONTHLY_SUM, resource.LAST):
2014-07-11 22:08:16 +00:00
# FIXME Aggregation of 0s returns None! django bug?
# value = dataset.aggregate(models.Sum('value'))['value__sum']
values = dataset.values_list('value', flat=True)
if values:
has_result = True
result += sum(values)
else:
2014-09-22 15:59:53 +00:00
raise NotImplementedError("%s support not implemented" % data.period)
2014-10-27 13:29:02 +00:00
return float(result)/resource.get_scale() if has_result else None