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