71d0c0594b067450b7ed75e4580b7640dd880965
[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)
63     #PAP
64     #p.wait()
65     stdout_value, err = p.communicate()
66
67     stdout_value_cleanup = ''
68     for line in stdout_value:
69         stdout_value_cleanup += line.replace('  ', ' ')
70     stdout_value = stdout_value_cleanup.splitlines()
71
72     ParseFlag = False
73     retval = {}
74     returncode = p.returncode
75
76     if returncode == 137:
77         cherrypy.log("   ansible-playbook system call timed out")
78         # ansible-playbook system call timed out
79         for line in stdout_value: # p.stdout.readlines():
80             log.append (line)
81     else:
82         for line in stdout_value: # p.stdout.readlines():
83             print line # line,
84             if ParseFlag and len(line.strip())>0:
85                 ip_address = line.split(':')[0].strip()
86                 ok_flag = line.split(':')[1].strip().split('=')[1].split('changed')[0].strip()
87                 changed_flag = line.split(':')[1].strip().split('=')[2].split('unreachable')[0].strip()
88                 unreachable_flag = line.split(':')[1].strip().split('=')[3].split('failed')[0].strip()
89                 failed_flag = line.split(':')[1].strip().split('=')[4].strip()
90                 retval[ip_address]=[ok_flag, changed_flag, unreachable_flag, failed_flag]
91             if "PLAY RECAP" in line:
92                 ParseFlag = True
93             log.append (line)
94             if "Killed" in line: # check for timeout
95                 cherrypy.log(" Playbook Killed(timeout)")
96                 returncode = 137
97
98     # retval['p'] = p.wait()
99
100     #cherrypy.log("*** <" + playbookdir + "> [" + str(log) + "] ***")
101     cherrypy.log("PlayBook Complete: " + playbookdir )
102     f = open(playbookdir + "/output.log", "w")
103     f.write(str(log))
104     f.close()
105
106     return retval, log, returncode
107
108 if __name__ == '__main__':
109
110     from multiprocessing import Process, Value, Array, Manager
111     import time
112
113     nodelist = 'host'
114
115     playbook_file = 'ansible_sleep@0.00.yml'
116
117
118     d = Manager().dict()
119
120     p = Process(nodelist=ansible_call, args=('ansible_module_config', playbook_file, nodelist,d, ))
121     p.start()
122
123     print "Process running"
124     print d
125     p.join()
126     print d