jumpserver/apps/assets/models/automations/base.py

121 lines
4.4 KiB
Python
Raw Normal View History

2022-09-07 11:49:42 +00:00
import uuid
from celery import current_task
from django.db import models
from django.utils.translation import ugettext_lazy as _
from common.const.choices import Trigger
2022-10-19 09:05:21 +00:00
from common.mixins.models import CommonModelMixin
2022-09-07 11:49:42 +00:00
from common.db.fields import EncryptJsonDictTextField
2022-10-19 09:05:21 +00:00
from orgs.mixins.models import OrgModelMixin
2022-09-07 11:49:42 +00:00
from ops.mixin import PeriodTaskModelMixin
2022-10-09 12:54:11 +00:00
from assets.models import Node, Asset
2022-10-25 10:43:34 +00:00
from assets.tasks import execute_automation
2022-10-27 10:53:10 +00:00
from assets.const import AutomationTypes
2022-09-07 11:49:42 +00:00
2022-10-19 09:05:21 +00:00
class BaseAutomation(CommonModelMixin, PeriodTaskModelMixin, OrgModelMixin):
2022-09-07 11:49:42 +00:00
accounts = models.JSONField(default=list, verbose_name=_("Accounts"))
2022-11-09 07:42:21 +00:00
nodes = models.ManyToManyField('assets.Node', blank=True, verbose_name=_("Nodes"))
assets = models.ManyToManyField('assets.Asset', blank=True, verbose_name=_("Assets"))
2022-10-27 10:53:10 +00:00
type = models.CharField(max_length=16, choices=AutomationTypes.choices, verbose_name=_('Type'))
2022-10-13 09:47:29 +00:00
is_active = models.BooleanField(default=True, verbose_name=_("Is active"))
2022-09-07 11:49:42 +00:00
comment = models.TextField(blank=True, verbose_name=_('Comment'))
def __str__(self):
return self.name + '@' + str(self.created_by)
@classmethod
def generate_unique_name(cls, name):
while True:
name = name + str(uuid.uuid4())[:8]
try:
cls.objects.get(name=name)
except cls.DoesNotExist:
return name
2022-10-09 12:54:11 +00:00
def get_all_assets(self):
nodes = self.nodes.all()
node_asset_ids = Node.get_nodes_all_assets(*nodes).values_list('id', flat=True)
direct_asset_ids = self.assets.all().values_list('id', flat=True)
asset_ids = set(list(direct_asset_ids) + list(node_asset_ids))
return Asset.objects.filter(id__in=asset_ids)
def all_assets_group_by_platform(self):
assets = self.get_all_assets().prefetch_related('platform')
return assets.group_by_platform()
2022-09-07 11:49:42 +00:00
def get_register_task(self):
2022-10-25 10:43:34 +00:00
name = f"automation_{self.type}_strategy_period_{str(self.id)[:8]}"
task = execute_automation.name
args = (str(self.id), Trigger.timing, self.type)
2022-10-25 10:43:34 +00:00
kwargs = {}
return name, task, args, kwargs
2022-09-07 11:49:42 +00:00
2022-10-21 10:19:09 +00:00
def get_many_to_many_ids(self, field: str):
return [str(i) for i in getattr(self, field).all().values_list('id', flat=True)]
2022-09-07 11:49:42 +00:00
def to_attr_json(self):
return {
'name': self.name,
2022-10-19 09:05:21 +00:00
'type': self.type,
2022-10-21 10:19:09 +00:00
'org_id': str(self.org_id),
2022-10-19 09:05:21 +00:00
'comment': self.comment,
2022-09-07 11:49:42 +00:00
'accounts': self.accounts,
2022-10-21 10:19:09 +00:00
'nodes': self.get_many_to_many_ids('nodes'),
'assets': self.get_many_to_many_ids('assets'),
2022-09-07 11:49:42 +00:00
}
2022-10-09 12:54:11 +00:00
def execute(self, trigger=Trigger.manual):
2022-09-07 11:49:42 +00:00
try:
eid = current_task.request.id
except AttributeError:
eid = str(uuid.uuid4())
2022-10-09 12:54:11 +00:00
2022-10-19 09:05:21 +00:00
execution = self.executions.model.objects.create(
id=eid, trigger=trigger, automation=self,
2022-10-21 10:19:09 +00:00
snapshot=self.to_attr_json(),
2022-09-07 11:49:42 +00:00
)
return execution.start()
class Meta:
unique_together = [('org_id', 'name')]
2022-10-19 06:56:27 +00:00
verbose_name = _("Automation task")
2022-09-07 11:49:42 +00:00
2022-10-09 12:54:11 +00:00
class AutomationExecution(OrgModelMixin):
2022-09-07 11:49:42 +00:00
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
2022-10-09 12:54:11 +00:00
automation = models.ForeignKey(
'BaseAutomation', related_name='executions', on_delete=models.CASCADE,
2022-10-19 06:56:27 +00:00
verbose_name=_('Automation task')
2022-10-09 12:54:11 +00:00
)
2022-11-09 07:42:21 +00:00
status = models.CharField(max_length=16, default='pending', verbose_name=_('Status'))
2022-10-09 12:54:11 +00:00
date_created = models.DateTimeField(auto_now_add=True, verbose_name=_('Date created'))
date_start = models.DateTimeField(null=True, verbose_name=_('Date start'), db_index=True)
date_finished = models.DateTimeField(null=True, verbose_name=_("Date finished"))
2022-09-07 11:49:42 +00:00
snapshot = EncryptJsonDictTextField(
default=dict, blank=True, null=True, verbose_name=_('Automation snapshot')
)
trigger = models.CharField(
2022-10-09 12:54:11 +00:00
max_length=128, default=Trigger.manual, choices=Trigger.choices,
verbose_name=_('Trigger mode')
2022-09-07 11:49:42 +00:00
)
class Meta:
2022-10-19 06:56:27 +00:00
verbose_name = _('Automation task execution')
2022-09-07 11:49:42 +00:00
@property
def manager_type(self):
return self.snapshot['type']
@property
def recipients(self):
recipients = self.snapshot.get('recipients')
if not recipients:
return []
return recipients.values()
2022-09-07 11:49:42 +00:00
def start(self):
2022-10-13 09:47:29 +00:00
from assets.automations.endpoint import ExecutionManager
2022-09-07 11:49:42 +00:00
manager = ExecutionManager(execution=self)
return manager.run()