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

65 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
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):
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()
logs = []
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):
2015-04-09 14:32:10 +00:00
op = Operation(backend, obj, Operation.MONITOR)
monitorings.append(op)
2015-03-18 21:51:12 +00:00
# TODO async=True only when running with celery
# monitor.request.id
logs += 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):
2015-04-09 14:32:10 +00:00
op = Operation(backend, obj, Operation.EXCEEDED)
triggers.append(op)
elif data.used < (data.allocated or 0):
2015-04-09 14:32:10 +00:00
op = Operation(backend, obj, Operation.RECOVERY)
triggers.append(op)
Operation.execute(triggers)
return logs
2015-05-03 18:33:07 +00:00
from orchestra.contrib.tasks import task
import time, sys
@task(name='rata')
def counter(num, log):
for i in range(1, num):
with open(log, 'a') as handler:
handler.write(str(i))
# sys.stderr.write('hola\n')
time.sleep(1)
#counter.apply_async(10, '/tmp/kakas')