mirror of https://github.com/jumpserver/jumpserver
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
379 lines
12 KiB
379 lines
12 KiB
8 years ago
|
# ~*~ coding: utf-8 ~*~
|
||
|
|
||
8 years ago
|
import json
|
||
7 years ago
|
import uuid
|
||
7 years ago
|
import os
|
||
7 years ago
|
import time
|
||
7 years ago
|
import datetime
|
||
|
|
||
7 years ago
|
from celery import current_task
|
||
8 years ago
|
from django.db import models
|
||
7 years ago
|
from django.conf import settings
|
||
7 years ago
|
from django.utils import timezone
|
||
8 years ago
|
from django.utils.translation import ugettext_lazy as _
|
||
7 years ago
|
from django_celery_beat.models import PeriodicTask
|
||
7 years ago
|
|
||
7 years ago
|
from common.utils import get_signer, get_logger
|
||
7 years ago
|
from ..celery.utils import delete_celery_periodic_task, \
|
||
7 years ago
|
create_or_update_celery_periodic_tasks, \
|
||
|
disable_celery_periodic_task
|
||
7 years ago
|
from ..ansible import AdHocRunner, AnsibleError
|
||
|
from ..inventory import JMSInventory
|
||
8 years ago
|
|
||
7 years ago
|
__all__ = ["Task", "AdHoc", "AdHocRunHistory"]
|
||
8 years ago
|
|
||
|
|
||
7 years ago
|
logger = get_logger(__file__)
|
||
7 years ago
|
signer = get_signer()
|
||
8 years ago
|
|
||
|
|
||
7 years ago
|
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
|
||
|
"""
|
||
7 years ago
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||
7 years ago
|
name = models.CharField(max_length=128, unique=True, verbose_name=_('Name'))
|
||
7 years ago
|
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 * * * *"))
|
||
7 years ago
|
is_periodic = models.BooleanField(default=False)
|
||
7 years ago
|
callback = models.CharField(max_length=128, blank=True, null=True, verbose_name=_("Callback")) # Callback must be a registered celery task
|
||
7 years ago
|
is_deleted = models.BooleanField(default=False)
|
||
7 years ago
|
comment = models.TextField(blank=True, verbose_name=_("Comment"))
|
||
7 years ago
|
created_by = models.CharField(max_length=128, blank=True, null=True, default='')
|
||
7 years ago
|
date_created = models.DateTimeField(auto_now_add=True)
|
||
7 years ago
|
__latest_adhoc = None
|
||
7 years ago
|
|
||
|
@property
|
||
|
def short_id(self):
|
||
|
return str(self.id).split('-')[-1]
|
||
8 years ago
|
|
||
7 years ago
|
@property
|
||
|
def latest_adhoc(self):
|
||
|
if not self.__latest_adhoc:
|
||
|
self.__latest_adhoc = self.get_latest_adhoc()
|
||
|
return self.__latest_adhoc
|
||
7 years ago
|
|
||
7 years ago
|
@latest_adhoc.setter
|
||
|
def latest_adhoc(self, item):
|
||
|
self.__latest_adhoc = item
|
||
7 years ago
|
|
||
7 years ago
|
@property
|
||
|
def latest_history(self):
|
||
|
try:
|
||
|
return self.history.all().latest()
|
||
|
except AdHocRunHistory.DoesNotExist:
|
||
|
return None
|
||
7 years ago
|
|
||
7 years ago
|
def get_latest_adhoc(self):
|
||
|
try:
|
||
|
return self.adhoc.all().latest()
|
||
|
except AdHoc.DoesNotExist:
|
||
|
return None
|
||
7 years ago
|
|
||
7 years ago
|
@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])
|
||
7 years ago
|
return {'total': total, 'success': success, 'failed': failed}
|
||
8 years ago
|
|
||
7 years ago
|
def get_run_history(self):
|
||
|
return self.history.all()
|
||
|
|
||
7 years ago
|
def run(self, record=True):
|
||
7 years ago
|
if self.latest_adhoc:
|
||
7 years ago
|
return self.latest_adhoc.run(record=record)
|
||
7 years ago
|
else:
|
||
|
return {'error': 'No adhoc'}
|
||
|
|
||
7 years ago
|
def save(self, force_insert=False, force_update=False, using=None,
|
||
|
update_fields=None):
|
||
7 years ago
|
from ..tasks import run_ansible_task
|
||
7 years ago
|
super().save(
|
||
7 years ago
|
force_insert=force_insert, force_update=force_update,
|
||
|
using=using, update_fields=update_fields,
|
||
|
)
|
||
|
|
||
7 years ago
|
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)
|
||
7 years ago
|
else:
|
||
7 years ago
|
disable_celery_periodic_task(self.name)
|
||
7 years ago
|
|
||
7 years ago
|
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
|
||
7 years ago
|
|
||
7 years ago
|
def __str__(self):
|
||
|
return self.name
|
||
|
|
||
7 years ago
|
class Meta:
|
||
|
db_table = 'ops_task'
|
||
7 years ago
|
get_latest_by = 'date_created'
|
||
7 years ago
|
|
||
|
|
||
|
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'))
|
||
7 years ago
|
pattern = models.CharField(max_length=64, default='{}', verbose_name=_('Pattern'))
|
||
7 years ago
|
_options = models.CharField(max_length=1024, default='', verbose_name=_('Options'))
|
||
7 years ago
|
_hosts = models.TextField(blank=True, verbose_name=_('Hosts')) # ['hostname1', 'hostname2']
|
||
|
run_as_admin = models.BooleanField(default=False, verbose_name=_('Run as admin'))
|
||
7 years ago
|
run_as = models.CharField(max_length=128, default='', verbose_name=_("Run as"))
|
||
|
_become = models.CharField(max_length=1024, default='', verbose_name=_("Become"))
|
||
7 years ago
|
created_by = models.CharField(max_length=64, default='', null=True, verbose_name=_('Create by'))
|
||
7 years ago
|
date_created = models.DateTimeField(auto_now_add=True)
|
||
8 years ago
|
|
||
8 years ago
|
@property
|
||
7 years ago
|
def tasks(self):
|
||
|
return json.loads(self._tasks)
|
||
|
|
||
|
@tasks.setter
|
||
|
def tasks(self, item):
|
||
7 years ago
|
if item and isinstance(item, list):
|
||
|
self._tasks = json.dumps(item)
|
||
|
else:
|
||
7 years ago
|
raise SyntaxError('Tasks should be a list: {}'.format(item))
|
||
8 years ago
|
|
||
|
@property
|
||
7 years ago
|
def hosts(self):
|
||
|
return json.loads(self._hosts)
|
||
8 years ago
|
|
||
7 years ago
|
@hosts.setter
|
||
|
def hosts(self, item):
|
||
|
self._hosts = json.dumps(item)
|
||
8 years ago
|
|
||
7 years ago
|
@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
|
||
|
|
||
7 years ago
|
@property
|
||
7 years ago
|
def become(self):
|
||
|
if self._become:
|
||
|
return json.loads(signer.unsign(self._become))
|
||
|
else:
|
||
|
return {}
|
||
|
|
||
7 years ago
|
def run(self, record=True):
|
||
|
if record:
|
||
|
return self._run_and_record()
|
||
|
else:
|
||
|
return self._run_only()
|
||
|
|
||
|
def _run_and_record(self):
|
||
7 years ago
|
try:
|
||
|
hid = current_task.request.id
|
||
|
except AttributeError:
|
||
|
hid = str(uuid.uuid4())
|
||
|
history = AdHocRunHistory(id=hid, adhoc=self, task=self.task)
|
||
7 years ago
|
time_start = time.time()
|
||
|
try:
|
||
7 years ago
|
date_start = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||
|
print("{} Start task: {}\r\n".format(date_start, self.task.name))
|
||
7 years ago
|
raw, summary = self._run_only()
|
||
7 years ago
|
date_end = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||
|
print("\r\n{} Task finished".format(date_end))
|
||
7 years ago
|
history.is_finished = True
|
||
7 years ago
|
if summary.get('dark'):
|
||
7 years ago
|
history.is_success = False
|
||
|
else:
|
||
|
history.is_success = True
|
||
7 years ago
|
history.result = raw
|
||
|
history.summary = summary
|
||
|
return raw, summary
|
||
7 years ago
|
except Exception as e:
|
||
|
return {}, {"dark": {"all": str(e)}, "contacted": []}
|
||
7 years ago
|
finally:
|
||
7 years ago
|
# f.close()
|
||
7 years ago
|
history.date_finished = timezone.now()
|
||
|
history.timedelta = time.time() - time_start
|
||
|
history.save()
|
||
|
|
||
7 years ago
|
def _run_only(self, file_obj=None):
|
||
|
runner = AdHocRunner(self.inventory, options=self.options)
|
||
7 years ago
|
try:
|
||
7 years ago
|
result = runner.run(
|
||
|
self.tasks,
|
||
|
self.pattern,
|
||
|
self.task.name,
|
||
|
file_obj=file_obj,
|
||
|
)
|
||
7 years ago
|
return result.results_raw, result.results_summary
|
||
7 years ago
|
except AnsibleError as e:
|
||
7 years ago
|
logger.warn("Failed run adhoc {}, {}".format(self.task.name, e))
|
||
7 years ago
|
pass
|
||
7 years ago
|
|
||
7 years ago
|
@become.setter
|
||
|
def become(self, item):
|
||
|
"""
|
||
|
:param item: {
|
||
|
method: "sudo",
|
||
|
user: "user",
|
||
|
pass: "pass",
|
||
|
}
|
||
|
:return:
|
||
|
"""
|
||
7 years ago
|
self._become = signer.sign(json.dumps(item)).decode('utf-8')
|
||
7 years ago
|
|
||
|
@property
|
||
|
def options(self):
|
||
|
if self._options:
|
||
7 years ago
|
_options = json.loads(self._options)
|
||
|
if isinstance(_options, dict):
|
||
|
return _options
|
||
|
return {}
|
||
7 years ago
|
|
||
7 years ago
|
@options.setter
|
||
|
def options(self, item):
|
||
|
self._options = json.dumps(item)
|
||
7 years ago
|
|
||
7 years ago
|
@property
|
||
7 years ago
|
def short_id(self):
|
||
|
return str(self.id).split('-')[-1]
|
||
8 years ago
|
|
||
7 years ago
|
@property
|
||
|
def latest_history(self):
|
||
|
try:
|
||
|
return self.history.all().latest()
|
||
|
except AdHocRunHistory.DoesNotExist:
|
||
|
return None
|
||
7 years ago
|
|
||
7 years ago
|
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)
|
||
|
|
||
7 years ago
|
def __str__(self):
|
||
7 years ago
|
return "{} of {}".format(self.task.name, self.short_id)
|
||
7 years ago
|
|
||
7 years ago
|
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
|
||
|
|
||
7 years ago
|
class Meta:
|
||
7 years ago
|
db_table = "ops_adhoc"
|
||
7 years ago
|
get_latest_by = 'date_created'
|
||
7 years ago
|
|
||
7 years ago
|
|
||
7 years ago
|
class AdHocRunHistory(models.Model):
|
||
7 years ago
|
"""
|
||
|
AdHoc running history.
|
||
|
"""
|
||
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
||
7 years ago
|
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)
|
||
7 years ago
|
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'))
|
||
7 years ago
|
_result = models.TextField(blank=True, null=True, verbose_name=_('Adhoc raw result'))
|
||
|
_summary = models.TextField(blank=True, null=True, verbose_name=_('Adhoc result summary'))
|
||
7 years ago
|
|
||
|
@property
|
||
|
def short_id(self):
|
||
|
return str(self.id).split('-')[-1]
|
||
|
|
||
7 years ago
|
@property
|
||
|
def log_path(self):
|
||
|
dt = datetime.datetime.now().strftime('%Y-%m-%d')
|
||
|
log_dir = os.path.join(settings.PROJECT_DIR, 'data', 'ansible', dt)
|
||
|
if not os.path.exists(log_dir):
|
||
|
os.makedirs(log_dir)
|
||
|
return os.path.join(log_dir, str(self.id) + '.log')
|
||
|
|
||
7 years ago
|
@property
|
||
|
def result(self):
|
||
7 years ago
|
if self._result:
|
||
|
return json.loads(self._result)
|
||
|
else:
|
||
|
return {}
|
||
7 years ago
|
|
||
|
@result.setter
|
||
|
def result(self, item):
|
||
|
self._result = json.dumps(item)
|
||
|
|
||
|
@property
|
||
|
def summary(self):
|
||
7 years ago
|
if self._summary:
|
||
|
return json.loads(self._summary)
|
||
|
else:
|
||
|
return {"ok": {}, "dark": {}}
|
||
7 years ago
|
|
||
|
@summary.setter
|
||
|
def summary(self, item):
|
||
|
self._summary = json.dumps(item)
|
||
|
|
||
7 years ago
|
@property
|
||
|
def success_hosts(self):
|
||
|
return self.summary.get('contacted', [])
|
||
|
|
||
|
@property
|
||
|
def failed_hosts(self):
|
||
|
return self.summary.get('dark', {})
|
||
|
|
||
7 years ago
|
def __str__(self):
|
||
|
return self.short_id
|
||
7 years ago
|
|
||
|
class Meta:
|
||
|
db_table = "ops_adhoc_history"
|
||
7 years ago
|
get_latest_by = 'date_start'
|