Fix playbook execution for VNF
[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 * Copyright (C) 2019 Orange
11 * ================================================================================
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 *      http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 *
24 * ============LICENSE_END=========================================================
25 */
26 '''
27
28 import os, subprocess
29 import sys
30 from collections import namedtuple
31 import json
32
33 import uuid
34 import cherrypy
35 from cherrypy.lib.httputil import parse_query_string
36 from cherrypy.lib import auth_basic
37
38 def ansibleSysCall (inventory_path, playbook_path, nodelist, mandatory, envparameters, localparameters, timeout, playbookdir):
39     cherrypy.log( "***> in AnsibleModule.ansibleSysCall")
40     log = []
41
42     str_parameters = ''
43
44     if 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 = '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 = '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, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
65     #PAP
66     #p.wait()
67     stdout_value, err = p.communicate()
68
69     stdout_value_cleanup = ''
70     for line in stdout_value:
71         stdout_value_cleanup += line.replace('  ', ' ')
72     stdout_value = stdout_value_cleanup.splitlines()
73
74     ParseFlag = False
75     retval = {}
76     returncode = p.returncode
77
78     if returncode == 137:
79         cherrypy.log("   ansible-playbook system call timed out")
80         # ansible-playbook system call timed out
81         for line in stdout_value: # p.stdout.readlines():
82             log.append (line)
83     else:
84         for line in stdout_value: # p.stdout.readlines():
85             print line # line,
86             if ParseFlag and len(line.strip())>0:
87                 ip_address = line.split(':')[0].strip()
88                 ok_flag = line.split(':')[1].strip().split('=')[1].split('changed')[0].strip()
89                 changed_flag = line.split(':')[1].strip().split('=')[2].split('unreachable')[0].strip()
90                 unreachable_flag = line.split(':')[1].strip().split('=')[3].split('failed')[0].strip()
91                 failed_flag = line.split(':')[1].strip().split('=')[4].split('skipped')[0].strip()
92                 retval[ip_address]=[ok_flag, changed_flag, unreachable_flag, failed_flag]
93             if "PLAY RECAP" in line:
94                 ParseFlag = True
95             log.append (line)
96             if "Killed" in line: # check for timeout
97                 cherrypy.log(" Playbook Killed(timeout)")
98                 returncode = 137
99
100     # retval['p'] = p.wait()
101
102     #cherrypy.log("*** <" + playbookdir + "> [" + str(log) + "] ***")
103     cherrypy.log("PlayBook Complete: " + playbookdir )
104     f = open(playbookdir + "/output.log", "w")
105     f.write(str(log))
106     f.close()
107
108     return retval, log, returncode
109
110 if __name__ == '__main__':
111
112     from multiprocessing import Process, Value, Array, Manager
113     import time
114
115     nodelist = 'host'
116
117     playbook_file = 'ansible_sleep@0.00.yml'
118
119
120     d = Manager().dict()
121
122     p = Process(nodelist=ansible_call, args=('ansible_module_config', playbook_file, nodelist,d, ))
123     p.start()
124
125     print "Process running"
126     print d
127     p.join()
128     print d