summaryrefslogtreecommitdiffstats
path: root/utils/env_prepare/stack_prepare.py
blob: 6b9bc510a49bb7e82660fb81556073c8ac4b28a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python
##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
import os
import subprocess
import errno
from utils.logger import Logger
from utils.parser import Parser as config
import utils.infra_setup.heat.manager as utils
import utils.infra_setup.runner.docker_env as docker_env
import utils.infra_setup.heat.manager as client_manager

LOG = Logger(__name__).getLogger()


def _prepare_env_daemon(test_yardstick):

    rc_file = config.bottlenecks_config["rc_dir"]

    if not os.path.exists(rc_file):
        installer_ip = os.environ.get('INSTALLER_IP', 'undefined')
        installer_type = os.environ.get('INSTALLER_TYPE', 'undefined')
        _get_remote_rc_file(rc_file, installer_ip, installer_type)

    _source_file(rc_file)

    if not os.environ.get("EXTERNAL_NETWORK"):
        _append_external_network(rc_file)
    if test_yardstick:
        yardstick_contain = docker_env.yardstick_info["container"]
        cmd = "cp %s %s" % (rc_file,
                            config.bottlenecks_config["yardstick_rc_dir"])
        docker_env.docker_exec_cmd(yardstick_contain,
                                   cmd)

    # update the external_network
    _source_file(rc_file)


def file_copy(src_file, dest_file):
    src = file(src_file, "r+")
    des = file(dest_file, "w+")
    des.writelines(src.read())
    src.close()
    des.close()


def _get_remote_rc_file(rc_file, installer_ip, installer_type):

    RELENG_DIR = config.bottlenecks_config["releng_dir"]
    OS_FETCH_SCRIPT = config.bottlenecks_config["fetch_os"]
    os_fetch_script = os.path.join(RELENG_DIR, OS_FETCH_SCRIPT)

    try:
        cmd = [os_fetch_script, '-d', rc_file, '-i', installer_type,
               '-a', installer_ip]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        p.communicate()[0]

        if p.returncode != 0:
            LOG.debug('Failed to fetch credentials from installer')
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise


def _source_file(rc_file):
    p = subprocess.Popen(". %s; env" % rc_file, stdout=subprocess.PIPE,
                         shell=True)
    output = p.communicate()[0]
    output_lines = output.splitlines()
    env = list()
    for line in output_lines:
        if '=' in line:
            env.append(tuple(line.split('=', 1)))

    env = dict(env)
#    env = dict((line.split('=', 1) for line in output_lines))
    os.environ.update(env)
    return env


def _append_external_network(rc_file):
    neutron_client = utils._get_neutron_client()
    networks = neutron_client.list_networks()['networks']
    try:
        ext_network = next(n['name'] for n in networks if n['router:external'])
    except StopIteration:
        LOG.warning("Can't find external network")
    else:
        cmd = 'export EXTERNAL_NETWORK=%s' % ext_network
        try:
            with open(rc_file, 'a') as f:
                f.write(cmd + '\n')
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise


def prepare_image(image_name, image_dir):
    glance_client = client_manager._get_glance_client()
    if not os.path.isfile(image_dir):
        LOG.error("Error: file %s does not exist.", image_dir)
        return None
    try:
        images = glance_client.images.list()
        image_id = next((i.id for i in images if i.name == image_name), None)
        if image_id is not None:
            LOG.info("Image %s already exists.", image_name)
        else:
            LOG.info("Creating image '%s' from '%s'...", image_name, image_dir)

            image = glance_client.images.create(
                name=image_name, visibility="public", disk_format="qcow2",
                container_format="bare")
            image_id = image.id
            with open(image_dir) as image_data:
                glance_client.images.upload(image_id, image_data)
        return image_id
    except Exception:  # pylint: disable=broad-except
        LOG.error(
            "Error [create_glance_image(glance_client, '%s', '%s')]",
            image_name, image_dir)
        return None