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