Merge "Reaping improvements for Fuel 7"
[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}
22 E = {'id': 0, 'status': 1, 'name': 2, 'mode': 3, 'release_id': 4,
23      'changes': 5, 'pending_release_id': 6}
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):
42     nul_f = open(os.devnull, 'w')
43     process = subprocess.Popen(cmd,
44                                stdout=subprocess.PIPE,
45                                stderr=nul_f,
46                                shell=True)
47     nul_f.close()
48     response = process.communicate()[0].strip()
49     return_code = process.returncode
50     if check:
51         if return_code > 0:
52             raise Exception(response)
53         else:
54             return response
55     return response, return_code
56
57
58 def run_proc(cmd):
59     process = subprocess.Popen(cmd,
60                                stdout=subprocess.PIPE,
61                                stderr=subprocess.STDOUT,
62                                shell=True)
63     return process
64
65
66 def parse(printout):
67     parsed_list = []
68     lines = printout.splitlines()
69     for l in lines[2:]:
70         parsed = [e.strip() for e in l.split('|')]
71         parsed_list.append(parsed)
72     return parsed_list
73
74
75 def clean(lines):
76     parsed_list = []
77     parsed = []
78     for l in lines.strip().splitlines():
79         parsed = []
80         cluttered = [e.strip() for e in l.split(' ')]
81         for p in cluttered:
82             if p:
83                 parsed.append(p)
84         parsed_list.append(parsed)
85     return parsed if len(parsed_list) == 1 else parsed_list
86
87
88 def err(message):
89     LOG.error('%s\n' % message)
90     sys.exit(1)
91
92
93 def warn(message):
94     LOG.warning('%s\n' % message)
95
96
97 def check_file_exists(file_path):
98     if not os.path.dirname(file_path):
99         file_path = '%s/%s' % (CWD, file_path)
100     if not os.path.isfile(file_path):
101         err('ERROR: File %s not found\n' % file_path)
102
103
104 def check_dir_exists(dir_path):
105     if not os.path.dirname(dir_path):
106         dir_path = '%s/%s' % (CWD, dir_path)
107     if not os.path.isdir(dir_path):
108         err('ERROR: Directory %s not found\n' % dir_path)
109
110
111 def create_dir_if_not_exists(dir_path):
112     if not os.path.isdir(dir_path):
113         log('Creating directory %s' % dir_path)
114         os.makedirs(dir_path)
115
116
117 def delete(f):
118     if os.path.isfile(f):
119         log('Deleting file %s' % f)
120         os.remove(f)
121     elif os.path.isdir(f):
122         log('Deleting directory %s' % f)
123         shutil.rmtree(f)
124
125
126 def commafy(comma_separated_list):
127     l = [c.strip() for c in comma_separated_list.split(',')]
128     return ','.join(l)
129
130
131 def check_if_root():
132     r = exec_cmd('whoami')
133     if r != 'root':
134         err('You need be root to run this application')
135
136
137 def log(message):
138     LOG.debug('%s\n' % message)
139
140
141 class ArgParser(argparse.ArgumentParser):
142
143     def error(self, message):
144         sys.stderr.write('ERROR: %s\n' % message)
145         self.print_help()
146         sys.exit(2)
147
148
149 def backup(path):
150     src = path
151     dst = path + '_orig'
152     delete(dst)
153     try:
154         shutil.copytree(src, dst)
155     except OSError as e:
156         if e.errno == errno.ENOTDIR:
157             shutil.copy(src, dst)
158         else:
159             raise