jumpserver/apps/ops/models/adhoc.py

381 lines
13 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
2018-03-30 14:03:43 +00:00
import os
2017-12-21 18:08:29 +00:00
import time
2018-03-30 14:03:43 +00:00
import datetime
2018-04-01 15:45:37 +00:00
from celery import current_task
2017-03-09 06:55:33 +00:00
from django.db import models
2018-03-30 14:03:43 +00:00
from django.conf import settings
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 _
2018-04-02 07:54:49 +00:00
from django_celery_beat.models import 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
2018-08-24 04:08:42 +00:00
from orgs.utils import set_to_root_org
2018-04-02 07:54:49 +00:00
from ..celery.utils import delete_celery_periodic_task, \
2018-03-30 14:03:43 +00:00
create_or_update_celery_periodic_tasks, \
disable_celery_periodic_task
2018-04-02 07:54:49 +00:00
from ..ansible import AdHocRunner, AnsibleError
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)
name = models.CharField(max_length=128, 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"))
created_by = models.CharField(max_length=128, blank=True, default='')
date_created = models.DateTimeField(auto_now_add=True, db_index=True)
2017-12-15 07:50:15 +00:00
__latest_adhoc = None
_ignore_auto_created_by = True
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):
2018-08-24 04:08:42 +00:00
set_to_root_org()
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):
2018-04-02 07:54:49 +00:00
from ..tasks import run_ansible_task
2017-12-22 13:42:12 +00:00
super().save(
force_insert=force_insert, force_update=force_update,
2017-12-21 18:08:29 +00:00
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.__str__(): {
2017-12-22 13:42:12 +00:00
"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:
disable_celery_periodic_task(self.__str__())
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.__str__())
2017-12-22 13:42:12 +00:00
@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 + '@' + str(self.created_by)
2017-12-15 07:50:15 +00:00
2017-12-10 16:29:25 +00:00
class Meta:
db_table = 'ops_task'
unique_together = ('name', 'created_by')
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
[Feature] 添加资产用户管理器 (#2489) * [Feature] 1. 资产用户管理器 * [Feature] 2. 资产用户管理器: 更新AuthBook * [Feature] 3. 资产用户管理器: 添加 AssetUser API * [Feature] 4. AssetUser Model: 添加方法 load_related_asset_auth * [Feature] 5. AdminUser: 更新管理用户获取认证信息时,先加载相关资产的认证 * [Feature] 6. SystemUser: 更新系统用户获取认证信息时,先加载相关资产的认证 * [Feature] 前端页面: 添加资产用户列表页面 * [Feature] 前端页面: 管理用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 前端页面: 系统用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 优化: 从管理用户和系统用户的backend中获取相关资产用户的逻辑 * [Update] Fix 1 * [Feature] 优化: SystemUserBackend之filter功能 * [Feature] 优化: AdminUserBackend之filter功能 * [Feature] 优化: AdminUserBackend和SystemUserBackend功能 * [Feature] 更新翻译: 资产用户管理器 * [Update] 更新资产用户列表页名称为: asset_asset_user_list.html * [Bugfix] 修改bug: SystemUserBackend 根据用户名过滤系统用户 * [Feature] 添加: 资产用户列表中可测试资产用户的连接性 * [Update] 修改: AdHoc model的run_as字段从SystemUser外键修改为username字符串 * [Feature] 添加: 获取系统用户认证信息(对应某个资产)API * [Update] 更新: API获取asset user时进行排序 * [Bugfix] 修改: 资产用户可连接性CACHE_KEY * [Update] 更新翻译信息 * [Update] 修改获取资产用户认证信息API的返回响应(200/400) * [Update] 修改BaseUser获取特定资产的方法名 * [Update] 修改logger输出,AuthBook set_version_and_latest * [Update] 修改日志输出添加exc_info参数 * [Update] 移除AuthBook迁移文件0026 * [Bugfix] 修复AdminUserBackend获取instances为空的bug
2019-03-18 02:15:33 +00:00
run_as: username(Add the uniform AssetUserManager <AssetUserManager> and change it to username)
2017-12-10 16:29:25 +00:00
_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']
hosts = models.ManyToManyField('assets.Asset', verbose_name=_("Host"))
2017-12-07 05:01:33 +00:00
run_as_admin = models.BooleanField(default=False, verbose_name=_('Run as admin'))
[Feature] 添加资产用户管理器 (#2489) * [Feature] 1. 资产用户管理器 * [Feature] 2. 资产用户管理器: 更新AuthBook * [Feature] 3. 资产用户管理器: 添加 AssetUser API * [Feature] 4. AssetUser Model: 添加方法 load_related_asset_auth * [Feature] 5. AdminUser: 更新管理用户获取认证信息时,先加载相关资产的认证 * [Feature] 6. SystemUser: 更新系统用户获取认证信息时,先加载相关资产的认证 * [Feature] 前端页面: 添加资产用户列表页面 * [Feature] 前端页面: 管理用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 前端页面: 系统用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 优化: 从管理用户和系统用户的backend中获取相关资产用户的逻辑 * [Update] Fix 1 * [Feature] 优化: SystemUserBackend之filter功能 * [Feature] 优化: AdminUserBackend之filter功能 * [Feature] 优化: AdminUserBackend和SystemUserBackend功能 * [Feature] 更新翻译: 资产用户管理器 * [Update] 更新资产用户列表页名称为: asset_asset_user_list.html * [Bugfix] 修改bug: SystemUserBackend 根据用户名过滤系统用户 * [Feature] 添加: 资产用户列表中可测试资产用户的连接性 * [Update] 修改: AdHoc model的run_as字段从SystemUser外键修改为username字符串 * [Feature] 添加: 获取系统用户认证信息(对应某个资产)API * [Update] 更新: API获取asset user时进行排序 * [Bugfix] 修改: 资产用户可连接性CACHE_KEY * [Update] 更新翻译信息 * [Update] 修改获取资产用户认证信息API的返回响应(200/400) * [Update] 修改BaseUser获取特定资产的方法名 * [Update] 修改logger输出,AuthBook set_version_and_latest * [Update] 修改日志输出添加exc_info参数 * [Update] 移除AuthBook迁移文件0026 * [Bugfix] 修复AdminUserBackend获取instances为空的bug
2019-03-18 02:15:33 +00:00
run_as = models.CharField(max_length=64, default='', null=True, verbose_name=_('Username'))
2017-12-10 16:29:25 +00:00
_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'))
2018-12-20 02:40:52 +00:00
date_created = models.DateTimeField(auto_now_add=True, db_index=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):
try:
return json.loads(self._tasks)
except:
return []
2017-12-07 05:01:33 +00:00
@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
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.all(), run_as_admin=self.run_as_admin,
2017-12-22 13:42:12 +00:00
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):
Dev2 (#1766) * [Update] 初始化操作日志 * [Feature] 完成操作日志记录 * [Update] 修改mfa失败提示 * [Update] 修改增加created by内容 * [Update] 增加改密日志 * [Update] 登录日志迁移到日志审计中 * [Update] change block user logic, if login success, clean block limit * [Update] 更新中/英文翻译(ALL) (#1662) * Revert "授权页面分页问题" * 增加命令导出 (#1566) * [Update] gunicorn不使用eventlet * [Update] 添加eventlet * 替换淘宝IP查询接口 * [Feature] 添加命令记录下载功能 (#1559) * [Feature] 添加命令记录下载功能 * [Update] 文案修改,导出记录、提交,取消全部命令导出 * [Update] 命令导出,修复时间问题 * [Update] paramiko => 2.4.1 * [Update] 修改settings * [Update] 修改权限判断 * Dev (#1646) * [Update] 添加org * [Update] 修改url * [Update] 完成基本框架 * [Update] 修改一些逻辑 * [Update] 修改用户view * [Update] 修改资产 * [Update] 修改asset api * [Update] 修改协议小问题 * [Update] stash it * [Update] 修改约束 * [Update] 修改外键为org_id * [Update] 删掉Premiddleware * [Update] 修改Node * [Update] 修改get_current_org 为 proxy对象 current_org * [Bugfix] 解决Node.root() 死循环,移动AdminRequired到permission中 (#1571) * [Update] 修改permission (#1574) * Tmp org (#1579) * [Update] 添加org api, 升级到django 2.0 * [Update] fix some bug * [Update] 修改一些bug * [Update] 添加授权规则org (#1580) * [Update] 修复创建授权规则,显示org_name不是有效UUID的bug * [Update] 更新org之间隔离授权规则,解决QuerySet与Manager问题;修复创建用户,显示org_name不是有效UUID之bug; * Tmp org (#1583) * [Update] 修改一些内容 * [Update] 修改datatable 支持process * [Bugfix] 修复asset queryset 没有valid方法的bug * [Update] 在线/历史/命令model添加org;修复命令记录保存org失败bug (#1584) * [Update] 修复创建授权规则,显示org_name不是有效UUID的bug * [Update] 更新org之间隔离授权规则,解决QuerySet与Manager问题;修复创建用户,显示org_name不是有效UUID之bug; * [Update] 在线/历史/命令model添加org * [Bugfix] 修复命令记录,保存org不成功bug * [Update] Org功能修改 * [Bugfix] 修复merge带来的问题 * [Update] org admin显示资产详情右侧选项卡;修复资产授权添加用户,会显示其他org用户的bug (#1594) * [Bugfix] 修复资产授权添加用户,显示其他org的用户bug * [Update] org admin 显示资产详情右侧选项卡 * Tmp org (#1596) * [Update] 修改index view * [Update] 修改nav * [Update] 修改profile * [Bugfix] 修复org下普通用户打开web终端看不到已被授权的资产和节点bug * [Update] 修改get_all_assets * [Bugfix] 修复节点前面有个空目录 * [Bugfix] 修复merge引起的bug * [Update] Add init * [Update] Node get_all_assets 过滤游离资产,条件nodes_key=None -> nodes=None * [Update] 恢复原来的api地址 * [Update] 修改api * [Bugfix] 修复org下用户查看我的资产不显示已授权节点/资产的bug * [Bugfix] Fix perm name unique * [Bugfix] 修复校验失败api * [Update] Merge with org * [Merge] 修改一下bug * [Update] 暂时修改一些url * [Update] 修改url 为django 2.0 path * [Update] 优化datatable 和显示组织优化 * [Update] 升级url * [Bugfix] 修复coco启动失败(load_config_from_server)、硬件刷新,测试连接,str 没有 decode(… (#1613) * [Bugfix] 修复coco启动失败(load_config_from_server)、硬件刷新,测试连接,str 没有 decode() method的bug * [Bugfix] (task任务系统)修复资产连接性测试、硬件刷新和系统用户连接性测试失败等bug * [Bugfix] 修复一些bug * [Bugfix] 修复一些bug * [Update] 更新org下普通用户的资产详情 (#1619) * [Update] 更新org下普通用户查看资产详情,只显示数据 * [Update] 优化org下普通用户查看资产详情前端代码 * [Update] 创建/更新用户的role选项;密码强度提示信息中英文; (#1623) * [Update] 修改 超级管理员/组织管理员 在 创建/更新 用户时role的选项 问题 * [Update] 用户密码强度提示信息支持中英文 * [Update] 修改token返回 * [Update] Asset返回org name * [Update] 修改支持xpack * [Update] 修改url * [Bugfix] 修复不登录就能查看资产的bug * [Update] 用户修改 * [Bugfix] ... * [Bugfix] 修复跳转错误的问题 * [Update] xpack/orgs组织添加删除功能-js; 修复Label继承Org后bug; (#1644) * [Update] 更新xpack下orgs的翻译信息 * [Update] 更新model Label,继承OrgModelMixin; * [Update] xpack/orgs组织添加删除功能-js; 修复Label继承Org后bug; * [Bugfix] 修复小bug * [Update] 优化一些api * [Update] 优化用户资产页面 * [Update] 更新 xpack/orgs 删除功能:限制在当前org下删除当前org (#1645) * [Update] 修改版本号 * [Update] 添加功能: 语言切换(中/英);修改 header_bar <商业支持、文档>显示方式 * [Update] 中/英切换文案修改;修改django_language key 从 settings 中获取 * [Update] 修改Dashboard页面文案,支持英文 * [Update] 更新中/英文翻译(ALL) * [Update] 解决翻译文件冲突 * [Update] 系统用户支持单独隋松 * [Update] 重置用户MFA * [Update] 设置session空闲时间 * [Update] 加密setting配置 * [Update] 修改单独推送和测试资产可连接性 * [Update] 添加功能:用户个人详情页添加 更改MFA操作 (#1748) * [Update] 添加功能:用户个人详情页添加 更改MFA操作 * [Update] 删除print * [Bugfix] 添加部分views的权限控制;从组织移除用户,同时从授权规则和用户组中移除此用户。 (#1746) * [Bugfix] 修复上传command log 为空 * [Update] 修复执行任务的bug * [Bugfix] 修复将用户从组内移除,其依然具有之前的组权限的bug, perms and user_groups * [Bugfix] 修复组管理员可以访问部分url-views的bug(如: /settings/)添加views权限控制 * [Update] 修改日志滚动 * [Bugfix] 修复组织权限控制的bug (#1763) * [Bugfix] 修复将用户从组内移除,其依然具有之前的组权限的bug, perms and user_groups * [Bugfix] 修复组管理员可以访问部分url-views的bug(如: /settings/)添加views权限控制
2018-09-03 03:24:25 +00:00
set_to_root_org()
2017-12-21 18:08:29 +00:00
if record:
return self._run_and_record()
else:
return self._run_only()
def _run_and_record(self):
2018-04-01 15:45:37 +00:00
try:
hid = current_task.request.id
except AttributeError:
hid = str(uuid.uuid4())
history = AdHocRunHistory(id=hid, adhoc=self, task=self.task)
2017-12-21 18:08:29 +00:00
time_start = time.time()
try:
2018-04-02 05:19:31 +00:00
date_start = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
history.date_start = date_start
2019-01-21 09:43:08 +00:00
print(_("{} Start task: {}").format(date_start, self.task.name))
2018-04-01 15:45:37 +00:00
raw, summary = self._run_only()
2018-04-02 05:19:31 +00:00
date_end = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
2019-01-21 09:43:08 +00:00
print(_("{} Task finish").format(date_end))
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:
logger.error(e, exc_info=True)
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):
2018-03-30 14:03:43 +00:00
runner = AdHocRunner(self.inventory, options=self.options)
2017-12-21 18:08:29 +00:00
try:
2018-03-30 14:03:43 +00:00
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.warn("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:
"""
# self._become = signer.sign(json.dumps(item)).decode('utf-8')
self._become = signer.sign(json.dumps(item))
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]
2018-03-30 14:03:43 +00:00
@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')
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'