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

48 lines
1.8 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
2014-07-10 10:03:22 +00:00
from orchestra.apps.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')
2014-10-27 13:29:02 +00:00
def monitor(resource_id, ids=None):
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()
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
operations = []
# Execute monitor
2014-10-27 13:29:02 +00:00
for obj in model.objects.filter(**kwargs):
2014-07-10 10:03:22 +00:00
operations.append(Operation.create(backend, obj, Operation.MONITOR))
# TODO async=TRue only when running with celery
Operation.execute(operations, async=True)
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
operations = []
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):
2014-07-11 21:09:17 +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:
2014-11-17 14:17:33 +00:00
if data.used > data.allocated:
2014-07-11 21:09:17 +00:00
op = Operation.create(backend, obj, Operation.EXCEED)
2014-07-11 14:48:46 +00:00
operations.append(op)
2014-09-22 15:59:53 +00:00
elif data.used < data.allocated:
2014-07-11 21:09:17 +00:00
op = Operation.create(backend, obj, Operation.RECOVERY)
2014-09-26 15:05:20 +00:00
operations.append(op)
2014-07-10 10:03:22 +00:00
Operation.execute(operations)