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