Add command line argument masking for exec_cmd
[fuel.git] / deploy / common.py
1 ###############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # szilard.cserey@ericsson.com
4 # peter.barabas@ericsson.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ###############################################################################
10
11
12 import subprocess
13 import sys
14 import os
15 import logging
16 import argparse
17 import shutil
18 import stat
19 import errno
20 import time
21
22 N = {'id': 0, 'status': 1, 'name': 2, 'cluster': 3, 'ip': 4, 'mac': 5,
23      'roles': 6, 'pending_roles': 7, 'online': 8, 'group_id': 9}
24 E = {'id': 0, 'status': 1, 'name': 2, 'release_id': 3, 'pending_release_id': 4}
25 R = {'id': 0, 'name': 1, 'state': 2, 'operating_system': 3, 'version': 4}
26 RO = {'name': 0, 'conflicts': 1}
27 CWD = os.getcwd()
28 LOG = logging.getLogger(__name__)
29 LOG.setLevel(logging.DEBUG)
30 formatter = logging.Formatter('%(message)s')
31 out_handler = logging.StreamHandler(sys.stdout)
32 out_handler.setFormatter(formatter)
33 LOG.addHandler(out_handler)
34 LOGFILE = 'autodeploy.log'
35 if os.path.isfile(LOGFILE):
36     os.remove(LOGFILE)
37 out_handler = logging.FileHandler(LOGFILE, mode='w')
38 out_handler.setFormatter(formatter)
39 LOG.addHandler(out_handler)
40 os.chmod(LOGFILE, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
41
42
43 def mask_arguments(cmd, mask_args, mask_str):
44     cmd_line = cmd.split()
45     for pos in mask_args:
46         # Don't mask the actual command; also check if we don't reference
47         # beyond bounds
48         if pos == 0 or pos >= len(cmd_line):
49             continue
50         cmd_line[pos] = mask_str
51     return ' '.join(cmd_line)
52
53
54 def exec_cmd(cmd, check=True, attempts=1, delay=5, verbose=False, mask_args=[], mask_str='*****'):
55     masked_cmd = mask_arguments(cmd, mask_args, mask_str)
56
57     # a negative value means forever
58     while attempts != 0:
59         attempts = attempts - 1
60         process = subprocess.Popen(cmd,
61                                    stdout=subprocess.PIPE,
62                                    stderr=subprocess.PIPE,
63                                    shell=True)
64         (response, stderr) = process.communicate()
65         return_code = process.returncode
66         if return_code == 0 or attempts == 0:
67             break
68         time.sleep(delay)
69         if verbose:
70             log('%d attempts left: %s' % (attempts, masked_cmd))
71
72     response = response.strip()
73     if check:
74         if return_code > 0:
75             stderr = stderr.strip()
76             print "Failed command: " + str(masked_cmd)
77             print "Command returned response: " + str(stderr)
78             print "Command return code: " + str(return_code)
79             raise Exception(stderr)
80         else:
81             print "Command: " + str(masked_cmd)
82             print str(response)
83             return response
84     return response, return_code
85
86
87 def run_proc(cmd):
88     process = subprocess.Popen(cmd,
89                                stdout=subprocess.PIPE,
90                                stderr=subprocess.STDOUT,
91                                shell=True)
92     return process
93
94
95 def run_proc_wait_terminated(process):
96     response = process.communicate()[0].strip()
97     return_code = process.returncode
98     return response, return_code
99
100
101 def run_proc_kill(process):
102     response = process.kill()
103     return response
104
105
106 def parse(printout):
107     parsed_list = []
108     lines = printout.splitlines()
109     for l in lines[2:]:
110         parsed = [e.strip() for e in l.split('|')]
111         parsed_list.append(parsed)
112     return parsed_list
113
114
115 def clean(lines):
116     parsed_list = []
117     parsed = []
118     for l in lines.strip().splitlines():
119         parsed = []
120         cluttered = [e.strip() for e in l.split(' ')]
121         for p in cluttered:
122             if p:
123                 parsed.append(p)
124         parsed_list.append(parsed)
125     return parsed if len(parsed_list) == 1 else parsed_list
126
127
128 def err(message, fun = None, *args):
129     LOG.error('%s\n' % message)
130     if fun:
131         fun(*args)
132     sys.exit(1)
133
134
135 def warn(message):
136     LOG.warning('%s\n' % message)
137
138
139 def check_file_exists(file_path):
140     if not os.path.dirname(file_path):
141         file_path = '%s/%s' % (CWD, file_path)
142     if not os.path.isfile(file_path):
143         err('ERROR: File %s not found\n' % file_path)
144
145
146 def check_dir_exists(dir_path):
147     if not os.path.dirname(dir_path):
148         dir_path = '%s/%s' % (CWD, dir_path)
149     if not os.path.isdir(dir_path):
150         err('ERROR: Directory %s not found\n' % dir_path)
151
152
153 def create_dir_if_not_exists(dir_path):
154     if not os.path.isdir(dir_path):
155         log('Creating directory %s' % dir_path)
156         os.makedirs(dir_path)
157
158
159 def delete(f):
160     if os.path.isfile(f):
161         log('Deleting file %s' % f)
162         os.remove(f)
163     elif os.path.isdir(f):
164         log('Deleting directory %s' % f)
165         shutil.rmtree(f)
166
167
168 def commafy(comma_separated_list):
169     l = [c.strip() for c in comma_separated_list.split(',')]
170     return ','.join(l)
171
172
173 def check_if_root():
174     uid = os.getuid()
175     if uid != 0:
176         err('You need be root to run this application')
177
178
179 def log(message):
180     LOG.debug('%s\n' % message)
181
182
183 class ArgParser(argparse.ArgumentParser):
184
185     def error(self, message):
186         sys.stderr.write('ERROR: %s\n' % message)
187         self.print_help()
188         sys.exit(2)
189
190
191 def backup(path):
192     src = path
193     dst = path + '_orig'
194     delete(dst)
195     try:
196         shutil.copytree(src, dst)
197     except OSError as e:
198         if e.errno == errno.ENOTDIR:
199             shutil.copy(src, dst)
200         else:
201             raise