Commit 51c530c1 authored by Administrator's avatar Administrator

[future] ansible运行结果存入数据库

parent 96bc1cd8
...@@ -210,6 +210,10 @@ LOGGING = { ...@@ -210,6 +210,10 @@ LOGGING = {
'jumpserver.users.view': { 'jumpserver.users.view': {
'handlers': ['console', 'file'], 'handlers': ['console', 'file'],
'level': LOG_LEVEL, 'level': LOG_LEVEL,
},
'jumpserver.ops.ansible_api': {
'handlers': ['console', 'file'],
'level': LOG_LEVEL,
} }
} }
} }
......
...@@ -229,10 +229,20 @@ class CallbackModule(CallbackBase): ...@@ -229,10 +229,20 @@ class CallbackModule(CallbackBase):
def __play_uuid(self): def __play_uuid(self):
return self.results[-1]['uuid'] return self.results[-1]['uuid']
def save_task_result(self, result): def save_task_result(self, result, status):
try: try:
task = AnsibleTask.objects.get(uuid=self.__task_uuid) task = AnsibleTask.objects.get(uuid=self.__task_uuid)
host_result = AnsibleHostResult(task=task, name=result._host) host_result = AnsibleHostResult(task=task, name=result._host)
if status == "failed":
host_result.failed = json.dumps(result._result)
elif status == "unreachable":
host_result.unreachable = json.dumps(result._result)
elif status == "skipped":
host_result.skipped = json.dumps(result._result)
elif status == "success":
host_result.success = json.dumps(result._result)
else:
logger.error("No such status(failed|unreachable|skipped|success), please check!")
host_result.save() host_result.save()
except Exception as e: except Exception as e:
logger.error("Save Ansible host result to database error!, %s" % e.message) logger.error("Save Ansible host result to database error!, %s" % e.message)
...@@ -247,17 +257,17 @@ class CallbackModule(CallbackBase): ...@@ -247,17 +257,17 @@ class CallbackModule(CallbackBase):
logger.error("Save Ansible host result to database error!, %s" % e.message) logger.error("Save Ansible host result to database error!, %s" % e.message)
def v2_runner_on_failed(self, result, ignore_errors=False): def v2_runner_on_failed(self, result, ignore_errors=False):
self.save_task_result(result) self.save_task_result(result, "failed")
host = result._host host = result._host
self.results[-1]['tasks'][-1]['failed'][host.name] = result._result self.results[-1]['tasks'][-1]['failed'][host.name] = result._result
def v2_runner_on_unreachable(self, result): def v2_runner_on_unreachable(self, result):
self.save_task_result(result) self.save_task_result(result, "unreachable")
host = result._host host = result._host
self.results[-1]['tasks'][-1]['unreachable'][host.name] = result._result self.results[-1]['tasks'][-1]['unreachable'][host.name] = result._result
def v2_runner_on_skipped(self, result): def v2_runner_on_skipped(self, result):
self.save_task_result(result) self.save_task_result(result, "skipped")
host = result._host host = result._host
self.results[-1]['tasks'][-1]['skipped'][host.name] = result._result self.results[-1]['tasks'][-1]['skipped'][host.name] = result._result
...@@ -266,7 +276,7 @@ class CallbackModule(CallbackBase): ...@@ -266,7 +276,7 @@ class CallbackModule(CallbackBase):
self.results[-1]['tasks'][-1]['no_hosts']['msg'] = "no host to run this task" self.results[-1]['tasks'][-1]['no_hosts']['msg'] = "no host to run this task"
def v2_runner_on_ok(self, result): def v2_runner_on_ok(self, result):
self.save_task_result(result) self.save_task_result(result, "success")
host = result._host host = result._host
self.results[-1]['tasks'][-1]['success'][host.name] = result._result self.results[-1]['tasks'][-1]['success'][host.name] = result._result
...@@ -421,11 +431,10 @@ class ADHocRunner(InventoryMixin): ...@@ -421,11 +431,10 @@ class ADHocRunner(InventoryMixin):
play.status_code = ext_code play.status_code = ext_code
play.save() play.save()
except Exception as e: except Exception as e:
print e.message
logger.error("Update Ansible Play Status into database error!, %s" % e.message) logger.error("Update Ansible Play Status into database error!, %s" % e.message)
def run(self): def run(self):
"""执行ADHoc, 执行完后, 修改AnsiblePlay的状态 """执行ADHoc, 执行完后, 修改AnsiblePlay的状态为完成状态.
""" """
tqm = None tqm = None
# TODO:日志和结果分析 # TODO:日志和结果分析
...@@ -439,11 +448,12 @@ class ADHocRunner(InventoryMixin): ...@@ -439,11 +448,12 @@ class ADHocRunner(InventoryMixin):
passwords=self.passwords passwords=self.passwords
) )
ext_code = tqm.run(self.play) ext_code = tqm.run(self.play)
result = json.dumps(self.results_callback.results) result = self.results_callback.results
self.update_db_play(result, ext_code) self.update_db_play(result, ext_code)
return ext_code, result ret = json.dumps(result)
return ext_code, ret
finally: finally:
if tqm: if tqm:
...@@ -478,7 +488,7 @@ def test_run(): ...@@ -478,7 +488,7 @@ def test_run():
"gather_facts": "no", "gather_facts": "no",
"tasks": [ "tasks": [
dict(action=dict(module='setup')), dict(action=dict(module='setup')),
dict(action=dict(module='command', args='ls')) dict(action=dict(module='command', args='lsss'))
] ]
} }
hoc = ADHocRunner(conf, play_source, *assets) hoc = ADHocRunner(conf, play_source, *assets)
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
from __future__ import unicode_literals, absolute_import from __future__ import unicode_literals, absolute_import
import logging import logging
import json
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
...@@ -48,28 +49,25 @@ class AnsibleHostResult(models.Model): ...@@ -48,28 +49,25 @@ class AnsibleHostResult(models.Model):
def __unicode__(self): def __unicode__(self):
return "AnsibleHostResult: %s<%s>" % (self.name, str(self.status)) return "AnsibleHostResult: %s<%s>" % (self.name, str(self.status))
@property
def is_failed(self): def is_failed(self):
pass if self.failed or self.unreachable or self.no_host:
return True
def result(self): return False
pass
@property
def success_data(self):
class AnsibleSetup(models.Model): if self.success:
task = models.ForeignKey(AnsibleTask, related_name='host_results', blank=True) return json.loads(self.success)
name = models.CharField(max_length=128, blank=True, verbose_name=_('Name')) elif self.skipped:
status = models.BooleanField(blank=True, default=False, verbose_name=_('Status')) return json.loads(self.skipped)
success = models.TextField(blank=True, verbose_name=_('Success'))
skipped = models.TextField(blank=True, verbose_name=_('Skipped')) @property
failed = models.TextField(blank=True, verbose_name=_('Failed')) def failed_data(self):
unreachable = models.TextField(blank=True, verbose_name=_('Unreachable')) if self.failed:
no_host = models.TextField(blank=True, verbose_name=_('NoHost')) return json.loads(self.failed)
elif self.unreachable:
def __unicode__(self): return json.loads(self.unreachable)
return "AnsibleHostResult: %s<%s>" % (self.name, str(self.status)) elif self.no_host:
return {"msg": self.no_host}
def is_failed(self):
pass
def result(self):
pass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment