jumpserver/apps/ops/utils.py

60 lines
1.7 KiB
Python
Raw Normal View History

2017-03-15 16:43:43 +00:00
# ~*~ coding: utf-8 ~*~
from django.utils.translation import ugettext_lazy as _
2017-12-22 13:42:12 +00:00
from common.utils import get_logger, get_object_or_none
from orgs.utils import set_to_root_org
2017-12-22 13:42:12 +00:00
from .models import Task, AdHoc
2017-03-15 16:43:43 +00:00
logger = get_logger(__file__)
2017-12-06 10:31:51 +00:00
2017-12-07 05:01:33 +00:00
2017-12-22 13:42:12 +00:00
def get_task_by_id(task_id):
return get_object_or_none(Task, id=task_id)
2017-12-10 16:29:25 +00:00
2017-12-24 10:53:07 +00:00
def update_or_create_ansible_task(
task_name, hosts, tasks, created_by,
2017-12-24 10:53:07 +00:00
interval=None, crontab=None, is_periodic=False,
callback=None, pattern='all', options=None,
run_as_admin=False, run_as=None, become_info=None,
2017-12-15 07:50:15 +00:00
):
if not hosts or not tasks or not task_name:
return
set_to_root_org()
2017-12-24 10:53:07 +00:00
defaults = {
'name': task_name,
'interval': interval,
'crontab': crontab,
'is_periodic': is_periodic,
'callback': callback,
'created_by': created_by,
}
2017-12-22 13:42:12 +00:00
2017-12-24 10:53:07 +00:00
created = False
task, ok = Task.objects.update_or_create(
defaults=defaults, name=task_name, created_by=created_by
2017-12-24 10:53:07 +00:00
)
adhoc = task.get_latest_adhoc()
2017-12-15 07:50:15 +00:00
new_adhoc = AdHoc(task=task, pattern=pattern,
run_as_admin=run_as_admin,
run_as=run_as)
new_adhoc.tasks = tasks
new_adhoc.options = options
new_adhoc.become = become_info
2017-12-24 10:53:07 +00:00
hosts_same = True
if adhoc:
old_hosts = set([str(asset.id) for asset in adhoc.hosts.all()])
new_hosts = set([str(asset.id) for asset in hosts])
hosts_same = old_hosts == new_hosts
if not adhoc or adhoc != new_adhoc or not hosts_same:
logger.info(_("Update task content: {}").format(task_name))
2017-12-15 07:50:15 +00:00
new_adhoc.save()
new_adhoc.hosts.set(hosts)
2017-12-15 07:50:15 +00:00
task.latest_adhoc = new_adhoc
2017-12-24 10:53:07 +00:00
created = True
return task, created
2017-12-22 13:42:12 +00:00
2017-12-10 16:29:25 +00:00