Fix wrong offset in environment array
[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
20 N = {'id': 0, 'status': 1, 'name': 2, 'cluster': 3, 'ip': 4, 'mac': 5,
21      'roles': 6, 'pending_roles': 7, 'online': 8, 'group_id': 9}
22 E = {'id': 0, 'status': 1, 'name': 2, 'release_id': 3, 'pending_release_id': 4}
23 R = {'id': 0, 'name': 1, 'state': 2, 'operating_system': 3, 'version': 4}
24 RO = {'name': 0, 'conflicts': 1}
25 CWD = os.getcwd()
26 LOG = logging.getLogger(__name__)
27 LOG.setLevel(logging.DEBUG)
28 formatter = logging.Formatter('%(message)s')
29 out_handler = logging.StreamHandler(sys.stdout)
30 out_handler.setFormatter(formatter)
31 LOG.addHandler(out_handler)
32 LOGFILE = 'autodeploy.log'
33 if os.path.isfile(LOGFILE):
34     os.remove(LOGFILE)
35 out_handler = logging.FileHandler(LOGFILE, mode='w')
36 out_handler.setFormatter(formatter)
37 LOG.addHandler(out_handler)
38 os.chmod(LOGFILE, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
39
40 def exec_cmd(cmd, check=True):
41     nul_f = open(os.devnull, 'w')
42     process = subprocess.Popen(cmd,
43                                stdout=subprocess.PIPE,
44                                stderr=nul_f,
45                                shell=True)
46     nul_f.close()
47     response = process.communicate()[0].strip()
48     return_code = process.returncode
49     if check:
50         if return_code > 0:
51             print "Failed command: " + str(cmd)
52             print "Command returned response: " + str(response)
53             print "Command return code: " + str(return_code)
54             raise Exception(response)
55         else:
56             print "Command: " + str(cmd)
57             print str(response)
58             return response
59     return response, return_code
60
61
62 def run_proc(cmd):
63     process = subprocess.Popen(cmd,
64                                stdout=subprocess.PIPE,
65                                stderr=subprocess.STDOUT,
66                                shell=True)
67     return process
68
69
70 def parse(printout):
71     parsed_list = []
72     lines = printout.splitlines()
73     for l in lines[2:]:
74         parsed = [e.strip() for e in l.split('|')]
75         parsed_list.append(parsed)
76     return parsed_list
77
78
79 def clean(lines):
80     parsed_list = []
81     parsed = []
82     for l in lines.strip().splitlines():
83         parsed = []
84         cluttered = [e.strip() for e in l.split(' ')]
85         for p in cluttered:
86             if p:
87                 parsed.append(p)
88         parsed_list.append(parsed)
89     return parsed if len(parsed_list) == 1 else parsed_list
90
91
92 def err(message):
93     LOG.error('%s\n' % message)
94     sys.exit(1)
95
96
97 def warn(message):
98     LOG.warning('%s\n' % message)
99
100
101 def check_file_exists(file_path):
102     if not os.path.dirname(file_path):
103         file_path = '%s/%s' % (CWD, file_path)
104     if not os.path.isfile(file_path):
105         err('ERROR: File %s not found\n' % file_path)
106
107
108 def check_dir_exists(dir_path):
109     if not os.path.dirname(dir_path):
110         dir_path = '%s/%s' % (CWD, dir_path)
111     if not os.path.isdir(dir_path):
112         err('ERROR: Directory %s not found\n' % dir_path)
113
114
115 def create_dir_if_not_exists(dir_path):
116     if not os.path.isdir(dir_path):
117         log('Creating directory %s' % dir_path)
118         os.makedirs(dir_path)
119
120
121 def delete(f):
122     if os.path.isfile(f):
123         log('Deleting file %s' % f)
124         os.remove(f)
125     elif os.path.isdir(f):
126         log('Deleting directory %s' % f)
127         shutil.rmtree(f)
128
129
130 def commafy(comma_separated_list):
131     l = [c.strip() for c in comma_separated_list.split(',')]
132     return ','.join(l)
133
134
135 def check_if_root():
136     r = exec_cmd('whoami')
137     if r != 'root':
138         err('You need be root to run this application')
139
140
141 def log(message):
142     LOG.debug('%s\n' % message)
143
144
145 class ArgParser(argparse.ArgumentParser):
146
147     def error(self, message):
148         sys.stderr.write('ERROR: %s\n' % message)
149         self.print_help()
150         sys.exit(2)
151
152
153 def backup(path):
154     src = path
155     dst = path + '_orig'
156     delete(dst)
157     try:
158         shutil.copytree(src, dst)
159     except OSError as e:
160         if e.errno == errno.ENOTDIR:
161             shutil.copy(src, dst)
162         else:
163             raise