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

54 lines
2.2 KiB
Python
Raw Normal View History

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