fix odl patches
[ccsdk/distribution.git] / ansible-server / src / main / ansible-server / AnsibleModule.py
1 '''
2 /*-
3 * ============LICENSE_START=======================================================
4 * ONAP : APPC
5 * ================================================================================
6 * Copyright (C) 2019 AT&T Intellectual Property.  All rights reserved.
7 * ================================================================================
8 * Copyright (C) 2019 Amdocs
9 * =============================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 *      http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 *
22 * ============LICENSE_END=========================================================
23 */
24 '''
25
26 import os, subprocess
27 import sys
28 from collections import namedtuple
29 import json
30
31 import uuid
32 import cherrypy
33 from cherrypy.lib.httputil import parse_query_string
34 from cherrypy.lib import auth_basic
35
36 def ansibleSysCall (inventory_path, playbook_path, nodelist, mandatory, envparameters, localparameters, timeout, playbookdir):
37     cherrypy.log( "***> in AnsibleModule.ansibleSysCall")
38     log = []
39
40     str_parameters = ''
41
42     if envparameters:
43         for key in envparameters:
44             if str_parameters == '':
45                 str_parameters = '"'  + str(key) + '=\'' + str(envparameters[key])  + '\''
46             else:
47                 str_parameters += ' '  + str(key) + '=\'' + str(envparameters[key])  + '\''
48                 # str_parameters += ', '  + str(key) + '=\'' + str(envparameters[key])  + '\''
49         str_parameters += '"'
50
51     if len(str_parameters) > 0:
52         cmd = 'cd ' + playbookdir + ';' + 'timeout -s KILL -t ' + str(timeout) + \
53               ' ansible-playbook -v --timeout ' + str(timeout) + ' --extra-vars ' + str_parameters + ' -i ' + \
54               inventory_path + ' ' + playbook_path + ' | tee log.file'
55     else:
56         cmd = 'cd ' + playbookdir + ';' + 'timeout -s KILL -t ' + str(timeout) + \
57               ' ansible-playbook -v --timeout ' + str(timeout) + ' -i ' + inventory_path + ' ' + playbook_path + ' | tee log.file'
58
59     cherrypy.log("CMD: " + cmd)
60
61     cherrypy.log("PlayBook Start: " + playbookdir )
62     p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
63     #PAP
64     #p.wait()
65     stdout_value, err = p.communicate()
66     stdout_value = stdout_value.splitlines()
67
68     stdout_value_cleanup = []
69     for line in stdout_value:
70         stdout_value_cleanup.append(line.replace('  ', ' '))
71     stdout_value = stdout_value_cleanup
72
73     ParseFlag = False
74     retval = {}
75     returncode = p.returncode
76
77     if returncode == 137:
78         cherrypy.log("   ansible-playbook system call timed out")
79         # ansible-playbook system call timed out
80         for line in stdout_value: # p.stdout.readlines():
81             log.append (line)
82     else:
83         for line in stdout_value: # p.stdout.readlines():
84             if line:
85                 cherrypy.log("OUTPUT: %s" % line)
86
87             if ParseFlag and len(line.strip())>0:
88                 ip_address = line.split(':')[0].strip()
89                 exec_results = line.split(':')[1].strip()
90
91                 result_items = [item for item in exec_results.split(' ') if item]
92                 cherrypy.log("Execcution results of '%s': %s" % (ip_address, str(result_items)))
93                 # ['ok=6', 'changed=5', 'unreachable=0', 'failed=0', 'skipped=3', 'rescued=0', 'ignored=0']
94
95                 ok_flag = result_items[0].split('=')[1].strip()
96                 changed_flag = result_items[1].split('=')[1].strip()
97                 unreachable_flag = result_items[2].split('=')[1].strip()
98                 failed_flag = result_items[3].split('=')[1].strip()
99
100                 retval[ip_address]=[ok_flag, changed_flag, unreachable_flag, failed_flag]
101             if "PLAY RECAP" in line:
102                 ParseFlag = True
103             log.append (line)
104             if "Killed" in line: # check for timeout
105                 cherrypy.log(" Playbook Killed(timeout)")
106                 returncode = 137
107
108     # retval['p'] = p.wait()
109
110     #cherrypy.log("*** <" + playbookdir + "> [" + str(log) + "] ***")
111     cherrypy.log("PlayBook Complete: " + playbookdir )
112     f = open(playbookdir + "/output.log", "w")
113     f.write(str(log))
114     f.close()
115
116     return retval, log, returncode
117
118 if __name__ == '__main__':
119
120     from multiprocessing import Process, Value, Array, Manager
121     import time
122
123     nodelist = 'host'
124
125     playbook_file = 'ansible_sleep@0.00.yml'
126
127
128     d = Manager().dict()
129
130     p = Process(nodelist=ansible_call, args=('ansible_module_config', playbook_file, nodelist,d, ))
131     p.start()
132
133     print("Process running")
134     print(d)
135     p.join()
136     print(d)