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

37 lines
1.4 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
2014-07-11 22:08:16 +00:00
elif resource.period == resource.MONTHLY_SUM:
# 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)
elif resource.period == resource.LAST:
result += dataset.value
2014-07-11 22:08:16 +00:00
has_result = True
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