Add wrappers for Tacker Python client
[functest.git] / ci / prepare_env.py
1 #!/usr/bin/env python
2 #
3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
4 #
5 # Installs the Functest framework within the Docker container
6 # and run the tests automatically
7 #
8 #
9 # All rights reserved. This program and the accompanying materials
10 # are made available under the terms of the Apache License, Version 2.0
11 # which accompanies this distribution, and is available at
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14
15
16 import json
17 import os
18 import re
19 import subprocess
20 import sys
21
22 import argparse
23 import yaml
24
25 import functest.utils.functest_logger as ft_logger
26 import functest.utils.functest_utils as ft_utils
27 import functest.utils.openstack_utils as os_utils
28
29 actions = ['start', 'check']
30 parser = argparse.ArgumentParser()
31 parser.add_argument("action", help="Possible actions are: "
32                     "'{d[0]}|{d[1]}' ".format(d=actions))
33 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
34 args = parser.parse_args()
35
36
37 """ logging configuration """
38 logger = ft_logger.Logger("prepare_env").getLogger()
39
40
41 """ global variables """
42 INSTALLERS = ['fuel', 'compass', 'apex', 'joid']
43 CI_INSTALLER_TYPE = ""
44 CI_INSTALLER_IP = ""
45 CI_SCENARIO = ""
46 CI_DEBUG = False
47 CONFIG_FUNCTEST_PATH = os.environ["CONFIG_FUNCTEST_YAML"]
48 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
49     CONFIG_FUNCTEST_PATH), "config_patch.yaml")
50
51 with open(CONFIG_PATCH_PATH) as f:
52     functest_patch_yaml = yaml.safe_load(f)
53
54 FUNCTEST_CONF_DIR = \
55     ft_utils.get_functest_config('general.directories.dir_functest_conf')
56
57
58 FUNCTEST_DATA_DIR = \
59     ft_utils.get_functest_config('general.directories.dir_functest_data')
60 FUNCTEST_RESULTS_DIR = \
61     ft_utils.get_functest_config('general.directories.dir_results')
62 DEPLOYMENT_MAME = \
63     ft_utils.get_functest_config('rally.deployment_name')
64 TEMPEST_REPO_DIR = \
65     ft_utils.get_functest_config('general.directories.dir_repo_tempest')
66
67 ENV_FILE = FUNCTEST_CONF_DIR + "/env_active"
68
69
70 def print_separator():
71     logger.info("==============================================")
72
73
74 def check_env_variables():
75     print_separator()
76     logger.info("Checking environment variables...")
77     global CI_INSTALLER_TYPE
78     global CI_INSTALLER_IP
79     global CI_DEBUG
80     global CI_SCENARIO
81     CI_INSTALLER_TYPE = os.getenv('INSTALLER_TYPE')
82     CI_INSTALLER_IP = os.getenv('INSTALLER_IP')
83     CI_SCENARIO = os.getenv('DEPLOY_SCENARIO')
84     CI_NODE = os.getenv('NODE_NAME')
85     CI_BUILD_TAG = os.getenv('BUILD_TAG')
86     CI_DEBUG = os.getenv('CI_DEBUG')
87
88     if CI_INSTALLER_TYPE is None:
89         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
90         CI_INSTALLER_TYPE = "undefined"
91     else:
92         if CI_INSTALLER_TYPE not in INSTALLERS:
93             logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
94                            "Available OPNFV Installers are : %s. "
95                            "Setting INSTALLER_TYPE=undefined."
96                            % (CI_INSTALLER_TYPE, INSTALLERS))
97             CI_INSTALLER_TYPE = "undefined"
98         else:
99             logger.info("    INSTALLER_TYPE=%s" % CI_INSTALLER_TYPE)
100
101     if CI_INSTALLER_IP is None:
102         logger.warning("The env variable 'INSTALLER_IP' is not defined. "
103                        "It is needed to fetch the OpenStack credentials. "
104                        "If the credentials are not provided to the "
105                        "container as a volume, please add this env variable "
106                        "to the 'docker run' command.")
107     else:
108         logger.info("    INSTALLER_IP=%s" % CI_INSTALLER_IP)
109
110     if CI_SCENARIO is None:
111         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
112                        "Setting CE_SCENARIO=undefined.")
113         CI_SCENARIO = "undefined"
114     else:
115         logger.info("    DEPLOY_SCENARIO=%s" % CI_SCENARIO)
116     if CI_DEBUG:
117         logger.info("    CI_DEBUG=%s" % CI_DEBUG)
118
119     if CI_NODE:
120         logger.info("    NODE_NAME=%s" % CI_NODE)
121
122     if CI_BUILD_TAG:
123         logger.info("    BUILD_TAG=%s" % CI_BUILD_TAG)
124
125
126 def create_directories():
127     print_separator()
128     logger.info("Creating needed directories...")
129     if not os.path.exists(FUNCTEST_CONF_DIR):
130         os.makedirs(FUNCTEST_CONF_DIR)
131         logger.info("    %s created." % FUNCTEST_CONF_DIR)
132     else:
133         logger.debug("   %s already exists." % FUNCTEST_CONF_DIR)
134
135     if not os.path.exists(FUNCTEST_DATA_DIR):
136         os.makedirs(FUNCTEST_DATA_DIR)
137         logger.info("    %s created." % FUNCTEST_DATA_DIR)
138     else:
139         logger.debug("   %s already exists." % FUNCTEST_DATA_DIR)
140
141
142 def source_rc_file():
143     print_separator()
144     logger.info("Fetching RC file...")
145     rc_file = os.getenv('creds')
146     if rc_file is None:
147         logger.warning("The environment variable 'creds' must be set and"
148                        "pointing to the local RC file. Using default: "
149                        "/home/opnfv/functest/conf/openstack.creds ...")
150         rc_file = "/home/opnfv/functest/conf/openstack.creds"
151
152     if not os.path.isfile(rc_file):
153         logger.info("RC file not provided. "
154                     "Fetching it from the installer...")
155         if CI_INSTALLER_IP is None:
156             logger.error("The env variable CI_INSTALLER_IP must be provided in"
157                          " order to fetch the credentials from the installer.")
158             sys.exit("Missing CI_INSTALLER_IP.")
159         if CI_INSTALLER_TYPE not in INSTALLERS:
160             logger.error("Cannot fetch credentials. INSTALLER_TYPE=%s is "
161                          "not a valid OPNFV installer. Available "
162                          "installers are : %s." % INSTALLERS)
163             sys.exit("Wrong INSTALLER_TYPE.")
164
165         cmd = ("/home/opnfv/repos/releng/utils/fetch_os_creds.sh "
166                "-d %s -i %s -a %s"
167                % (rc_file, CI_INSTALLER_TYPE, CI_INSTALLER_IP))
168         logger.debug("Executing command: %s" % cmd)
169         p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
170         output = p.communicate()[0]
171         logger.debug("\n%s" % output)
172         if p.returncode != 0:
173             logger.error("Failed to fetch credentials from installer.")
174             sys.exit(1)
175     else:
176         logger.info("RC file provided in %s." % rc_file)
177         if os.path.getsize(rc_file) == 0:
178             logger.error("The file %s is empty." % rc_file)
179             sys.exit(1)
180
181     logger.info("Sourcing the OpenStack RC file...")
182     creds = os_utils.source_credentials(rc_file)
183     str = ""
184     for key, value in creds.iteritems():
185         if re.search("OS_", key):
186             str += "\n\t\t\t\t\t\t   " + key + "=" + value
187     logger.debug("Used credentials: %s" % str)
188
189
190 def patch_config_file():
191     updated = False
192     for key in functest_patch_yaml:
193         if key in CI_SCENARIO:
194             new_functest_yaml = dict(ft_utils.merge_dicts(
195                 ft_utils.get_functest_yaml(), functest_patch_yaml[key]))
196             updated = True
197
198     if updated:
199         os.remove(CONFIG_FUNCTEST_PATH)
200         with open(CONFIG_FUNCTEST_PATH, "w") as f:
201             f.write(yaml.dump(new_functest_yaml, default_style='"'))
202         f.close()
203
204
205 def verify_deployment():
206     print_separator()
207     logger.info("Verifying OpenStack services...")
208     cmd = ("%s/ci/check_os.sh" % ft_utils.FUNCTEST_REPO)
209
210     logger.debug("Executing command: %s" % cmd)
211     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
212
213     while p.poll() is None:
214         line = p.stdout.readline().rstrip()
215         if "ERROR" in line:
216             logger.error(line)
217             sys.exit("Problem while running 'check_os.sh'.")
218         logger.info(line)
219
220
221 def install_rally():
222     print_separator()
223     logger.info("Creating Rally environment...")
224
225     cmd = "rally deployment destroy opnfv-rally"
226     ft_utils.execute_command(cmd, exit_on_error=False,
227                              error_msg=("Deployment %s does not exist."
228                                         % DEPLOYMENT_MAME), verbose=False)
229     rally_conf = os_utils.get_credentials_for_rally()
230     with open('rally_conf.json', 'w') as fp:
231         json.dump(rally_conf, fp)
232     cmd = "rally deployment create --file=rally_conf.json --name="
233     cmd += DEPLOYMENT_MAME
234     ft_utils.execute_command(cmd,
235                              error_msg="Problem creating Rally deployment")
236
237     logger.info("Installing tempest from existing repo...")
238     cmd = ("rally verify install --source " + TEMPEST_REPO_DIR +
239            " --system-wide")
240     ft_utils.execute_command(cmd,
241                              error_msg="Problem installing Tempest.")
242
243     cmd = "rally deployment check"
244     ft_utils.execute_command(cmd,
245                              error_msg=("OpenStack not responding or "
246                                         "faulty Rally deployment."))
247
248     cmd = "rally show images"
249     ft_utils.execute_command(cmd,
250                              error_msg=("Problem while listing "
251                                         "OpenStack images."))
252
253     cmd = "rally show flavors"
254     ft_utils.execute_command(cmd,
255                              error_msg=("Problem while showing "
256                                         "OpenStack flavors."))
257
258
259 def check_environment():
260     msg_not_active = "The Functest environment is not installed."
261     if not os.path.isfile(ENV_FILE):
262         logger.error(msg_not_active)
263         sys.exit(1)
264
265     with open(ENV_FILE, "r") as env_file:
266         s = env_file.read()
267         if not re.search("1", s):
268             logger.error(msg_not_active)
269             sys.exit(1)
270
271     logger.info("Functest environment installed.")
272
273
274 def main():
275     if not (args.action in actions):
276         logger.error('Argument not valid.')
277         sys.exit()
278
279     if args.action == "start":
280         logger.info("######### Preparing Functest environment #########\n")
281         check_env_variables()
282         create_directories()
283         source_rc_file()
284         patch_config_file()
285         verify_deployment()
286         install_rally()
287
288         with open(ENV_FILE, "w") as env_file:
289             env_file.write("1")
290
291         check_environment()
292
293     if args.action == "check":
294         check_environment()
295
296     exit(0)
297
298 if __name__ == '__main__':
299     main()