Merge "Refactor Foreman install guide reStructuredText"
[genesis.git] / fuel / deploy / common.py
1 import subprocess
2 import sys
3 import os
4 import logging
5
6 N = {'id': 0, 'status': 1, 'name': 2, 'cluster': 3, 'ip': 4, 'mac': 5,
7      'roles': 6, 'pending_roles': 7, 'online': 8}
8 E = {'id': 0, 'status': 1, 'name': 2, 'mode': 3, 'release_id': 4,
9      'changes': 5, 'pending_release_id': 6}
10 R = {'id': 0, 'name': 1, 'state': 2, 'operating_system': 3, 'version': 4}
11 RO = {'name': 0, 'conflicts': 1}
12
13 LOG = logging.getLogger(__name__)
14 LOG.setLevel(logging.DEBUG)
15 formatter = logging.Formatter('%(message)s')
16 out_handler = logging.StreamHandler(sys.stdout)
17 out_handler.setFormatter(formatter)
18 LOG.addHandler(out_handler)
19 out_handler = logging.FileHandler('autodeploy.log', mode='w')
20 out_handler.setFormatter(formatter)
21 LOG.addHandler(out_handler)
22
23 def exec_cmd(cmd, check=True):
24     process = subprocess.Popen(cmd,
25                                stdout=subprocess.PIPE,
26                                stderr=subprocess.STDOUT,
27                                shell=True)
28     response = process.communicate()[0].strip()
29     return_code = process.returncode
30     if check:
31         if return_code > 0:
32             err(response)
33         else:
34             return response
35     return response, return_code
36
37 def run_proc(cmd):
38     process = subprocess.Popen(cmd,
39                                stdout=subprocess.PIPE,
40                                stderr=subprocess.STDOUT,
41                                shell=True)
42     return process
43
44 def parse(printout):
45     parsed_list = []
46     lines = printout.splitlines()
47     for l in lines[2:]:
48          parsed = [e.strip() for e in l.split('|')]
49          parsed_list.append(parsed)
50     return parsed_list
51
52 def clean(lines):
53     parsed_list = []
54     parsed = []
55     for l in lines.strip().splitlines():
56         parsed = []
57         cluttered = [e.strip() for e in l.split(' ')]
58         for p in cluttered:
59             if p:
60                 parsed.append(p)
61         parsed_list.append(parsed)
62     return parsed if len(parsed_list) == 1 else parsed_list
63
64 def err(message):
65     LOG.error('%s\n' % message)
66     sys.exit(1)
67
68 def check_file_exists(file_path):
69     if not os.path.isfile(file_path):
70         err('ERROR: File %s not found\n' % file_path)
71
72 def check_dir_exists(dir_path):
73     if not os.path.isdir(dir_path):
74         err('ERROR: Directory %s not found\n' % dir_path)
75
76 def check_if_root():
77     r = exec_cmd('whoami')
78     if r != 'root':
79         err('You need be root to run this application')
80
81 def log(message):
82     LOG.debug('%s\n' % message)