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