django-orchestra-test/orchestra/contrib/resources/tasks.py

54 lines
1.9 KiB
Python
Raw Normal View History

2014-07-09 16:17:43 +00:00
from celery import shared_task
2014-07-11 21:09:17 +00:00
2015-04-05 10:46:24 +00:00
from orchestra.contrib.orchestration.models import BackendOperation as Operation
2014-10-27 13:29:02 +00:00
from orchestra.models.utils import get_model_field_path
2014-07-10 10:03:22 +00:00
2014-07-09 16:17:43 +00:00
from .backends import ServiceMonitor
2014-07-10 10:03:22 +00:00
@shared_task(name='resources.Monitor')
def monitor(resource_id, ids=None, async=True):
2014-10-27 13:29:02 +00:00
from .models import ResourceData, Resource
2014-07-10 10:03:22 +00:00
2014-10-27 13:29:02 +00:00
resource = Resource.objects.get(pk=resource_id)
resource_model = resource.content_type.model_class()
operations = []
2014-07-10 10:03:22 +00:00
# Execute monitors
for monitor_name in resource.monitors:
backend = ServiceMonitor.get_backend(monitor_name)
2014-11-14 16:12:56 +00:00
model = backend.model_class()
2014-10-27 13:29:02 +00:00
kwargs = {}
if ids:
path = get_model_field_path(model, resource_model)
path = '%s__in' % ('__'.join(path) or 'id')
kwargs = {
path: ids
}
2014-07-10 10:03:22 +00:00
# Execute monitor
monitorings = []
2014-10-27 13:29:02 +00:00
for obj in model.objects.filter(**kwargs):
op = Operation.create(backend, obj, Operation.MONITOR)
operations.append(op)
monitorings.append(op)
2015-03-18 21:51:12 +00:00
# TODO async=True only when running with celery
Operation.execute(monitorings, async=async)
2014-07-10 10:03:22 +00:00
2014-10-27 13:29:02 +00:00
kwargs = {'id__in': ids} if ids else {}
2014-07-10 10:03:22 +00:00
# Update used resources and trigger resource exceeded and revovery
triggers = []
2014-07-11 21:09:17 +00:00
model = resource.content_type.model_class()
2014-10-27 13:29:02 +00:00
for obj in model.objects.filter(**kwargs):
2015-04-01 15:49:21 +00:00
data, __ = ResourceData.get_or_create(obj, resource)
2014-09-22 15:59:53 +00:00
data.update()
2014-07-11 14:48:46 +00:00
if not resource.disable_trigger:
a = data.used
b = data.allocated
if data.used > (data.allocated or 0):
op = Operation.create(backend, obj, Operation.EXCEEDED)
triggers.append(op)
elif data.used < (data.allocated or 0):
2014-07-11 21:09:17 +00:00
op = Operation.create(backend, obj, Operation.RECOVERY)
triggers.append(op)
Operation.execute(triggers)
return operations