2022-10-08 08:55:14 +00:00
|
|
|
import os.path
|
|
|
|
import uuid
|
2022-10-08 11:12:04 +00:00
|
|
|
import logging
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
from django.utils import timezone
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
from orgs.mixins.models import JMSOrgBaseModel
|
|
|
|
from ..ansible.inventory import JMSInventory
|
|
|
|
from ..mixin import PeriodTaskModelMixin
|
|
|
|
|
|
|
|
|
2022-11-01 03:52:51 +00:00
|
|
|
class BaseAnsibleJob(PeriodTaskModelMixin, JMSOrgBaseModel):
|
2022-10-08 08:55:14 +00:00
|
|
|
owner = models.ForeignKey('users.User', verbose_name=_("Creator"), on_delete=models.SET_NULL, null=True)
|
|
|
|
assets = models.ManyToManyField('assets.Asset', verbose_name=_("Assets"))
|
|
|
|
account = models.CharField(max_length=128, default='root', verbose_name=_('Account'))
|
|
|
|
account_policy = models.CharField(max_length=128, default='root', verbose_name=_('Account policy'))
|
2022-11-11 11:20:17 +00:00
|
|
|
last_execution = models.ForeignKey('BaseAnsibleExecution', verbose_name=_("Last execution"),
|
|
|
|
on_delete=models.SET_NULL, null=True)
|
2022-10-08 08:55:14 +00:00
|
|
|
date_last_run = models.DateTimeField(null=True, verbose_name=_('Date last run'))
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
|
|
|
@property
|
|
|
|
def inventory(self):
|
|
|
|
inv = JMSInventory(self.assets.all(), self.account, self.account_policy)
|
2022-10-08 11:12:04 +00:00
|
|
|
return inv
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
def get_register_task(self):
|
2022-10-10 05:56:42 +00:00
|
|
|
raise NotImplementedError
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
def to_json(self):
|
2022-10-10 05:56:42 +00:00
|
|
|
raise NotImplementedError
|
2022-10-08 08:55:14 +00:00
|
|
|
|
2022-10-08 11:12:04 +00:00
|
|
|
def create_execution(self):
|
|
|
|
execution = self.executions.create()
|
|
|
|
return execution
|
|
|
|
|
|
|
|
def run(self, *args, **kwargs):
|
|
|
|
execution = self.create_execution()
|
|
|
|
return execution.start()
|
|
|
|
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
class BaseAnsibleExecution(models.Model):
|
|
|
|
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
|
|
|
|
status = models.CharField(max_length=16, verbose_name=_('Status'), default='running')
|
2022-11-01 03:52:51 +00:00
|
|
|
task = models.ForeignKey(BaseAnsibleJob, on_delete=models.CASCADE, related_name='executions', null=True)
|
2022-10-08 08:55:14 +00:00
|
|
|
result = models.JSONField(blank=True, null=True, verbose_name=_('Result'))
|
|
|
|
summary = models.JSONField(default=dict, verbose_name=_('Summary'))
|
|
|
|
creator = models.ForeignKey('users.User', verbose_name=_("Creator"), on_delete=models.SET_NULL, null=True)
|
|
|
|
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)
|
2022-10-09 12:54:11 +00:00
|
|
|
date_finished = models.DateTimeField(null=True, verbose_name=_("Date finished"))
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
ordering = ["-date_start"]
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.id)
|
|
|
|
|
2022-10-08 11:12:04 +00:00
|
|
|
@property
|
2022-10-08 08:55:14 +00:00
|
|
|
def private_dir(self):
|
|
|
|
uniq = self.date_created.strftime('%Y%m%d_%H%M%S') + '_' + self.short_id
|
|
|
|
return os.path.join(settings.ANSIBLE_DIR, self.task.name, uniq)
|
|
|
|
|
2022-10-08 11:12:04 +00:00
|
|
|
@property
|
|
|
|
def inventory_path(self):
|
|
|
|
return os.path.join(self.private_dir, 'inventory', 'hosts')
|
|
|
|
|
2022-10-08 08:55:14 +00:00
|
|
|
def get_runner(self):
|
2022-10-10 05:56:42 +00:00
|
|
|
raise NotImplementedError
|
2022-10-08 08:55:14 +00:00
|
|
|
|
2022-10-08 11:12:04 +00:00
|
|
|
def finish_task(self):
|
|
|
|
self.date_finished = timezone.now()
|
|
|
|
self.save(update_fields=['result', 'status', 'summary', 'date_finished'])
|
|
|
|
self.update_task()
|
|
|
|
|
|
|
|
def set_error(self, error):
|
|
|
|
this = self.__class__.objects.get(id=self.id) # 重新获取一次,避免数据库超时连接超时
|
|
|
|
this.status = 'failed'
|
|
|
|
this.summary['error'] = str(error)
|
|
|
|
this.finish_task()
|
|
|
|
|
|
|
|
def set_result(self, cb):
|
|
|
|
status_mapper = {
|
2022-11-01 03:52:51 +00:00
|
|
|
'successful': 'success',
|
2022-10-08 11:12:04 +00:00
|
|
|
}
|
|
|
|
this = self.__class__.objects.get(id=self.id)
|
|
|
|
this.status = status_mapper.get(cb.status, cb.status)
|
|
|
|
this.summary = cb.summary
|
|
|
|
this.result = cb.result
|
|
|
|
this.finish_task()
|
|
|
|
print("Finished")
|
|
|
|
|
2022-10-08 08:55:14 +00:00
|
|
|
def update_task(self):
|
|
|
|
self.task.last_execution = self
|
|
|
|
self.task.date_last_run = timezone.now()
|
|
|
|
self.task.save(update_fields=['last_execution', 'date_last_run'])
|
|
|
|
|
|
|
|
def start(self, **kwargs):
|
|
|
|
runner = self.get_runner()
|
|
|
|
try:
|
|
|
|
cb = runner.run(**kwargs)
|
2022-10-08 11:12:04 +00:00
|
|
|
self.set_result(cb)
|
|
|
|
return cb
|
2022-10-08 08:55:14 +00:00
|
|
|
except Exception as e:
|
2022-10-08 11:12:04 +00:00
|
|
|
logging.error(e, exc_info=True)
|
|
|
|
self.set_error(e)
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_finished(self):
|
2022-11-01 03:52:51 +00:00
|
|
|
return self.status in ['success', 'failed']
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_success(self):
|
2022-11-01 03:52:51 +00:00
|
|
|
return self.status == 'success'
|
2022-10-08 08:55:14 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def short_id(self):
|
|
|
|
return str(self.id).split('-')[-1]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def timedelta(self):
|
|
|
|
if self.date_start and self.date_finished:
|
|
|
|
return self.date_finished - self.date_start
|
|
|
|
return None
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
@property
|
|
|
|
def time_cost(self):
|
|
|
|
if self.date_finished and self.date_start:
|
|
|
|
return (self.date_finished - self.date_start).total_seconds()
|
|
|
|
return None
|