diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 3464fa0..3e40ba5 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -10,7 +10,7 @@ - + @@ -51,52 +51,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -108,7 +63,6 @@ - MIDDLEWARE container1 password get_args @@ -138,6 +92,7 @@ form retsult_data id_vars + vars E:\chain @@ -153,7 +108,6 @@ - @@ -194,16 +148,17 @@ - - - - + + + + + @@ -220,7 +175,7 @@ true DEFINITION_ORDER - + @@ -242,62 +197,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -311,32 +213,36 @@ - + - - + + - + + + - - + + + + @@ -346,13 +252,6 @@ - - - - - - - @@ -360,6 +259,13 @@ + + + + + + + @@ -373,7 +279,7 @@ - + @@ -567,8 +473,7 @@ - - + @@ -577,8 +482,8 @@ - - + + @@ -625,384 +530,420 @@ - + - - - - - - - - + - - + + - + - - + + - + - - + + - - - - + + + + - + - - + + - + - + - - + + - + - - + + + + + - + - - + + + - + - - + + - + - - + + - + + - + - - + + + - + - - + + + - + - - + + + + + - + - - + + + - + - - + + + - + - - + + + + + - + - + + + + - + + + + - + - - + + + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + - + - - + + + - + - + + - - - - + + + + + - + - - + + + - + - + + - + - + + + + + + + + + + - + + - + - - + + - + - - - - - + + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - - - - + + + - + - - - - - + + + - + - - + + - + - - + + diff --git a/tasks/tasks.py b/tasks/tasks.py index a07a2da..365bec5 100644 --- a/tasks/tasks.py +++ b/tasks/tasks.py @@ -2,10 +2,12 @@ platforms.C_FORCE_ROOT = True from chain import settings + app = Celery('chain') -app.config_from_object('django.conf:settings',) +app.config_from_object('django.conf:settings', ) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) -import logging,json +import logging, json + logger = logging.getLogger('tasks') from multiprocessing import current_process @@ -20,17 +22,16 @@ def debug_task(self): print('Request: {0!r}'.format(self.request)) - @app.task() -def ansbile_tools(assets,tools,module): +def ansbile_tools(assets, tools, module): current_process()._config = {'semprefix': '/mp'} inventory = BaseInventory(host_list=assets) - hostname,retsult_data = [],[] + hostname, retsult_data = [], [] for i in inventory.hosts: hostname.append(i) - if module == "script": + if module == "script": runner = AdHocRunner(inventory) tasks = [ {"action": {"module": "{}".format(module), "args": "{}".format(tools)}, "name": "script"}, @@ -55,86 +56,81 @@ def ansbile_tools(assets,tools,module): ret_host = {} try: out = ret[element]['script']['stdout'] - if not out: + if not out: out = ret[element]['script']['stderr'] std.append("{0}".format(out)) except Exception as e: - logger.error(e) - try: - std.append("{0}".format(ret[element]['script']['msg'])) - except Exception as e: - logger.error("执行失败{0}".format(e)) + logger.error(e) + try: + std.append("{0}".format(ret[element]['script']['msg'])) + except Exception as e: + logger.error("执行失败{0}".format(e)) ret_host['hostname'] = element - ret_host['data'] = '\n'.join(std) + ret_host['data'] = ''.join(std) retsult_data.append(ret_host) - elif module == 'yml': - - runers = PlayBookRunner(playbook_path=tools, inventory=inventory) - retsult = runers.run() - - try: - ret = retsult['results_callback'] - except Exception as e: - logger.error("{}".format(e)) - - for i, element in enumerate(hostname): - std = [] - ret_host = {} - try: - out = ret[element]['stdout'] - if not out: - out= ret[element]['stderr'] - std.append("{0}".format(out)) - except Exception as e: - logger.error(e) - try: - std.append("{0}".format(ret[element]['msg'])) - except Exception as e: - logger.error("执行失败{0}".format(e)) - ret_host['hostname'] = element - ret_host['data'] = '\n'.join(std) - retsult_data.append(ret_host) - - return retsult_data + elif module == 'yml': -@app.task() -def ansbile_asset_hardware(id,assets): - current_process()._config = {'semprefix': '/mp'} - - inventory = BaseInventory(assets) - runner = AdHocRunner(inventory) - tasks = [ - {"action": {"module": "setup", "args": ""}, "name": "script"}, - ] - retsult = runner.run(tasks, "all") - hostname = assets[0]['hostname'] + runers = PlayBookRunner(playbook_path=tools, inventory=inventory) + retsult = runers.run() try: - data = retsult.results_raw['ok'][hostname]['script']['ansible_facts'] - nodename = data['ansible_nodename'] - disk = "{}".format(str(sum([int(data["ansible_devices"][i]["sectors"]) * \ - int(data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024 \ - for i in data["ansible_devices"] if - i[0:2] in ("vd", "ss", "sd")])) + str(" GB")) - mem = int(data['ansible_memtotal_mb'] / 1024) - cpu = int("{}".format( - data['ansible_processor_count'] * data["ansible_processor_cores"])) - - system = data['ansible_product_name']+" "+data['ansible_lsb']["description"] - - obj = asset.objects.filter(id=id).update(hostname=nodename, - disk=disk, - memory=mem, - cpu=cpu, - system=system) - + ret = retsult['results_callback'] except Exception as e: - logger.error(e) - + logger.error("{}".format(e)) + for i, element in enumerate(hostname): + std = [] + ret_host = {} + try: + out = ret[element]['stdout'] + if not out: + out = ret[element]['stderr'] + std.append("{0}".format(out)) + except Exception as e: + logger.error(e) + try: + std.append("{0}".format(ret[element]['msg'])) + except Exception as e: + logger.error("执行失败{0}".format(e)) + ret_host['hostname'] = element + ret_host['data'] = ''.join(std) + retsult_data.append(ret_host) + return retsult_data +@app.task() +def ansbile_asset_hardware(id, assets): + current_process()._config = {'semprefix': '/mp'} + inventory = BaseInventory(assets) + runner = AdHocRunner(inventory) + tasks = [ + {"action": {"module": "setup", "args": ""}, "name": "script"}, + ] + retsult = runner.run(tasks, "all") + hostname = assets[0]['hostname'] + + try: + data = retsult.results_raw['ok'][hostname]['script']['ansible_facts'] + nodename = data['ansible_nodename'] + disk = "{}".format(str(sum([int(data["ansible_devices"][i]["sectors"]) * \ + int(data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024 \ + for i in data["ansible_devices"] if + i[0:2] in ("vd", "ss", "sd")])) + str(" GB")) + mem = int(data['ansible_memtotal_mb'] / 1024) + cpu = int("{}".format( + data['ansible_processor_count'] * data["ansible_processor_cores"])) + + system = data['ansible_product_name'] + " " + data['ansible_lsb']["description"] + + obj = asset.objects.filter(id=id).update(hostname=nodename, + disk=disk, + memory=mem, + cpu=cpu, + system=system) + + except Exception as e: + logger.error(e) diff --git a/tasks/templatetags/__init__.py b/tasks/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tasks/templatetags/mytags.py b/tasks/templatetags/mytags.py new file mode 100644 index 0000000..63b1bf3 --- /dev/null +++ b/tasks/templatetags/mytags.py @@ -0,0 +1,17 @@ +from django import template +##自定义过滤器 +register = template.Library() +import json + +@register.filter +def result(text): + for i,j in enumerate(text): + a = j['data'] + out = " ".join(a.split()) + j['data']=out + + return json.dumps(text) + + + + diff --git a/tasks/tests.py b/tasks/tests.py index 9ed78d7..545dde7 100644 --- a/tasks/tests.py +++ b/tasks/tests.py @@ -1,26 +1,10 @@ +a = {'hostname': 'SDF1', 'data': 'Aegis-\nansible_19xkmz1l\nansible_5c31w637\nansible_w6p4y54e\nchain\n_config.yml\ndb.sqlite3\nLICENSE\nmanage.py\nREADME.md\nrequirements.txt\nshell.sh\nsystemd-private-92a8135b7e8c4a7290ed5adf81e91c2b-ntpd.service-8G1GuO'} -a ={'SDF': {'task0': {'cmd': 'pwd', 'stdout': '/home/hequan', 'stderr': '', 'rc': 0, 'start': '2018-04-12 15:32:41.836286', 'end': '2018-04-12 15:32:41.841759', 'delta': '0:00:00.005473', 'changed': True, 'invocation': {'module_args': {'_raw_params': 'pwd', '_uses_shell': True, 'warn': True, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': ['/home/hequan'], 'stderr_lines': [], '_ansible_no_log': False}, 'task1': {'cmd': 'hostname', 'stdout': 'k8s_master', 'stderr': '', 'rc': 0, 'start': '2018-04-12 15:32:42.679044', 'end': '2018-04-12 15:32:42.684143', 'delta': '0:00:00.005099', 'changed': True, 'invocation': {'module_args': {'_raw_params': 'hostname', '_uses_shell': True, 'warn': True, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': ['k8s_master'], 'stderr_lines': [], '_ansible_no_log': False}}, 'devops': {'task0': {'changed': True, 'end': '2018-04-12 15:32:41.905235', 'stdout': '/home/hequan', 'cmd': 'pwd', 'rc': 0, 'start': '2018-04-12 15:32:41.894985', 'stderr': '', 'delta': '0:00:00.010250', 'invocation': {'module_args': {'creates': None, 'executable': None, '_uses_shell': True, '_raw_params': 'pwd', 'removes': None, 'warn': True, 'chdir': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': ['/home/hequan'], 'stderr_lines': [], '_ansible_no_log': False}, 'task1': {'changed': True, 'end': '2018-04-12 15:32:42.775568', 'stdout': 'devops', 'cmd': 'hostname', 'rc': 0, 'start': '2018-04-12 15:32:42.765349', 'stderr': '', 'delta': '0:00:00.010219', 'invocation': {'module_args': {'creates': None, 'executable': None, '_uses_shell': True, '_raw_params': 'hostname', 'removes': None, 'warn': True, 'chdir': None, 'stdin': None}}, '_ansible_parsed': True, 'stdout_lines': ['devops'], 'stderr_lines': [], '_ansible_no_log': False}}} -import pprint -pp = pprint.PrettyPrinter(indent=4) -pp.pprint(a) -hostname = ['SDF','devops'] +b =a['data'] -ret1 = {} -c = [] - -for i in range(len(hostname)): - b= [] - ret1 = {} - n = hostname[i] - for t in range(2): - print(n,a[n]['task{}'.format(t)]['stdout']) - b.append(a[n]['task{}'.format(t)]['stdout']) - ret1['hostname']=n - ret1['data']='\n'.join(b) - # print(ret1) - c.append(ret1) - - -print(c) +b.replace('\n',"--") +print(b) +out = " ".join(b.split()) +print(out) \ No newline at end of file diff --git a/tasks/views.py b/tasks/views.py index 0733d73..0bc730d 100644 --- a/tasks/views.py +++ b/tasks/views.py @@ -145,6 +145,7 @@ def post(self, request): vars = {'hostname':i.hostname,'inner_ip':i.inner_ip,"network_ip":i.network_ip,"project":i.project } try : vars.update(variable.objects.get(assets__hostname=i).vars) + print(vars) except Exception as e: logger.error(e) diff --git a/templates/tasks/tools-results-detail.html b/templates/tasks/tools-results-detail.html index 8de082b..8bc303a 100644 --- a/templates/tasks/tools-results-detail.html +++ b/templates/tasks/tools-results-detail.html @@ -1,8 +1,9 @@ {% extends "base.html" %} {% block title %}资产详情{% endblock %} +{% load mytags %} +{% load bootstrap3 %} {% block header-css %} -{% load bootstrap3 %} {% endblock %} @@ -75,10 +76,6 @@ 任务结果 - - 结果: - {{ results.result }} - @@ -106,10 +103,19 @@ 任务结果 {{ task.ctime }} + + 结果: + + {{ results.result | result }} + + + + + @@ -142,7 +148,22 @@ 任务结果 - {% endblock %} +{% block footer-js %} + + + + + +{% endblock %} \ No newline at end of file