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