Merge "Update ansible-server to support playbook of PNF"
[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,
37                     envparameters, localparameters, timeout, playbookdir):
38
39     cherrypy.log( "***> in AnsibleModule.ansibleSysCall")
40     log = []
41
42     str_parameters = ''
43
44     if not envparameters == '':
45         for key in envparameters:
46             if str_parameters == '':
47                 str_parameters = '"'  + str(key) + '=\'' + str(envparameters[key])  + '\''
48             else:
49                 str_parameters += ' '  + str(key) + '=\'' + str(envparameters[key])  + '\''
50                 # str_parameters += ', '  + str(key) + '=\'' + str(envparameters[key])  + '\''
51         str_parameters += '"'
52
53     if len(str_parameters) > 0:
54         cmd = 'export HOME=/home/ansible; env; cd ' + playbookdir + ';' +'timeout -s KILL -t ' + str(timeout) + \
55               ' ansible-playbook -v --timeout ' + str(timeout) + ' --extra-vars ' + str_parameters + ' -i ' + \
56               inventory_path + ' ' + playbook_path + ' | tee log.file'
57     else:
58         cmd = 'export HOME=/home/ansible; env; cd ' + playbookdir + ';' +'timeout -s KILL -t ' + str(timeout) + \
59               ' ansible-playbook -v --timeout ' + str(timeout) + ' -i ' + inventory_path + ' ' + playbook_path +' | tee log.file'
60
61     cherrypy.log("CMD: " + cmd)
62
63     cherrypy.log("PlayBook Start: " + playbookdir )
64     p = subprocess.Popen(cmd, shell=True,
65                          stdout=subprocess.PIPE,
66                          stderr=subprocess.STDOUT)
67     #PAP
68     #p.wait()
69     (stdout_value, err) = p.communicate()
70
71     stdout_value_cleanup = ''
72     for line in stdout_value:
73         stdout_value_cleanup += line.replace('  ', ' ')
74     stdout_value = stdout_value_cleanup.splitlines()
75
76     ParseFlag = False
77     retval = {}
78     returncode = p.returncode
79
80     if returncode == 137:
81
82         cherrypy.log("   ansible-playbook system call timed out")
83         # ansible-playbook system call timed out
84         for line in stdout_value: # p.stdout.readlines():
85             log.append (line)
86
87
88     else:
89
90         for line in stdout_value: # p.stdout.readlines():
91             print line # line,
92             if ParseFlag and len(line.strip())>0:
93                 ip_address = line.split(':')[0].strip()
94                 ok_flag = line.split(':')[1].strip().split('=')[1].split('changed')[0].strip()
95                 changed_flag = line.split(':')[1].strip().split('=')[2].split('unreachable')[0].strip()
96                 unreachable_flag = line.split(':')[1].strip().split('=')[3].split('failed')[0].strip()
97                 failed_flag = line.split(':')[1].strip().split('=')[4].strip()
98                 retval[ip_address]=[ok_flag, changed_flag, unreachable_flag, failed_flag]
99             if "PLAY RECAP" in line:
100                 ParseFlag = True
101             log.append (line)
102             if "Killed" in line: # check for timeout
103                 cherrypy.log(" Playbook Killed(timeout)")
104                 returncode = 137
105
106     # retval['p'] = p.wait()
107
108     #cherrypy.log("*** <" + playbookdir + "> [" + str(log) + "] ***")
109     cherrypy.log("PlayBook Complete: " + playbookdir )
110     f = open(playbookdir + "/output.log", "w")
111     f.write(str(log))
112     f.close()
113
114     return retval, log, returncode
115
116 if __name__ == '__main__':
117
118     from multiprocessing import Process, Value, Array, Manager
119     import time
120
121     nodelist = 'host'
122
123     playbook_file = 'ansible_sleep@0.00.yml'
124
125
126     d = Manager().dict()
127
128     p = Process(nodelist=ansible_call, args=('ansible_module_config', playbook_file, nodelist,d, ))
129     p.start()
130
131     print "Process running"
132     print d
133     p.join()
134     print d