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