jumpserver/apps/ops/models.py

355 lines
12 KiB
Python
Raw Normal View History

2017-03-09 06:55:33 +00:00
# ~*~ coding: utf-8 ~*~
2017-03-13 16:58:25 +00:00
import json
2017-11-23 06:08:01 +00:00
import uuid
2017-03-09 06:55:33 +00:00
2017-12-21 18:08:29 +00:00
import time
2017-03-09 06:55:33 +00:00
from django.db import models
2017-12-21 18:08:29 +00:00
from django.utils import timezone
2017-03-09 06:55:33 +00:00
from django.utils.translation import ugettext_lazy as _
2017-12-21 18:08:29 +00:00
from django_celery_beat.models import CrontabSchedule, IntervalSchedule, PeriodicTask
2017-12-10 16:29:25 +00:00
2017-12-24 10:53:07 +00:00
from common.utils import get_signer, get_logger
from common.celery import delete_celery_periodic_task, create_or_update_celery_periodic_tasks, \
disable_celery_periodic_task
2017-12-21 18:08:29 +00:00
from .ansible import AdHocRunner, AnsibleError
2017-12-22 13:42:12 +00:00
from .inventory import JMSInventory
2017-03-09 06:55:33 +00:00
2017-12-10 16:29:25 +00:00
__all__ = ["Task", "AdHoc", "AdHocRunHistory"]
2017-03-09 06:55:33 +00:00
2017-12-22 13:42:12 +00:00
logger = get_logger(__file__)
2017-12-24 10:53:07 +00:00
signer = get_signer()
2017-03-09 06:55:33 +00:00
2017-12-10 16:29:25 +00:00
class Task(models.Model):
"""
This task is different ansible task, Task like 'push system user', 'get asset info' ..
One task can have some versions of adhoc, run a task only run the latest version adhoc
"""
2017-12-07 05:01:33 +00:00
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
2017-12-15 07:50:15 +00:00
name = models.CharField(max_length=128, unique=True, verbose_name=_('Name'))
2017-12-22 13:42:12 +00:00
interval = models.IntegerField(verbose_name=_("Interval"), null=True, blank=True, help_text=_("Units: seconds"))
crontab = models.CharField(verbose_name=_("Crontab"), null=True, blank=True, max_length=128, help_text=_("5 * * * *"))
2017-12-21 18:08:29 +00:00
is_periodic = models.BooleanField(default=False)
2017-12-22 13:42:12 +00:00
callback = models.CharField(max_length=128, blank=True, null=True, verbose_name=_("Callback")) # Callback must be a registered celery task
2017-12-07 08:25:50 +00:00
is_deleted = models.BooleanField(default=False)
2017-12-21 18:08:29 +00:00
comment = models.TextField(blank=True, verbose_name=_("Comment"))
2017-12-15 09:07:52 +00:00
created_by = models.CharField(max_length=128, blank=True, null=True, default='')
2017-12-10 16:29:25 +00:00
date_created = models.DateTimeField(auto_now_add=True)
2017-12-15 07:50:15 +00:00
__latest_adhoc = None
2017-12-07 05:01:33 +00:00
@property
def short_id(self):
return str(self.id).split('-')[-1]
2017-03-09 06:55:33 +00:00
2017-12-15 07:50:15 +00:00
@property
def latest_adhoc(self):
if not self.__latest_adhoc:
self.__latest_adhoc = self.get_latest_adhoc()
return self.__latest_adhoc
2017-12-07 05:01:33 +00:00
2017-12-15 07:50:15 +00:00
@latest_adhoc.setter
def latest_adhoc(self, item):
self.__latest_adhoc = item
2017-12-10 16:29:25 +00:00
2017-12-15 07:50:15 +00:00
@property
def latest_history(self):
try:
return self.history.all().latest()
except AdHocRunHistory.DoesNotExist:
return None
2017-12-10 16:29:25 +00:00
2017-12-15 07:50:15 +00:00
def get_latest_adhoc(self):
try:
return self.adhoc.all().latest()
except AdHoc.DoesNotExist:
return None
2017-12-10 16:29:25 +00:00
2017-12-15 07:50:15 +00:00
@property
def history_summary(self):
history = self.get_run_history()
total = len(history)
success = len([history for history in history if history.is_success])
failed = len([history for history in history if not history.is_success])
2017-12-10 16:29:25 +00:00
return {'total': total, 'success': success, 'failed': failed}
2017-03-09 06:55:33 +00:00
2017-12-15 07:50:15 +00:00
def get_run_history(self):
return self.history.all()
2017-12-21 18:08:29 +00:00
def run(self, record=True):
2017-12-15 07:50:15 +00:00
if self.latest_adhoc:
2017-12-21 18:08:29 +00:00
return self.latest_adhoc.run(record=record)
2017-12-15 07:50:15 +00:00
else:
return {'error': 'No adhoc'}
2017-12-21 18:08:29 +00:00
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
2017-12-22 13:42:12 +00:00
from .tasks import run_ansible_task
super().save(
2017-12-21 18:08:29 +00:00
force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields,
)
2017-12-22 13:42:12 +00:00
if self.is_periodic:
interval = None
crontab = None
if self.interval:
interval = self.interval
elif self.crontab:
crontab = self.crontab
tasks = {
self.name: {
"task": run_ansible_task.name,
"interval": interval,
"crontab": crontab,
"args": (str(self.id),),
"kwargs": {"callback": self.callback},
"enabled": True,
}
}
create_or_update_celery_periodic_tasks(tasks)
2017-12-21 18:08:29 +00:00
else:
2017-12-22 13:42:12 +00:00
disable_celery_periodic_task(self.name)
2017-12-21 18:08:29 +00:00
2017-12-22 13:42:12 +00:00
def delete(self, using=None, keep_parents=False):
super().delete(using=using, keep_parents=keep_parents)
delete_celery_periodic_task(self.name)
@property
def schedule(self):
try:
return PeriodicTask.objects.get(name=self.name)
except PeriodicTask.DoesNotExist:
return None
2017-12-21 18:08:29 +00:00
2017-12-15 07:50:15 +00:00
def __str__(self):
return self.name
2017-12-10 16:29:25 +00:00
class Meta:
db_table = 'ops_task'
2017-12-15 07:50:15 +00:00
get_latest_by = 'date_created'
2017-12-10 16:29:25 +00:00
class AdHoc(models.Model):
"""
task: A task reference
_tasks: [{'name': 'task_name', 'action': {'module': '', 'args': ''}, 'other..': ''}, ]
_options: ansible options, more see ops.ansible.runner.Options
_hosts: ["hostname1", "hostname2"], hostname must be unique key of cmdb
run_as_admin: if true, then need get every host admin user run it, because every host may be have different admin user, so we choise host level
run_as: if not run as admin, it run it as a system/common user from cmdb
_become: May be using become [sudo, su] options. {method: "sudo", user: "user", pass: "pass"]
pattern: Even if we set _hosts, We only use that to make inventory, We also can set `patter` to run task on match hosts
"""
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
task = models.ForeignKey(Task, related_name='adhoc', on_delete=models.CASCADE)
_tasks = models.TextField(verbose_name=_('Tasks'))
2017-12-15 09:07:52 +00:00
pattern = models.CharField(max_length=64, default='{}', verbose_name=_('Pattern'))
2017-12-10 16:29:25 +00:00
_options = models.CharField(max_length=1024, default='', verbose_name=_('Options'))
2017-12-07 05:01:33 +00:00
_hosts = models.TextField(blank=True, verbose_name=_('Hosts')) # ['hostname1', 'hostname2']
run_as_admin = models.BooleanField(default=False, verbose_name=_('Run as admin'))
2017-12-10 16:29:25 +00:00
run_as = models.CharField(max_length=128, default='', verbose_name=_("Run as"))
_become = models.CharField(max_length=1024, default='', verbose_name=_("Become"))
2017-12-15 09:07:52 +00:00
created_by = models.CharField(max_length=64, default='', null=True, verbose_name=_('Create by'))
date_created = models.DateTimeField(auto_now_add=True)
2017-03-09 06:55:33 +00:00
2017-03-13 16:58:25 +00:00
@property
2017-12-07 05:01:33 +00:00
def tasks(self):
return json.loads(self._tasks)
@tasks.setter
def tasks(self, item):
2017-12-10 16:29:25 +00:00
if item and isinstance(item, list):
self._tasks = json.dumps(item)
else:
raise SyntaxError('Tasks should be a list: {}'.format(item))
2017-03-13 16:58:25 +00:00
@property
2017-12-07 05:01:33 +00:00
def hosts(self):
return json.loads(self._hosts)
2017-03-13 16:58:25 +00:00
2017-12-07 05:01:33 +00:00
@hosts.setter
def hosts(self, item):
self._hosts = json.dumps(item)
2017-03-13 16:58:25 +00:00
2017-12-22 13:42:12 +00:00
@property
def inventory(self):
if self.become:
become_info = {
'become': {
self.become
}
}
else:
become_info = None
inventory = JMSInventory(
self.hosts, run_as_admin=self.run_as_admin,
run_as=self.run_as, become_info=become_info
)
return inventory
2017-12-07 08:25:50 +00:00
@property
2017-12-10 16:29:25 +00:00
def become(self):
if self._become:
return json.loads(signer.unsign(self._become))
else:
return {}
2017-12-21 18:08:29 +00:00
def run(self, record=True):
if record:
return self._run_and_record()
else:
return self._run_only()
def _run_and_record(self):
history = AdHocRunHistory(adhoc=self, task=self.task)
time_start = time.time()
try:
2017-12-22 13:42:12 +00:00
raw, summary = self._run_only()
2017-12-21 18:08:29 +00:00
history.is_finished = True
2017-12-22 13:42:12 +00:00
if summary.get('dark'):
2017-12-21 18:08:29 +00:00
history.is_success = False
else:
history.is_success = True
2017-12-22 13:42:12 +00:00
history.result = raw
history.summary = summary
return raw, summary
except Exception as e:
return {}, {"dark": {"all": str(e)}, "contacted": []}
2017-12-21 18:08:29 +00:00
finally:
history.date_finished = timezone.now()
history.timedelta = time.time() - time_start
history.save()
def _run_only(self):
2017-12-22 13:42:12 +00:00
runner = AdHocRunner(self.inventory)
2017-12-21 18:08:29 +00:00
for k, v in self.options.items():
runner.set_option(k, v)
try:
result = runner.run(self.tasks, self.pattern, self.task.name)
2017-12-22 13:42:12 +00:00
return result.results_raw, result.results_summary
2017-12-21 18:08:29 +00:00
except AnsibleError as e:
logger.error("Failed run adhoc {}, {}".format(self.task.name, e))
2018-01-02 09:02:03 +00:00
pass
2017-12-15 07:50:15 +00:00
2017-12-10 16:29:25 +00:00
@become.setter
def become(self, item):
"""
:param item: {
method: "sudo",
user: "user",
pass: "pass",
}
:return:
"""
2017-12-24 10:53:07 +00:00
self._become = signer.sign(json.dumps(item)).decode('utf-8')
2017-12-10 16:29:25 +00:00
@property
def options(self):
if self._options:
2017-12-15 09:07:52 +00:00
_options = json.loads(self._options)
if isinstance(_options, dict):
return _options
return {}
2017-12-07 08:25:50 +00:00
2017-12-10 16:29:25 +00:00
@options.setter
def options(self, item):
self._options = json.dumps(item)
2017-12-07 08:25:50 +00:00
2017-12-07 05:01:33 +00:00
@property
2017-12-10 16:29:25 +00:00
def short_id(self):
return str(self.id).split('-')[-1]
2017-03-13 16:58:25 +00:00
2017-12-15 07:50:15 +00:00
@property
def latest_history(self):
try:
return self.history.all().latest()
except AdHocRunHistory.DoesNotExist:
return None
2017-12-07 08:25:50 +00:00
2017-12-24 10:53:07 +00:00
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
super().save(force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
2017-12-07 05:01:33 +00:00
def __str__(self):
2017-12-10 16:29:25 +00:00
return "{} of {}".format(self.task.name, self.short_id)
2017-12-07 05:01:33 +00:00
2017-12-15 07:50:15 +00:00
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
fields_check = []
for field in self.__class__._meta.fields:
if field.name not in ['id', 'date_created']:
fields_check.append(field)
for field in fields_check:
if getattr(self, field.name) != getattr(other, field.name):
return False
return True
2017-12-07 08:25:50 +00:00
class Meta:
2017-12-10 16:29:25 +00:00
db_table = "ops_adhoc"
2017-12-15 07:50:15 +00:00
get_latest_by = 'date_created'
2017-12-07 08:25:50 +00:00
2017-12-07 05:01:33 +00:00
2017-12-07 08:25:50 +00:00
class AdHocRunHistory(models.Model):
2017-12-10 16:29:25 +00:00
"""
AdHoc running history.
"""
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
2017-12-15 07:50:15 +00:00
task = models.ForeignKey(Task, related_name='history', on_delete=models.SET_NULL, null=True)
adhoc = models.ForeignKey(AdHoc, related_name='history', on_delete=models.SET_NULL, null=True)
2017-12-06 10:31:51 +00:00
date_start = models.DateTimeField(auto_now_add=True, verbose_name=_('Start time'))
date_finished = models.DateTimeField(blank=True, null=True, verbose_name=_('End time'))
timedelta = models.FloatField(default=0.0, verbose_name=_('Time'), null=True)
is_finished = models.BooleanField(default=False, verbose_name=_('Is finished'))
is_success = models.BooleanField(default=False, verbose_name=_('Is success'))
2017-12-10 16:29:25 +00:00
_result = models.TextField(blank=True, null=True, verbose_name=_('Adhoc raw result'))
_summary = models.TextField(blank=True, null=True, verbose_name=_('Adhoc result summary'))
2017-12-07 05:01:33 +00:00
@property
def short_id(self):
return str(self.id).split('-')[-1]
2017-12-10 16:29:25 +00:00
@property
def result(self):
if self._result:
return json.loads(self._result)
else:
return {}
2017-12-10 16:29:25 +00:00
@result.setter
def result(self, item):
self._result = json.dumps(item)
@property
def summary(self):
if self._summary:
return json.loads(self._summary)
else:
return {"ok": {}, "dark": {}}
2017-12-10 16:29:25 +00:00
@summary.setter
def summary(self, item):
self._summary = json.dumps(item)
2017-12-20 03:30:15 +00:00
@property
def success_hosts(self):
return self.summary.get('contacted', [])
@property
def failed_hosts(self):
return self.summary.get('dark', {})
2017-12-07 05:01:33 +00:00
def __str__(self):
return self.short_id
2017-12-07 08:25:50 +00:00
class Meta:
db_table = "ops_adhoc_history"
2017-12-15 07:50:15 +00:00
get_latest_by = 'date_start'