2022-11-16 13:06:14 +00:00
|
|
|
import json
|
2022-12-20 12:23:42 +00:00
|
|
|
import logging
|
2022-11-11 11:20:17 +00:00
|
|
|
import os
|
|
|
|
import uuid
|
2023-02-22 07:35:59 +00:00
|
|
|
from collections import defaultdict
|
2023-02-23 09:01:24 +00:00
|
|
|
from datetime import timedelta
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2022-12-20 12:23:42 +00:00
|
|
|
from celery import current_task
|
2022-11-11 11:20:17 +00:00
|
|
|
from django.conf import settings
|
|
|
|
from django.db import models
|
2023-02-22 07:35:59 +00:00
|
|
|
from django.db.models import Q
|
2022-11-11 11:20:17 +00:00
|
|
|
from django.utils import timezone
|
2022-12-20 12:23:42 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2023-02-22 07:35:59 +00:00
|
|
|
__all__ = ["Job", "JobExecution", "JMSPermedInventory"]
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2022-12-20 11:46:19 +00:00
|
|
|
from simple_history.models import HistoricalRecords
|
|
|
|
|
2023-02-22 07:35:59 +00:00
|
|
|
from accounts.models import Account
|
2023-02-14 08:34:55 +00:00
|
|
|
from acls.models import CommandFilterACL
|
2023-02-22 07:35:59 +00:00
|
|
|
from assets.models import Asset
|
2023-06-14 11:48:43 +00:00
|
|
|
from ops.ansible import JMSInventory, AdHocRunner, PlaybookRunner, CommandInBlackListException
|
2022-11-18 10:46:48 +00:00
|
|
|
from ops.mixin import PeriodTaskModelMixin
|
2022-12-06 11:43:32 +00:00
|
|
|
from ops.variables import *
|
2022-12-19 10:04:11 +00:00
|
|
|
from ops.const import Types, Modules, RunasPolicies, JobStatus
|
2022-12-15 09:25:21 +00:00
|
|
|
from orgs.mixins.models import JMSOrgBaseModel
|
2023-02-22 07:35:59 +00:00
|
|
|
from perms.models import AssetPermission
|
|
|
|
from perms.utils import UserPermAssetUtil
|
2023-02-14 08:34:55 +00:00
|
|
|
from terminal.notifications import CommandExecutionAlert
|
2023-07-17 12:52:54 +00:00
|
|
|
from terminal.notifications import CommandWarningMessage
|
2023-07-19 02:11:47 +00:00
|
|
|
from terminal.const import RiskLevelChoices
|
2022-11-11 11:20:17 +00:00
|
|
|
|
|
|
|
|
2023-02-22 07:35:59 +00:00
|
|
|
def get_parent_keys(key, include_self=True):
|
|
|
|
keys = []
|
|
|
|
split_keys = key.split(':')
|
|
|
|
for i in range(len(split_keys)):
|
|
|
|
keys.append(':'.join(split_keys[:i + 1]))
|
|
|
|
if not include_self:
|
|
|
|
keys.pop()
|
|
|
|
return keys
|
|
|
|
|
|
|
|
|
|
|
|
class JMSPermedInventory(JMSInventory):
|
|
|
|
def __init__(self, assets, account_policy='privileged_first',
|
2023-08-01 02:39:34 +00:00
|
|
|
account_prefer='root,Administrator', host_callback=None, user=None):
|
|
|
|
super().__init__(assets, account_policy, account_prefer, host_callback, exclude_localhost=True)
|
2023-02-22 07:35:59 +00:00
|
|
|
self.user = user
|
|
|
|
self.assets_accounts_mapper = self.get_assets_accounts_mapper()
|
|
|
|
|
2023-03-16 11:06:50 +00:00
|
|
|
def get_asset_sorted_accounts(self, asset):
|
2023-04-12 10:13:55 +00:00
|
|
|
accounts = self.assets_accounts_mapper.get(asset.id, [])
|
|
|
|
return list(accounts)
|
2023-02-22 07:35:59 +00:00
|
|
|
|
|
|
|
def get_assets_accounts_mapper(self):
|
|
|
|
mapper = defaultdict(set)
|
|
|
|
asset_ids = self.assets.values_list('id', flat=True)
|
2023-02-22 10:06:46 +00:00
|
|
|
asset_node_keys = Asset.nodes.through.objects \
|
|
|
|
.filter(asset_id__in=asset_ids) \
|
|
|
|
.values_list('asset_id', 'node__key')
|
2023-02-22 07:35:59 +00:00
|
|
|
|
|
|
|
node_asset_map = defaultdict(set)
|
|
|
|
for asset_id, node_key in asset_node_keys:
|
|
|
|
all_keys = get_parent_keys(node_key)
|
|
|
|
for key in all_keys:
|
|
|
|
node_asset_map[key].add(asset_id)
|
|
|
|
|
2023-02-22 10:06:46 +00:00
|
|
|
groups = self.user.groups.all()
|
2023-02-22 07:35:59 +00:00
|
|
|
perms = AssetPermission.objects \
|
2023-02-22 10:06:46 +00:00
|
|
|
.filter(date_expired__gte=timezone.now()) \
|
2023-02-22 07:35:59 +00:00
|
|
|
.filter(is_active=True) \
|
2023-02-22 10:06:46 +00:00
|
|
|
.filter(Q(users=self.user) | Q(user_groups__in=groups)) \
|
|
|
|
.filter(Q(assets__in=asset_ids) | Q(nodes__key__in=node_asset_map.keys())) \
|
2023-02-22 07:35:59 +00:00
|
|
|
.values_list('assets', 'nodes__key', 'accounts')
|
|
|
|
|
|
|
|
asset_permed_accounts_mapper = defaultdict(set)
|
2023-02-22 10:06:46 +00:00
|
|
|
for asset_id, node_key, accounts in perms:
|
|
|
|
if asset_id in asset_ids:
|
2023-02-22 07:35:59 +00:00
|
|
|
asset_permed_accounts_mapper[asset_id].update(accounts)
|
2023-02-22 10:06:46 +00:00
|
|
|
for my_asset in node_asset_map[node_key]:
|
|
|
|
asset_permed_accounts_mapper[my_asset].update(accounts)
|
2023-02-22 07:35:59 +00:00
|
|
|
|
|
|
|
accounts = Account.objects.filter(asset__in=asset_ids)
|
|
|
|
for account in accounts:
|
|
|
|
if account.asset_id not in asset_permed_accounts_mapper:
|
|
|
|
continue
|
|
|
|
permed_usernames = asset_permed_accounts_mapper[account.asset_id]
|
|
|
|
if "@ALL" in permed_usernames or account.username in permed_usernames:
|
|
|
|
mapper[account.asset_id].add(account)
|
|
|
|
return mapper
|
|
|
|
|
|
|
|
|
2022-12-15 09:25:21 +00:00
|
|
|
class Job(JMSOrgBaseModel, PeriodTaskModelMixin):
|
2022-11-11 11:20:17 +00:00
|
|
|
name = models.CharField(max_length=128, null=True, verbose_name=_('Name'))
|
2023-02-17 11:38:34 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
instant = models.BooleanField(default=False)
|
2023-04-13 07:47:16 +00:00
|
|
|
args = models.CharField(max_length=8192, default='', verbose_name=_('Args'), null=True, blank=True)
|
2023-02-17 11:38:34 +00:00
|
|
|
module = models.CharField(max_length=128, choices=Modules.choices, default=Modules.shell, verbose_name=_('Module'),
|
|
|
|
null=True)
|
2022-11-16 13:06:14 +00:00
|
|
|
chdir = models.CharField(default="", max_length=1024, verbose_name=_('Chdir'), null=True, blank=True)
|
2022-12-27 08:06:21 +00:00
|
|
|
timeout = models.IntegerField(default=-1, verbose_name=_('Timeout (Seconds)'))
|
2023-02-17 11:38:34 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
playbook = models.ForeignKey('ops.Playbook', verbose_name=_("Playbook"), null=True, on_delete=models.SET_NULL)
|
2023-02-17 11:38:34 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
type = models.CharField(max_length=128, choices=Types.choices, default=Types.adhoc, verbose_name=_("Type"))
|
2022-12-06 03:03:14 +00:00
|
|
|
creator = models.ForeignKey('users.User', verbose_name=_("Creator"), on_delete=models.SET_NULL, null=True)
|
2022-11-11 11:20:17 +00:00
|
|
|
assets = models.ManyToManyField('assets.Asset', verbose_name=_("Assets"))
|
2023-02-17 11:38:34 +00:00
|
|
|
use_parameter_define = models.BooleanField(default=False, verbose_name=(_('Use Parameter Define')))
|
|
|
|
parameters_define = models.JSONField(default=dict, verbose_name=_('Parameters define'))
|
2022-11-11 11:20:17 +00:00
|
|
|
runas = models.CharField(max_length=128, default='root', verbose_name=_('Runas'))
|
|
|
|
runas_policy = models.CharField(max_length=128, choices=RunasPolicies.choices, default=RunasPolicies.skip,
|
|
|
|
verbose_name=_('Runas policy'))
|
2022-11-16 13:06:14 +00:00
|
|
|
comment = models.CharField(max_length=1024, default='', verbose_name=_('Comment'), null=True, blank=True)
|
2022-12-20 11:46:19 +00:00
|
|
|
version = models.IntegerField(default=0)
|
|
|
|
history = HistoricalRecords()
|
|
|
|
|
2023-02-20 08:05:35 +00:00
|
|
|
def __str__(self):
|
|
|
|
return self.name
|
|
|
|
|
2022-12-20 11:46:19 +00:00
|
|
|
def get_history(self, version):
|
|
|
|
return self.history.filter(version=version).first()
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2022-11-18 10:46:48 +00:00
|
|
|
@property
|
|
|
|
def last_execution(self):
|
2023-02-22 10:53:35 +00:00
|
|
|
return self.executions.first()
|
2022-11-18 10:46:48 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def date_last_run(self):
|
|
|
|
return self.last_execution.date_created if self.last_execution else None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def summary(self):
|
|
|
|
summary = {
|
|
|
|
"total": 0,
|
|
|
|
"success": 0,
|
|
|
|
}
|
|
|
|
for execution in self.executions.all():
|
|
|
|
summary["total"] += 1
|
|
|
|
if execution.is_success:
|
|
|
|
summary["success"] += 1
|
|
|
|
return summary
|
|
|
|
|
|
|
|
@property
|
|
|
|
def average_time_cost(self):
|
|
|
|
total_cost = 0
|
|
|
|
finished_count = self.executions.filter(status__in=['success', 'failed']).count()
|
|
|
|
for execution in self.executions.filter(status__in=['success', 'failed']).all():
|
|
|
|
total_cost += execution.time_cost
|
|
|
|
return total_cost / finished_count if finished_count else 0
|
|
|
|
|
|
|
|
def get_register_task(self):
|
2023-02-10 10:37:53 +00:00
|
|
|
from ..tasks import run_ops_job
|
2022-11-18 10:46:48 +00:00
|
|
|
name = "run_ops_job_period_{}".format(str(self.id)[:8])
|
2023-02-10 10:37:53 +00:00
|
|
|
task = run_ops_job.name
|
2022-11-18 10:46:48 +00:00
|
|
|
args = (str(self.id),)
|
|
|
|
kwargs = {}
|
|
|
|
return name, task, args, kwargs
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
@property
|
|
|
|
def inventory(self):
|
2023-02-22 07:35:59 +00:00
|
|
|
return JMSPermedInventory(self.assets.all(), self.runas_policy, self.runas, user=self.creator)
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2023-02-07 03:25:13 +00:00
|
|
|
@property
|
|
|
|
def material(self):
|
|
|
|
if self.type == 'adhoc':
|
|
|
|
return "{}:{}".format(self.module, self.args)
|
|
|
|
if self.type == 'playbook':
|
|
|
|
return "{}:{}:{}".format(self.org.name, self.creator.name, self.playbook.name)
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
def create_execution(self):
|
2023-02-09 09:00:54 +00:00
|
|
|
return self.executions.create(job_version=self.version, material=self.material, job_type=Types[self.type].value)
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2022-11-25 19:13:06 +00:00
|
|
|
class Meta:
|
2022-12-23 07:49:32 +00:00
|
|
|
verbose_name = _("Job")
|
2023-02-13 07:05:31 +00:00
|
|
|
unique_together = [('name', 'org_id', 'creator')]
|
2022-11-25 19:13:06 +00:00
|
|
|
ordering = ['date_created']
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2023-02-23 09:01:24 +00:00
|
|
|
zombie_task_exception = Exception(
|
|
|
|
'This task has been marked as a zombie task because it has not updated its status for too long')
|
|
|
|
|
|
|
|
|
2022-12-15 09:25:21 +00:00
|
|
|
class JobExecution(JMSOrgBaseModel):
|
2022-11-11 11:20:17 +00:00
|
|
|
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
|
|
|
|
task_id = models.UUIDField(null=True)
|
2022-12-19 10:04:11 +00:00
|
|
|
status = models.CharField(max_length=16, verbose_name=_('Status'), default=JobStatus.running)
|
2023-02-03 08:44:05 +00:00
|
|
|
job = models.ForeignKey(Job, on_delete=models.SET_NULL, related_name='executions', null=True)
|
2022-12-20 11:46:19 +00:00
|
|
|
job_version = models.IntegerField(default=0)
|
2022-11-17 12:10:13 +00:00
|
|
|
parameters = models.JSONField(default=dict, verbose_name=_('Parameters'))
|
2022-11-11 11:20:17 +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)
|
|
|
|
date_finished = models.DateTimeField(null=True, verbose_name=_("Date finished"))
|
|
|
|
|
2023-04-13 07:47:16 +00:00
|
|
|
material = models.CharField(max_length=8192, default='', verbose_name=_('Material'), null=True, blank=True)
|
2023-02-07 03:25:13 +00:00
|
|
|
job_type = models.CharField(max_length=128, choices=Types.choices, default=Types.adhoc,
|
|
|
|
verbose_name=_("Material Type"))
|
|
|
|
|
2023-02-23 09:01:24 +00:00
|
|
|
# clean up zombie execution
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def clean_unexpected_execution(cls):
|
|
|
|
for execution in cls.objects.filter(status__in=[JobStatus.running]).all():
|
|
|
|
if execution.date_created < (timezone.now() - timedelta(hours=3)):
|
|
|
|
execution.set_error(zombie_task_exception)
|
|
|
|
|
2022-12-20 11:46:19 +00:00
|
|
|
@property
|
|
|
|
def current_job(self):
|
|
|
|
if self.job.version != self.job_version:
|
|
|
|
return self.job.get_history(self.job_version)
|
|
|
|
return self.job
|
|
|
|
|
2022-12-07 12:13:26 +00:00
|
|
|
@property
|
|
|
|
def assent_result_detail(self):
|
2023-02-03 08:44:05 +00:00
|
|
|
if not self.is_finished or self.summary.get('error'):
|
|
|
|
return None
|
|
|
|
result = {
|
|
|
|
"summary": self.summary,
|
|
|
|
"detail": [],
|
|
|
|
}
|
|
|
|
for asset in self.current_job.assets.all():
|
|
|
|
asset_detail = {
|
|
|
|
"name": asset.name,
|
|
|
|
"status": "ok",
|
|
|
|
"tasks": [],
|
2022-12-07 12:13:26 +00:00
|
|
|
}
|
2023-02-03 08:44:05 +00:00
|
|
|
if self.summary.get("excludes", None) and self.summary["excludes"].get(asset.name, None):
|
|
|
|
asset_detail.update({"status": "excludes"})
|
2022-12-07 12:13:26 +00:00
|
|
|
result["detail"].append(asset_detail)
|
2023-02-03 08:44:05 +00:00
|
|
|
break
|
|
|
|
if self.result["dark"].get(asset.name, None):
|
|
|
|
asset_detail.update({"status": "failed"})
|
|
|
|
for key, task in self.result["dark"][asset.name].items():
|
|
|
|
task_detail = {"name": key,
|
|
|
|
"output": "{}{}".format(task.get("stdout", ""), task.get("stderr", ""))}
|
|
|
|
asset_detail["tasks"].append(task_detail)
|
|
|
|
if self.result["failures"].get(asset.name, None):
|
|
|
|
asset_detail.update({"status": "failed"})
|
|
|
|
for key, task in self.result["failures"][asset.name].items():
|
|
|
|
task_detail = {"name": key,
|
|
|
|
"output": "{}{}".format(task.get("stdout", ""), task.get("stderr", ""))}
|
|
|
|
asset_detail["tasks"].append(task_detail)
|
|
|
|
|
|
|
|
if self.result["ok"].get(asset.name, None):
|
|
|
|
for key, task in self.result["ok"][asset.name].items():
|
|
|
|
task_detail = {"name": key,
|
|
|
|
"output": "{}{}".format(task.get("stdout", ""), task.get("stderr", ""))}
|
|
|
|
asset_detail["tasks"].append(task_detail)
|
|
|
|
result["detail"].append(asset_detail)
|
|
|
|
return result
|
2022-12-07 12:13:26 +00:00
|
|
|
|
2022-11-30 08:24:17 +00:00
|
|
|
def compile_shell(self):
|
2022-12-20 11:46:19 +00:00
|
|
|
if self.current_job.type != 'adhoc':
|
2022-11-30 08:24:17 +00:00
|
|
|
return
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
module = self.current_job.module
|
|
|
|
# replace win_shell
|
|
|
|
if module == 'win_shell':
|
|
|
|
module = 'ansible.windows.win_shell'
|
|
|
|
|
|
|
|
if self.current_job.module in ['python']:
|
|
|
|
module = "shell"
|
|
|
|
|
|
|
|
shell = self.current_job.args
|
2022-12-27 07:04:43 +00:00
|
|
|
if self.current_job.chdir:
|
2023-02-06 08:19:43 +00:00
|
|
|
if module == "shell":
|
2023-01-16 11:02:09 +00:00
|
|
|
shell += " chdir={}".format(self.current_job.chdir)
|
2022-12-26 11:02:05 +00:00
|
|
|
if self.current_job.module in ['python']:
|
2023-01-16 11:02:09 +00:00
|
|
|
shell += " executable={}".format(self.current_job.module)
|
|
|
|
return module, shell
|
2022-11-30 08:24:17 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
def get_runner(self):
|
2022-12-20 11:46:19 +00:00
|
|
|
inv = self.current_job.inventory
|
2022-11-11 11:20:17 +00:00
|
|
|
inv.write_to_file(self.inventory_path)
|
2022-12-20 08:36:22 +00:00
|
|
|
self.summary = self.result = {"excludes": {}}
|
2022-12-07 12:13:26 +00:00
|
|
|
if len(inv.exclude_hosts) > 0:
|
2022-12-20 08:36:22 +00:00
|
|
|
self.summary.update({"excludes": inv.exclude_hosts})
|
|
|
|
self.result.update({"excludes": inv.exclude_hosts})
|
2022-12-07 12:13:26 +00:00
|
|
|
self.save()
|
|
|
|
|
2022-11-18 10:46:48 +00:00
|
|
|
if isinstance(self.parameters, str):
|
|
|
|
extra_vars = json.loads(self.parameters)
|
|
|
|
else:
|
|
|
|
extra_vars = {}
|
2022-11-11 11:20:17 +00:00
|
|
|
|
2022-12-06 11:43:32 +00:00
|
|
|
static_variables = self.gather_static_variables()
|
|
|
|
extra_vars.update(static_variables)
|
|
|
|
|
2022-12-20 11:46:19 +00:00
|
|
|
if self.current_job.type == 'adhoc':
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
module, args = self.compile_shell()
|
2022-12-26 11:02:05 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
runner = AdHocRunner(
|
2022-12-26 11:02:05 +00:00
|
|
|
self.inventory_path,
|
|
|
|
module,
|
2022-12-27 08:06:21 +00:00
|
|
|
timeout=self.current_job.timeout,
|
2022-12-26 11:02:05 +00:00
|
|
|
module_args=args,
|
|
|
|
pattern="all",
|
|
|
|
project_dir=self.private_dir,
|
|
|
|
extra_vars=extra_vars,
|
2022-11-11 11:20:17 +00:00
|
|
|
)
|
2022-12-20 11:46:19 +00:00
|
|
|
elif self.current_job.type == 'playbook':
|
2022-11-11 11:20:17 +00:00
|
|
|
runner = PlaybookRunner(
|
2022-12-20 11:46:19 +00:00
|
|
|
self.inventory_path, self.current_job.playbook.entry
|
2022-11-11 11:20:17 +00:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise Exception("unsupported job type")
|
|
|
|
return runner
|
|
|
|
|
2022-12-06 11:43:32 +00:00
|
|
|
def gather_static_variables(self):
|
|
|
|
default = {
|
2022-12-20 11:46:19 +00:00
|
|
|
JMS_JOB_ID: str(self.current_job.id),
|
|
|
|
JMS_JOB_NAME: self.current_job.name,
|
2022-12-06 11:43:32 +00:00
|
|
|
}
|
2022-12-15 09:25:21 +00:00
|
|
|
if self.creator:
|
|
|
|
default.update({JMS_USERNAME: self.creator.username})
|
2022-12-06 11:43:32 +00:00
|
|
|
return default
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
@property
|
|
|
|
def short_id(self):
|
|
|
|
return str(self.id).split('-')[-1]
|
|
|
|
|
2022-11-16 07:04:46 +00:00
|
|
|
@property
|
|
|
|
def time_cost(self):
|
2023-02-09 12:11:12 +00:00
|
|
|
if not self.date_start:
|
|
|
|
return 0
|
2023-01-16 11:02:09 +00:00
|
|
|
if self.is_finished:
|
2022-11-16 07:04:46 +00:00
|
|
|
return (self.date_finished - self.date_start).total_seconds()
|
2023-01-16 11:02:09 +00:00
|
|
|
return (timezone.now() - self.date_start).total_seconds()
|
2022-11-16 07:04:46 +00:00
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
@property
|
|
|
|
def timedelta(self):
|
|
|
|
if self.date_start and self.date_finished:
|
|
|
|
return self.date_finished - self.date_start
|
|
|
|
return None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_finished(self):
|
2022-12-27 07:04:43 +00:00
|
|
|
return self.status in [JobStatus.success, JobStatus.failed, JobStatus.timeout]
|
2022-11-11 11:20:17 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_success(self):
|
2022-12-19 10:04:11 +00:00
|
|
|
return self.status == JobStatus.success
|
2022-11-11 11:20:17 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def inventory_path(self):
|
|
|
|
return os.path.join(self.private_dir, 'inventory', 'hosts')
|
|
|
|
|
|
|
|
@property
|
|
|
|
def private_dir(self):
|
|
|
|
uniq = self.date_created.strftime('%Y%m%d_%H%M%S') + '_' + self.short_id
|
2022-12-20 11:46:19 +00:00
|
|
|
job_name = self.current_job.name if self.current_job.name else 'instant'
|
2022-11-11 11:20:17 +00:00
|
|
|
return os.path.join(settings.ANSIBLE_DIR, job_name, uniq)
|
|
|
|
|
|
|
|
def set_error(self, error):
|
|
|
|
this = self.__class__.objects.get(id=self.id) # 重新获取一次,避免数据库超时连接超时
|
2022-12-19 10:04:11 +00:00
|
|
|
this.status = JobStatus.failed
|
2022-12-07 12:13:26 +00:00
|
|
|
this.summary.update({'error': str(error)})
|
2022-11-11 11:20:17 +00:00
|
|
|
this.finish_task()
|
|
|
|
|
|
|
|
def set_result(self, cb):
|
|
|
|
status_mapper = {
|
2022-12-19 10:04:11 +00:00
|
|
|
'successful': JobStatus.success,
|
2022-11-11 11:20:17 +00:00
|
|
|
}
|
|
|
|
this = self.__class__.objects.get(id=self.id)
|
|
|
|
this.status = status_mapper.get(cb.status, cb.status)
|
2022-12-07 12:13:26 +00:00
|
|
|
this.summary.update(cb.summary)
|
2022-12-15 09:25:21 +00:00
|
|
|
if this.result:
|
|
|
|
this.result.update(cb.result)
|
|
|
|
else:
|
|
|
|
this.result = cb.result
|
2022-11-11 11:20:17 +00:00
|
|
|
this.finish_task()
|
|
|
|
|
|
|
|
def finish_task(self):
|
|
|
|
self.date_finished = timezone.now()
|
|
|
|
self.save(update_fields=['result', 'status', 'summary', 'date_finished'])
|
|
|
|
|
|
|
|
def set_celery_id(self):
|
|
|
|
if not current_task:
|
|
|
|
return
|
|
|
|
task_id = current_task.request.root_id
|
|
|
|
self.task_id = task_id
|
|
|
|
|
2023-02-14 08:34:55 +00:00
|
|
|
def match_command_group(self, acl, asset):
|
|
|
|
for cg in acl.command_groups.all():
|
2023-02-14 08:43:47 +00:00
|
|
|
matched, __ = cg.match(self.current_job.args)
|
2023-02-14 08:34:55 +00:00
|
|
|
if matched:
|
|
|
|
if acl.is_action(CommandFilterACL.ActionChoices.accept):
|
|
|
|
return True
|
|
|
|
elif acl.is_action(CommandFilterACL.ActionChoices.reject) or acl.is_action(
|
|
|
|
CommandFilterACL.ActionChoices.review):
|
|
|
|
print("\033[31mcommand \'{}\' on asset {}({}) is rejected by acl {}\033[0m"
|
|
|
|
.format(self.current_job.args, asset.name, asset.address, acl))
|
|
|
|
CommandExecutionAlert({
|
|
|
|
"assets": self.current_job.assets.all(),
|
|
|
|
"input": self.material,
|
2023-07-19 03:00:58 +00:00
|
|
|
"risk_level": RiskLevelChoices.reject,
|
2023-02-14 08:34:55 +00:00
|
|
|
"user": self.creator,
|
|
|
|
}).publish_async()
|
|
|
|
raise Exception("command is rejected by ACL")
|
2023-07-17 12:52:54 +00:00
|
|
|
elif acl.is_action(CommandFilterACL.ActionChoices.warning):
|
2023-07-19 02:11:47 +00:00
|
|
|
command = {
|
|
|
|
'input': self.material,
|
2023-07-19 03:00:58 +00:00
|
|
|
'user': self.creator.name,
|
2023-07-19 02:11:47 +00:00
|
|
|
'asset': asset.name,
|
2023-07-19 03:00:58 +00:00
|
|
|
'cmd_filter_acl': str(acl.id),
|
|
|
|
'cmd_group': str(cg.id),
|
|
|
|
'risk_level': RiskLevelChoices.warning,
|
|
|
|
'org_id': self.org_id,
|
2023-07-19 02:11:47 +00:00
|
|
|
'_account': self.current_job.runas,
|
|
|
|
'_cmd_filter_acl': acl,
|
|
|
|
'_cmd_group': cg,
|
2023-07-19 03:00:58 +00:00
|
|
|
'_org_name': self.org_name,
|
2023-07-19 02:11:47 +00:00
|
|
|
}
|
2023-07-19 03:00:58 +00:00
|
|
|
for reviewer in acl.reviewers.all():
|
|
|
|
CommandWarningMessage(reviewer, command).publish_async()
|
2023-07-17 12:52:54 +00:00
|
|
|
return True
|
2023-02-14 08:34:55 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
def check_command_acl(self):
|
|
|
|
for asset in self.current_job.assets.all():
|
2023-04-20 02:33:53 +00:00
|
|
|
acls = CommandFilterACL.filter_queryset(
|
|
|
|
user=self.creator,
|
|
|
|
asset=asset,
|
|
|
|
is_active=True,
|
|
|
|
account_username=self.current_job.runas)
|
2023-02-14 08:34:55 +00:00
|
|
|
for acl in acls:
|
|
|
|
if self.match_command_group(acl, asset):
|
|
|
|
break
|
|
|
|
|
2023-02-13 11:22:52 +00:00
|
|
|
def check_danger_keywords(self):
|
|
|
|
lines = self.job.playbook.check_dangerous_keywords()
|
|
|
|
if len(lines) > 0:
|
|
|
|
for line in lines:
|
|
|
|
print('\033[31mThe {} line of the file \'{}\' contains the '
|
|
|
|
'dangerous keyword \'{}\'\033[0m'.format(line['line'], line['file'], line['keyword']))
|
|
|
|
raise Exception("Playbook contains dangerous keywords")
|
|
|
|
|
2023-02-22 10:06:46 +00:00
|
|
|
def check_assets_perms(self):
|
|
|
|
all_permed_assets = UserPermAssetUtil(self.creator).get_all_assets()
|
|
|
|
has_permed_assets = set(self.current_job.assets.all()) & set(all_permed_assets)
|
|
|
|
|
2023-02-22 12:05:31 +00:00
|
|
|
error_assets_count = 0
|
2023-02-22 10:06:46 +00:00
|
|
|
for asset in self.current_job.assets.all():
|
|
|
|
if asset not in has_permed_assets:
|
|
|
|
print("\033[31mAsset {}({}) has no access permission\033[0m".format(asset.name, asset.address))
|
2023-02-22 12:05:31 +00:00
|
|
|
error_assets_count += 1
|
2023-02-22 10:06:46 +00:00
|
|
|
|
2023-02-22 12:05:31 +00:00
|
|
|
if error_assets_count > 0:
|
|
|
|
raise Exception("You do not have access rights to {} assets".format(error_assets_count))
|
2023-02-22 10:06:46 +00:00
|
|
|
|
2023-02-14 08:34:55 +00:00
|
|
|
def before_start(self):
|
2023-02-22 10:06:46 +00:00
|
|
|
self.check_assets_perms()
|
2023-02-14 08:34:55 +00:00
|
|
|
if self.current_job.type == 'playbook':
|
|
|
|
self.check_danger_keywords()
|
|
|
|
if self.current_job.type == 'adhoc':
|
|
|
|
self.check_command_acl()
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
def start(self, **kwargs):
|
|
|
|
self.date_start = timezone.now()
|
|
|
|
self.set_celery_id()
|
|
|
|
self.save()
|
2023-02-14 08:34:55 +00:00
|
|
|
self.before_start()
|
|
|
|
|
2022-11-11 11:20:17 +00:00
|
|
|
runner = self.get_runner()
|
|
|
|
try:
|
|
|
|
cb = runner.run(**kwargs)
|
|
|
|
self.set_result(cb)
|
|
|
|
return cb
|
2023-06-14 11:48:43 +00:00
|
|
|
except CommandInBlackListException as e:
|
2023-06-14 12:04:20 +00:00
|
|
|
print(e)
|
2023-06-14 12:38:18 +00:00
|
|
|
self.set_error(e)
|
2022-11-11 11:20:17 +00:00
|
|
|
except Exception as e:
|
|
|
|
logging.error(e, exc_info=True)
|
|
|
|
self.set_error(e)
|
2022-11-25 19:13:06 +00:00
|
|
|
|
|
|
|
class Meta:
|
2022-12-23 07:49:32 +00:00
|
|
|
verbose_name = _("Job Execution")
|
2023-02-14 08:43:47 +00:00
|
|
|
ordering = ['-date_created']
|