jumpserver/apps/ops/api/job.py

65 lines
2.0 KiB
Python
Raw Normal View History

2022-11-11 11:20:17 +00:00
from rest_framework import viewsets
from ops.models import Job, JobExecution
from ops.serializers.job import JobSerializer, JobExecutionSerializer
__all__ = ['JobViewSet', 'JobExecutionViewSet']
from ops.tasks import run_ops_job_execution
2022-11-23 16:50:37 +00:00
from orgs.mixins.api import OrgBulkModelViewSet
2022-11-11 11:20:17 +00:00
def set_task_to_serializer_data(serializer, task):
data = getattr(serializer, "_data", {})
data["task_id"] = task.id
setattr(serializer, "_data", data)
2022-11-23 16:50:37 +00:00
class JobViewSet(OrgBulkModelViewSet):
2022-11-11 11:20:17 +00:00
serializer_class = JobSerializer
2022-11-23 16:50:37 +00:00
model = Job
permission_classes = ()
2022-11-11 11:20:17 +00:00
def get_queryset(self):
2022-11-23 16:50:37 +00:00
query_set = super().get_queryset()
2022-11-25 19:13:06 +00:00
if self.action != 'retrieve':
return query_set.filter(instant=False)
return query_set
2022-11-11 11:20:17 +00:00
def perform_create(self, serializer):
instance = serializer.save()
2022-12-02 04:21:56 +00:00
run_after_save = serializer.validated_data.get('run_after_save', False)
if instance.instant or run_after_save:
self.run_job(instance, serializer)
def perform_update(self, serializer):
instance = serializer.save()
run_after_save = serializer.validated_data.get('run_after_save', False)
if run_after_save:
self.run_job(instance, serializer)
@staticmethod
def run_job(job, serializer):
execution = job.create_execution()
task = run_ops_job_execution.delay(execution.id)
set_task_to_serializer_data(serializer, task)
2022-11-11 11:20:17 +00:00
2022-11-23 16:50:37 +00:00
class JobExecutionViewSet(OrgBulkModelViewSet):
2022-11-11 11:20:17 +00:00
serializer_class = JobExecutionSerializer
http_method_names = ('get', 'post', 'head', 'options',)
2022-11-23 16:50:37 +00:00
permission_classes = ()
model = JobExecution
2022-11-11 11:20:17 +00:00
def perform_create(self, serializer):
instance = serializer.save()
task = run_ops_job_execution.delay(instance.id)
set_task_to_serializer_data(serializer, task)
2022-11-11 11:20:17 +00:00
def get_queryset(self):
2022-11-23 16:50:37 +00:00
query_set = super().get_queryset()
2022-11-11 11:20:17 +00:00
job_id = self.request.query_params.get('job_id')
if job_id:
query_set = query_set.filter(job_id=job_id)
2022-11-23 16:50:37 +00:00
return query_set