Merge "adding files to the build cache to reduce bandwidth by reusing already downloa...
[genesis.git] / fuel / 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 import subprocess
11 import sys
12 import os
13 import logging
14 import argparse
15 import shutil
16 import stat
17 import errno
18
19 N = {'id': 0, 'status': 1, 'name': 2, 'cluster': 3, 'ip': 4, 'mac': 5,
20      'roles': 6, 'pending_roles': 7, 'online': 8}
21 E = {'id': 0, 'status': 1, 'name': 2, 'mode': 3, 'release_id': 4,
22      'changes': 5, 'pending_release_id': 6}
23 R = {'id': 0, 'name': 1, 'state': 2, 'operating_system': 3, 'version': 4}
24 RO = {'name': 0, 'conflicts': 1}
25
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 out_handler = logging.FileHandler('autodeploy.log', mode='w')
33 out_handler.setFormatter(formatter)
34 LOG.addHandler(out_handler)
35 os.chmod('autodeploy.log', stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
36
37 def exec_cmd(cmd, check=True):
38     process = subprocess.Popen(cmd,
39                                stdout=subprocess.PIPE,
40                                stderr=subprocess.STDOUT,
41                                shell=True)
42     response = process.communicate()[0].strip()
43     return_code = process.returncode
44     if check:
45         if return_code > 0:
46             err(response)
47         else:
48             return response
49     return response, return_code
50
51
52 def run_proc(cmd):
53     process = subprocess.Popen(cmd,
54                                stdout=subprocess.PIPE,
55                                stderr=subprocess.STDOUT,
56                                shell=True)
57     return process
58
59
60 def parse(printout):
61     parsed_list = []
62     lines = printout.splitlines()
63     for l in lines[2:]:
64         parsed = [e.strip() for e in l.split('|')]
65         parsed_list.append(parsed)
66     return parsed_list
67
68
69 def clean(lines):
70     parsed_list = []
71     parsed = []
72     for l in lines.strip().splitlines():
73         parsed = []
74         cluttered = [e.strip() for e in l.split(' ')]
75         for p in cluttered:
76             if p:
77                 parsed.append(p)
78         parsed_list.append(parsed)
79     return parsed if len(parsed_list) == 1 else parsed_list
80
81
82 def err(message):
83     LOG.error('%s\n' % message)
84     sys.exit(1)
85
86
87 def warn(message):
88     LOG.warning('%s\n' % message)
89
90
91 def check_file_exists(file_path):
92     if not os.path.isfile(file_path):
93         err('ERROR: File %s not found\n' % file_path)
94
95
96 def check_dir_exists(dir_path):
97     if not os.path.isdir(dir_path):
98         err('ERROR: Directory %s not found\n' % dir_path)
99
100
101 def create_dir_if_not_exists(dir_path):
102     if not os.path.isdir(dir_path):
103         log('Creating directory %s' % dir_path)
104         os.makedirs(dir_path)
105
106
107 def delete(f):
108     if os.path.isfile(f):
109         log('Deleting file %s' % f)
110         os.remove(file)
111     elif os.path.isdir(f):
112         log('Deleting directory %s' % f)
113         shutil.rmtree(f)
114
115
116 def commafy(comma_separated_list):
117     l = [c.strip() for c in comma_separated_list.split(',')]
118     return ','.join(l)
119
120
121 def check_if_root():
122     r = exec_cmd('whoami')
123     if r != 'root':
124         err('You need be root to run this application')
125
126
127 def log(message):
128     LOG.debug('%s\n' % message)
129
130
131 class ArgParser(argparse.ArgumentParser):
132
133     def error(self, message):
134         sys.stderr.write('ERROR: %s\n' % message)
135         self.print_help()
136         sys.exit(2)
137
138
139 class literal_unicode(unicode):
140     pass
141
142
143 def literal_unicode_representer(dumper, data):
144     return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
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