3c706fad62cb0a0eb7f177b556fccf509401160b
[bottlenecks.git] / utils / env_prepare / stack_prepare.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 import os
11 import subprocess
12 import errno
13 from utils.logger import Logger
14 from utils.parser import Parser as config
15 import utils.infra_setup.heat.manager as utils
16
17 LOG = Logger(__name__).getLogger()
18
19
20 def _prepare_env_daemon():
21
22     installer_ip = os.environ.get('INSTALLER_IP', 'undefined')
23     installer_type = os.environ.get('INSTALLER_TYPE', 'undefined')
24
25     rc_file = config.bottlenecks_config["rc_dir"]
26
27     _get_remote_rc_file(rc_file, installer_ip, installer_type)
28
29     _source_file(rc_file)
30
31     # _append_external_network(rc_file)
32
33     # update the external_network
34     # _source_file(rc_file)
35
36
37 def _get_remote_rc_file(rc_file, installer_ip, installer_type):
38
39     RELENG_DIR = config.bottlenecks_config["releng_dir"]
40     OS_FETCH_SCRIPT = config.bottlenecks_config["fetch_os"]
41     os_fetch_script = os.path.join(RELENG_DIR, OS_FETCH_SCRIPT)
42
43     try:
44         cmd = [os_fetch_script, '-d', rc_file, '-i', installer_type,
45                '-a', installer_ip]
46         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
47         p.communicate()[0]
48
49         if p.returncode != 0:
50             LOG.debug('Failed to fetch credentials from installer')
51     except OSError as e:
52         if e.errno != errno.EEXIST:
53             raise
54
55
56 def _source_file(rc_file):
57     p = subprocess.Popen(". %s; env" % rc_file, stdout=subprocess.PIPE,
58                          shell=True)
59     output = p.communicate()[0]
60     env = dict((line.split('=', 1) for line in output.splitlines()))
61     os.environ.update(env)
62     return env
63
64
65 def _append_external_network(rc_file):
66     neutron_client = utils._get_neutron_client()
67     networks = neutron_client.list_networks()['networks']
68     try:
69         ext_network = next(n['name'] for n in networks if n['router:external'])
70     except StopIteration:
71         LOG.warning("Can't find external network")
72     else:
73         cmd = 'export EXTERNAL_NETWORK=%s' % ext_network
74         try:
75             with open(rc_file, 'a') as f:
76                 f.write(cmd + '\n')
77         except OSError as e:
78             if e.errno != errno.EEXIST:
79                 raise