django-orchestra-test/orchestra/apps/resources/models.py

210 lines
8.6 KiB
Python
Raw Normal View History

2014-07-08 15:19:15 +00:00
import datetime
from django.db import models
2014-07-11 21:09:17 +00:00
from django.db.models.loading import get_model
2014-07-10 15:19:06 +00:00
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
2014-07-08 15:19:15 +00:00
from django.contrib.contenttypes.models import ContentType
from django.core import validators
2014-07-11 21:09:17 +00:00
from django.utils import timezone
2014-07-08 15:19:15 +00:00
from django.utils.translation import ugettext_lazy as _
from djcelery.models import PeriodicTask, CrontabSchedule
2014-07-09 16:17:43 +00:00
from orchestra.models.fields import MultiSelectField
2014-07-11 21:09:17 +00:00
from orchestra.models.utils import get_model_field_path
2014-07-08 15:19:15 +00:00
from orchestra.utils.apps import autodiscover
2014-07-09 16:17:43 +00:00
from .backends import ServiceMonitor
2014-07-08 15:19:15 +00:00
class Resource(models.Model):
2014-07-09 16:17:43 +00:00
"""
Defines a resource, a resource is basically an interpretation of data
gathered by a Monitor
"""
LAST = 'LAST'
MONTHLY_SUM = 'MONTHLY_SUM'
MONTHLY_AVG = 'MONTHLY_AVG'
2014-07-08 15:19:15 +00:00
PERIODS = (
2014-07-09 16:17:43 +00:00
(LAST, _("Last")),
(MONTHLY_SUM, _("Monthly Sum")),
(MONTHLY_AVG, _("Monthly Average")),
2014-07-08 15:19:15 +00:00
)
name = models.CharField(_("name"), max_length=32, unique=True,
help_text=_('Required. 32 characters or fewer. Lowercase letters, '
'digits and hyphen only.'),
validators=[validators.RegexValidator(r'^[a-z0-9_\-]+$',
_('Enter a valid name.'), 'invalid')])
verbose_name = models.CharField(_("verbose name"), max_length=256, unique=True)
2014-07-10 15:19:06 +00:00
content_type = models.ForeignKey(ContentType,
help_text=_("Model where this resource will be hooked"))
2014-07-11 14:48:46 +00:00
period = models.CharField(_("period"), max_length=16, choices=PERIODS,
default=LAST,
help_text=_("Operation used for aggregating this resource monitored"
"data."))
2014-07-10 15:19:06 +00:00
ondemand = models.BooleanField(_("on demand"), default=False,
help_text=_("If enabled the resource will not be pre-allocated, "
"but allocated under the application demand"))
2014-07-09 16:17:43 +00:00
default_allocation = models.PositiveIntegerField(_("default allocation"),
2014-07-11 14:48:46 +00:00
null=True, blank=True,
2014-07-10 15:19:06 +00:00
help_text=_("Default allocation value used when this is not an "
2014-07-11 14:48:46 +00:00
"on demand resource"))
2014-07-09 16:17:43 +00:00
is_active = models.BooleanField(_("is active"), default=True)
2014-07-10 15:19:06 +00:00
disable_trigger = models.BooleanField(_("disable trigger"), default=False,
2014-07-11 14:48:46 +00:00
help_text=_("Disables monitors exeeded and recovery triggers"))
2014-07-10 10:03:22 +00:00
crontab = models.ForeignKey(CrontabSchedule, verbose_name=_("crontab"),
2014-07-11 14:48:46 +00:00
null=True, blank=True,
help_text=_("Crontab for periodic execution. "
"Leave it empty to disable periodic monitoring"))
monitors = MultiSelectField(_("monitors"), max_length=256, blank=True,
choices=ServiceMonitor.get_choices(),
help_text=_("Monitor backends used for monitoring this resource."))
2014-07-08 15:19:15 +00:00
def __unicode__(self):
return self.name
2014-07-10 10:03:22 +00:00
def save(self, *args, **kwargs):
super(Resource, self).save(*args, **kwargs)
# Create Celery periodic task
name = 'monitor.%s' % str(self)
try:
task = PeriodicTask.objects.get(name=name)
except PeriodicTask.DoesNotExist:
2014-07-10 15:19:06 +00:00
if self.is_active:
PeriodicTask.objects.create(name=name, task='resources.Monitor',
args=[self.pk], crontab=self.crontab)
else:
if not self.is_active:
task.delete()
elif task.crontab != self.crontab:
2014-07-10 10:03:22 +00:00
task.crontab = self.crontab
task.save()
2014-07-10 15:19:06 +00:00
2014-07-10 10:03:22 +00:00
def delete(self, *args, **kwargs):
super(Resource, self).delete(*args, **kwargs)
name = 'monitor.%s' % str(self)
PeriodicTask.objects.filter(name=name, task='resources.Monitor',
args=[self.pk]).delete()
2014-07-08 15:19:15 +00:00
@classmethod
def group_by_content_type(cls):
prev = None
group = []
2014-07-11 14:48:46 +00:00
resources = cls.objects.filter(is_active=True).order_by('content_type')
for resource in resources:
2014-07-08 15:19:15 +00:00
ct = resource.content_type
if prev != ct:
if group:
yield group
group = [resource]
else:
group.append(resource)
prev = ct
if group:
yield group
2014-07-10 10:03:22 +00:00
class ResourceData(models.Model):
""" Stores computed resource usage and allocation """
resource = models.ForeignKey(Resource, related_name='dataset')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
used = models.PositiveIntegerField(null=True)
last_update = models.DateTimeField(null=True)
2014-07-10 17:34:23 +00:00
allocated = models.PositiveIntegerField(null=True, blank=True)
2014-07-10 10:03:22 +00:00
2014-07-10 15:19:06 +00:00
content_object = GenericForeignKey()
2014-07-10 10:03:22 +00:00
class Meta:
unique_together = ('resource', 'content_type', 'object_id')
verbose_name_plural = _("resource data")
@classmethod
def get_or_create(cls, obj, resource):
2014-07-11 21:09:17 +00:00
ct = ContentType.objects.get_for_model(type(obj))
2014-07-10 10:03:22 +00:00
try:
2014-07-11 21:09:17 +00:00
return cls.objects.get(content_type=ct, object_id=obj.pk,
resource=resource)
except cls.DoesNotExist:
2014-07-10 10:03:22 +00:00
return cls.objects.create(content_object=obj, resource=resource,
2014-07-11 21:09:17 +00:00
allocated=resource.default_allocation)
2014-07-08 15:19:15 +00:00
2014-07-10 10:03:22 +00:00
def get_used(self):
resource = self.resource
2014-07-11 14:48:46 +00:00
today = timezone.now()
2014-07-08 15:19:15 +00:00
result = 0
has_result = False
2014-07-10 10:03:22 +00:00
for monitor in resource.monitors:
2014-07-11 21:09:17 +00:00
resource_model = self.content_type.model_class()
monitor_model = get_model(ServiceMonitor.get_backend(monitor).model)
if resource_model == monitor_model:
dataset = MonitorData.objects.filter(monitor=monitor,
content_type=self.content_type_id, object_id=self.object_id)
else:
path = get_model_field_path(monitor_model, resource_model)
fields = '__'.join(path)
objects = monitor_model.objects.filter(**{fields: self.object_id})
pks = objects.values_list('id', flat=True)
ct = ContentType.objects.get_for_model(monitor_model)
dataset = MonitorData.objects.filter(monitor=monitor,
content_type=ct, object_id__in=pks)
2014-07-10 10:03:22 +00:00
if resource.period == resource.MONTHLY_AVG:
2014-07-09 16:17:43 +00:00
try:
last = dataset.latest()
except MonitorData.DoesNotExist:
continue
has_result = True
2014-07-11 14:48:46 +00:00
epoch = datetime(year=today.year, month=today.month, day=1,
tzinfo=timezone.utc)
2014-07-09 16:17:43 +00:00
total = (epoch-last.date).total_seconds()
dataset = dataset.filter(date__year=today.year,
2014-07-11 21:09:17 +00:00
date__month=today.month)
2014-07-09 16:17:43 +00:00
for data in dataset:
slot = (previous-data.date).total_seconds()
result += data.value * slot/total
2014-07-10 10:03:22 +00:00
elif resource.period == resource.MONTHLY_SUM:
2014-07-11 21:09:17 +00:00
data = dataset.filter(date__year=today.year, date__month=today.month)
# FIXME Aggregation of 0s returns None! django bug?
# value = data.aggregate(models.Sum('value'))['value__sum']
values = data.values_list('value', flat=True)
if values:
2014-07-09 16:17:43 +00:00
has_result = True
2014-07-11 21:09:17 +00:00
result += sum(values)
2014-07-10 10:03:22 +00:00
elif resource.period == resource.LAST:
2014-07-09 16:17:43 +00:00
try:
result += dataset.latest().value
except MonitorData.DoesNotExist:
continue
has_result = True
2014-07-08 15:19:15 +00:00
else:
2014-07-11 14:48:46 +00:00
msg = "%s support not implemented" % self.period
raise NotImplementedError(msg)
2014-07-08 15:19:15 +00:00
return result if has_result else None
class MonitorData(models.Model):
2014-07-09 16:17:43 +00:00
""" Stores monitored data """
monitor = models.CharField(_("monitor"), max_length=256,
choices=ServiceMonitor.get_choices())
2014-07-08 15:19:15 +00:00
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
date = models.DateTimeField(auto_now_add=True)
value = models.PositiveIntegerField()
2014-07-10 15:19:06 +00:00
content_object = GenericForeignKey()
2014-07-08 15:19:15 +00:00
2014-07-09 16:17:43 +00:00
class Meta:
get_latest_by = 'date'
verbose_name_plural = _("monitor data")
2014-07-08 15:19:15 +00:00
def __unicode__(self):
return str(self.monitor)
2014-07-10 10:03:22 +00:00
def create_resource_relation():
2014-07-10 15:19:06 +00:00
relation = GenericRelation('resources.ResourceData')
2014-07-10 10:03:22 +00:00
for resources in Resource.group_by_content_type():
model = resources[0].content_type.model_class()
model.add_to_class('resources', relation)