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