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