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