2018-12-10 02:11:54 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2019-01-15 02:23:30 +00:00
|
|
|
import os
|
2019-02-13 07:55:11 +00:00
|
|
|
import re
|
2024-01-18 07:28:13 +00:00
|
|
|
from collections import defaultdict
|
2019-02-13 07:55:11 +00:00
|
|
|
|
2023-01-31 03:00:21 +00:00
|
|
|
from celery.result import AsyncResult
|
2022-10-25 12:02:23 +00:00
|
|
|
from django.shortcuts import get_object_or_404
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2019-12-05 07:09:25 +00:00
|
|
|
from django_celery_beat.models import PeriodicTask
|
2023-12-12 06:18:26 +00:00
|
|
|
from django_filters import rest_framework as drf_filters
|
2023-05-16 06:48:00 +00:00
|
|
|
from rest_framework import generics, viewsets, mixins, status
|
2023-02-06 11:16:24 +00:00
|
|
|
from rest_framework.response import Response
|
|
|
|
|
2023-05-16 06:48:00 +00:00
|
|
|
from common.api import LogTailApi, CommonApiMixin
|
2023-12-12 06:18:26 +00:00
|
|
|
from common.drf.filters import BaseFilterSet
|
2023-02-16 07:52:21 +00:00
|
|
|
from common.exceptions import JMSException
|
2022-02-17 12:13:31 +00:00
|
|
|
from common.permissions import IsValidUser
|
2023-12-12 06:18:26 +00:00
|
|
|
from common.utils.timezone import local_now
|
2023-02-06 11:16:24 +00:00
|
|
|
from ops.celery import app
|
2020-12-29 13:05:18 +00:00
|
|
|
from ..ansible.utils import get_ansible_task_log_path
|
2023-05-16 06:48:00 +00:00
|
|
|
from ..celery.utils import get_celery_task_log_path
|
|
|
|
from ..models import CeleryTaskExecution, CeleryTask
|
2023-01-31 03:00:21 +00:00
|
|
|
from ..serializers import CeleryResultSerializer, CeleryPeriodTaskSerializer
|
|
|
|
from ..serializers.celery import CeleryTaskSerializer, CeleryTaskExecutionSerializer
|
2018-12-10 02:11:54 +00:00
|
|
|
|
2020-12-29 13:05:18 +00:00
|
|
|
__all__ = [
|
2022-10-24 12:14:18 +00:00
|
|
|
'CeleryTaskExecutionLogApi', 'CeleryResultApi', 'CeleryPeriodTaskViewSet',
|
|
|
|
'AnsibleTaskLogApi', 'CeleryTaskViewSet', 'CeleryTaskExecutionViewSet'
|
2020-12-29 13:05:18 +00:00
|
|
|
]
|
2018-12-10 02:11:54 +00:00
|
|
|
|
|
|
|
|
2022-10-24 12:14:18 +00:00
|
|
|
class CeleryTaskExecutionLogApi(LogTailApi):
|
2018-12-10 02:11:54 +00:00
|
|
|
permission_classes = (IsValidUser,)
|
2019-01-15 02:23:30 +00:00
|
|
|
task = None
|
|
|
|
task_id = ''
|
2019-02-13 07:55:11 +00:00
|
|
|
pattern = re.compile(r'Task .* succeeded in \d+\.\d+s.*')
|
2018-12-10 02:11:54 +00:00
|
|
|
|
|
|
|
def get(self, request, *args, **kwargs):
|
2019-01-15 02:23:30 +00:00
|
|
|
self.task_id = str(kwargs.get('pk'))
|
|
|
|
self.task = AsyncResult(self.task_id)
|
|
|
|
return super().get(request, *args, **kwargs)
|
|
|
|
|
2019-02-13 07:55:11 +00:00
|
|
|
def filter_line(self, line):
|
|
|
|
if self.pattern.match(line):
|
|
|
|
line = self.pattern.sub(line, '')
|
|
|
|
return line
|
|
|
|
|
2019-01-15 02:23:30 +00:00
|
|
|
def get_log_path(self):
|
|
|
|
new_path = get_celery_task_log_path(self.task_id)
|
|
|
|
if new_path and os.path.isfile(new_path):
|
|
|
|
return new_path
|
|
|
|
try:
|
2022-10-24 12:14:18 +00:00
|
|
|
task = CeleryTaskExecution.objects.get(id=self.task_id)
|
|
|
|
except CeleryTaskExecution.DoesNotExist:
|
2019-01-15 02:23:30 +00:00
|
|
|
return None
|
|
|
|
return task.full_log_path
|
|
|
|
|
|
|
|
def is_file_finish_write(self):
|
|
|
|
return self.task.ready()
|
2018-12-10 02:11:54 +00:00
|
|
|
|
2019-02-20 09:51:53 +00:00
|
|
|
def get_no_file_message(self, request):
|
|
|
|
if self.mark == 'undefined':
|
|
|
|
return '.'
|
|
|
|
else:
|
|
|
|
return _('Waiting task start')
|
|
|
|
|
2018-12-10 02:11:54 +00:00
|
|
|
|
2020-12-29 13:05:18 +00:00
|
|
|
class AnsibleTaskLogApi(LogTailApi):
|
|
|
|
permission_classes = (IsValidUser,)
|
|
|
|
|
|
|
|
def get_log_path(self):
|
|
|
|
new_path = get_ansible_task_log_path(self.kwargs.get('pk'))
|
|
|
|
if new_path and os.path.isfile(new_path):
|
|
|
|
return new_path
|
|
|
|
|
|
|
|
def get_no_file_message(self, request):
|
|
|
|
if self.mark == 'undefined':
|
|
|
|
return '.'
|
|
|
|
else:
|
|
|
|
return _('Waiting task start')
|
|
|
|
|
|
|
|
|
2018-12-10 02:11:54 +00:00
|
|
|
class CeleryResultApi(generics.RetrieveAPIView):
|
|
|
|
permission_classes = (IsValidUser,)
|
|
|
|
serializer_class = CeleryResultSerializer
|
|
|
|
|
|
|
|
def get_object(self):
|
|
|
|
pk = self.kwargs.get('pk')
|
2023-03-15 05:58:36 +00:00
|
|
|
return AsyncResult(str(pk))
|
2018-12-10 02:11:54 +00:00
|
|
|
|
2019-12-05 07:09:25 +00:00
|
|
|
|
|
|
|
class CeleryPeriodTaskViewSet(CommonApiMixin, viewsets.ModelViewSet):
|
|
|
|
queryset = PeriodicTask.objects.all()
|
|
|
|
serializer_class = CeleryPeriodTaskSerializer
|
|
|
|
http_method_names = ('get', 'head', 'options', 'patch')
|
2024-03-20 10:15:00 +00:00
|
|
|
lookup_field = 'name'
|
|
|
|
lookup_value_regex = '[\w.@]+'
|
2019-12-05 07:09:25 +00:00
|
|
|
|
2024-03-20 10:15:00 +00:00
|
|
|
def get_object(self):
|
|
|
|
name = self.kwargs.get('name')
|
|
|
|
obj = get_object_or_404(PeriodicTask, name=name)
|
|
|
|
return obj
|
2022-10-24 12:14:18 +00:00
|
|
|
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
class CelerySummaryAPIView(generics.RetrieveAPIView):
|
|
|
|
def get(self, request, *args, **kwargs):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2023-09-12 07:31:34 +00:00
|
|
|
class CeleryTaskFilterSet(BaseFilterSet):
|
|
|
|
id = drf_filters.CharFilter(field_name='id', lookup_expr='exact')
|
|
|
|
name = drf_filters.CharFilter(method='filter_name')
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def filter_name(queryset, name, value):
|
|
|
|
_ids = []
|
|
|
|
for task in queryset:
|
|
|
|
comment = task.meta.get('comment')
|
|
|
|
if not comment:
|
|
|
|
continue
|
|
|
|
if value not in comment:
|
|
|
|
continue
|
|
|
|
_ids.append(task.id)
|
|
|
|
queryset = queryset.filter(id__in=_ids)
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = CeleryTask
|
|
|
|
fields = ['id', 'name']
|
|
|
|
|
|
|
|
|
2023-01-31 03:00:21 +00:00
|
|
|
class CeleryTaskViewSet(
|
|
|
|
CommonApiMixin, mixins.RetrieveModelMixin,
|
|
|
|
mixins.ListModelMixin, mixins.DestroyModelMixin,
|
|
|
|
viewsets.GenericViewSet
|
|
|
|
):
|
2023-09-12 07:31:34 +00:00
|
|
|
search_fields = ('id', 'name')
|
|
|
|
filterset_class = CeleryTaskFilterSet
|
2022-10-24 12:14:18 +00:00
|
|
|
serializer_class = CeleryTaskSerializer
|
|
|
|
|
2022-11-15 08:29:40 +00:00
|
|
|
def get_queryset(self):
|
|
|
|
return CeleryTask.objects.exclude(name__startswith='celery')
|
|
|
|
|
2023-12-12 06:18:26 +00:00
|
|
|
@staticmethod
|
|
|
|
def extract_schedule(input_string):
|
|
|
|
pattern = r'(\S+ \S+ \S+ \S+ \S+).*'
|
|
|
|
match = re.match(pattern, input_string)
|
|
|
|
if match:
|
|
|
|
return match.group(1)
|
|
|
|
else:
|
|
|
|
return input_string
|
|
|
|
|
|
|
|
def generate_execute_time(self, queryset):
|
|
|
|
now = local_now()
|
|
|
|
for i in queryset:
|
2024-03-20 10:15:00 +00:00
|
|
|
task = getattr(i, 'periodic_obj', None)
|
2023-12-12 06:18:26 +00:00
|
|
|
if not task:
|
|
|
|
continue
|
|
|
|
i.exec_cycle = self.extract_schedule(str(task.scheduler))
|
|
|
|
last_run_at = task.last_run_at or now
|
|
|
|
next_run_at = task.schedule.remaining_estimate(last_run_at)
|
|
|
|
if next_run_at.total_seconds() < 0:
|
|
|
|
next_run_at = task.schedule.remaining_estimate(now)
|
|
|
|
i.next_exec_time = now + next_run_at
|
2024-03-20 10:15:00 +00:00
|
|
|
i.enabled = task.enabled
|
2023-12-12 06:18:26 +00:00
|
|
|
return queryset
|
|
|
|
|
2024-01-18 07:28:13 +00:00
|
|
|
def generate_summary_state(self, execution_qs):
|
|
|
|
model = self.get_queryset().model
|
|
|
|
executions = execution_qs.order_by('-date_published').values('name', 'state')
|
|
|
|
summary_state_dict = defaultdict(
|
|
|
|
lambda: {
|
|
|
|
'states': [], 'state': 'green',
|
|
|
|
'summary': {'total': 0, 'success': 0}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
for execution in executions:
|
|
|
|
name = execution['name']
|
|
|
|
state = execution['state']
|
|
|
|
|
|
|
|
summary = summary_state_dict[name]['summary']
|
|
|
|
|
|
|
|
summary['total'] += 1
|
|
|
|
summary['success'] += 1 if state == 'SUCCESS' else 0
|
|
|
|
|
|
|
|
states = summary_state_dict[name].get('states')
|
|
|
|
if states is not None and len(states) >= 5:
|
|
|
|
color = model.compute_state_color(states)
|
|
|
|
summary_state_dict[name]['state'] = color
|
|
|
|
summary_state_dict[name].pop('states', None)
|
|
|
|
elif isinstance(states, list):
|
|
|
|
states.append(state)
|
|
|
|
|
|
|
|
return summary_state_dict
|
|
|
|
|
|
|
|
def loading_summary_state(self, queryset):
|
|
|
|
if isinstance(queryset, list):
|
|
|
|
names = [i.name for i in queryset]
|
|
|
|
execution_qs = CeleryTaskExecution.objects.filter(name__in=names)
|
|
|
|
else:
|
|
|
|
execution_qs = CeleryTaskExecution.objects.all()
|
|
|
|
summary_state_dict = self.generate_summary_state(execution_qs)
|
|
|
|
for i in queryset:
|
|
|
|
i.summary = summary_state_dict.get(i.name, {}).get('summary', {})
|
|
|
|
i.state = summary_state_dict.get(i.name, {}).get('state', 'green')
|
|
|
|
return queryset
|
|
|
|
|
2023-12-12 06:18:26 +00:00
|
|
|
def list(self, request, *args, **kwargs):
|
|
|
|
queryset = self.filter_queryset(self.get_queryset())
|
2024-03-20 10:15:00 +00:00
|
|
|
queryset = self.mark_periodic_and_sorted(queryset)
|
2023-12-12 06:18:26 +00:00
|
|
|
|
|
|
|
page = self.paginate_queryset(queryset)
|
|
|
|
if page is not None:
|
|
|
|
page = self.generate_execute_time(page)
|
2024-01-18 07:28:13 +00:00
|
|
|
page = self.loading_summary_state(page)
|
2023-12-12 06:18:26 +00:00
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
|
|
|
|
queryset = self.generate_execute_time(queryset)
|
2024-01-18 07:28:13 +00:00
|
|
|
queryset = self.loading_summary_state(queryset)
|
2023-12-12 06:18:26 +00:00
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
2024-03-20 10:15:00 +00:00
|
|
|
@staticmethod
|
|
|
|
def mark_periodic_and_sorted(queryset):
|
|
|
|
names = queryset.values_list('name', flat=True)
|
|
|
|
periodic_tasks = PeriodicTask.objects.filter(name__in=names)
|
|
|
|
periodic_task_dict = {task.task: task for task in periodic_tasks}
|
|
|
|
for q in queryset:
|
|
|
|
if q.name in periodic_task_dict:
|
|
|
|
q.periodic_obj = periodic_task_dict[q.name]
|
|
|
|
q.is_periodic = True
|
|
|
|
else:
|
|
|
|
q.is_periodic = False
|
|
|
|
queryset = sorted(queryset, key=lambda x: x.is_periodic, reverse=True)
|
|
|
|
return queryset
|
|
|
|
|
2022-10-24 12:14:18 +00:00
|
|
|
|
2023-02-06 11:16:24 +00:00
|
|
|
class CeleryTaskExecutionViewSet(CommonApiMixin, viewsets.ModelViewSet):
|
2022-10-24 12:14:18 +00:00
|
|
|
serializer_class = CeleryTaskExecutionSerializer
|
2023-02-06 11:16:24 +00:00
|
|
|
http_method_names = ('get', 'post', 'head', 'options',)
|
2022-11-11 11:20:17 +00:00
|
|
|
queryset = CeleryTaskExecution.objects.all()
|
2023-02-09 09:44:35 +00:00
|
|
|
search_fields = ('name',)
|
2022-10-25 12:02:23 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
2022-11-11 11:20:17 +00:00
|
|
|
task_id = self.request.query_params.get('task_id')
|
2022-10-25 12:02:23 +00:00
|
|
|
if task_id:
|
2022-11-11 11:20:17 +00:00
|
|
|
task = get_object_or_404(CeleryTask, id=task_id)
|
|
|
|
self.queryset = self.queryset.filter(name=task.name)
|
2024-03-28 03:00:18 +00:00
|
|
|
if not self.request.user.is_superuser:
|
|
|
|
self.queryset = self.queryset.filter(creator=self.request.user)
|
2022-11-11 11:20:17 +00:00
|
|
|
return self.queryset
|
2023-02-06 11:16:24 +00:00
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
form_id = self.request.query_params.get('from', None)
|
|
|
|
if not form_id:
|
|
|
|
return Response(status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
execution = get_object_or_404(CeleryTaskExecution, id=form_id)
|
|
|
|
task = app.tasks.get(execution.name, None)
|
|
|
|
if not task:
|
2023-02-16 07:52:21 +00:00
|
|
|
msg = _("Task {} not found").format(execution.name)
|
|
|
|
raise JMSException(code='task_not_found_error', detail=msg)
|
|
|
|
try:
|
|
|
|
t = task.delay(*execution.args, **execution.kwargs)
|
|
|
|
except TypeError:
|
|
|
|
msg = _("Task {} args or kwargs error").format(execution.name)
|
|
|
|
raise JMSException(code='task_args_error', detail=msg)
|
2023-02-06 11:16:24 +00:00
|
|
|
return Response(status=status.HTTP_201_CREATED, data={'task_id': t.id})
|