Move rally and tempest out of functest-core
[functest-xtesting.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 logging
11 import logging.config
12 import os
13 import pkg_resources
14 import re
15 import sys
16
17 import yaml
18
19 from functest.ci import check_deployment
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 = logging.getLogger('functest.ci.prepare_env')
31 handler = None
32 # set the architecture to default
33 pod_arch = os.getenv("POD_ARCH", None)
34 arch_filter = ['aarch64']
35
36 CONFIG_FUNCTEST_PATH = pkg_resources.resource_filename(
37     'functest', 'ci/config_functest.yaml')
38 CONFIG_PATCH_PATH = pkg_resources.resource_filename(
39     'functest', 'ci/config_patch.yaml')
40 CONFIG_AARCH64_PATCH_PATH = pkg_resources.resource_filename(
41     'functest', 'ci/config_aarch64_patch.yaml')
42
43
44 class PrepareEnvParser(object):
45
46     def __init__(self):
47         self.parser = argparse.ArgumentParser()
48         self.parser.add_argument("action", help="Possible actions are: "
49                                  "'{d[0]}|{d[1]}' ".format(d=actions),
50                                  choices=actions)
51         self.parser.add_argument("-d", "--debug", help="Debug mode",
52                                  action="store_true")
53
54     def parse_args(self, argv=[]):
55         return vars(self.parser.parse_args(argv))
56
57
58 def print_separator():
59     logger.info("==============================================")
60
61
62 def check_env_variables():
63     print_separator()
64     logger.info("Checking environment variables...")
65
66     if CONST.__getattribute__('INSTALLER_TYPE') is None:
67         logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
68         CONST.__setattr__('INSTALLER_TYPE', 'undefined')
69     else:
70         if (CONST.__getattribute__('INSTALLER_TYPE') not in
71                 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.__getattribute__('INSTALLER_TYPE'),
76                               opnfv_constants.INSTALLERS))
77             CONST.__setattr__('INSTALLER_TYPE', 'undefined')
78         else:
79             logger.info("    INSTALLER_TYPE=%s"
80                         % CONST.__getattribute__('INSTALLER_TYPE'))
81
82     if CONST.__getattribute__('INSTALLER_IP') is None:
83         logger.warning(
84             "The env variable 'INSTALLER_IP' is not defined. It is recommended"
85             " to extract some information from the deployment")
86     else:
87         logger.info("    INSTALLER_IP=%s" %
88                     CONST.__getattribute__('INSTALLER_IP'))
89
90     if CONST.__getattribute__('DEPLOY_SCENARIO') is None:
91         logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
92                        "Setting CI_SCENARIO=undefined.")
93         CONST.__setattr__('DEPLOY_SCENARIO', 'undefined')
94     else:
95         logger.info("    DEPLOY_SCENARIO=%s"
96                     % CONST.__getattribute__('DEPLOY_SCENARIO'))
97     if CONST.__getattribute__('CI_DEBUG'):
98         logger.info("    CI_DEBUG=%s" % CONST.__getattribute__('CI_DEBUG'))
99
100     if CONST.__getattribute__('NODE_NAME'):
101         logger.info("    NODE_NAME=%s" % CONST.__getattribute__('NODE_NAME'))
102
103     if CONST.__getattribute__('BUILD_TAG'):
104         logger.info("    BUILD_TAG=%s" % CONST.__getattribute__('BUILD_TAG'))
105
106     if CONST.__getattribute__('IS_CI_RUN'):
107         logger.info("    IS_CI_RUN=%s" % CONST.__getattribute__('IS_CI_RUN'))
108
109
110 def get_deployment_handler():
111     global handler
112     global pod_arch
113
114     installer_params_yaml = pkg_resources.resource_filename(
115         'functest', 'ci/installer_params.yaml')
116     if (CONST.__getattribute__('INSTALLER_IP') and
117         CONST.__getattribute__('INSTALLER_TYPE') and
118             CONST.__getattribute__('INSTALLER_TYPE') in
119             opnfv_constants.INSTALLERS):
120         try:
121             installer_params = ft_utils.get_parameter_from_yaml(
122                 CONST.__getattribute__('INSTALLER_TYPE'),
123                 installer_params_yaml)
124         except ValueError as e:
125             logger.debug('Printing deployment info is not supported for %s' %
126                          CONST.__getattribute__('INSTALLER_TYPE'))
127             logger.debug(e)
128         else:
129             user = installer_params.get('user', None)
130             password = installer_params.get('password', None)
131             pkey = installer_params.get('pkey', None)
132             try:
133                 handler = factory.Factory.get_handler(
134                     installer=CONST.__getattribute__('INSTALLER_TYPE'),
135                     installer_ip=CONST.__getattribute__('INSTALLER_IP'),
136                     installer_user=user,
137                     installer_pwd=password,
138                     pkey_file=pkey)
139                 if handler:
140                     pod_arch = handler.get_arch()
141             except Exception as e:
142                 logger.debug("Cannot get deployment information. %s" % e)
143
144
145 def create_directories():
146     print_separator()
147     logger.info("Creating needed directories...")
148     if not os.path.exists(CONST.__getattribute__('dir_functest_conf')):
149         os.makedirs(CONST.__getattribute__('dir_functest_conf'))
150         logger.info("    %s created." %
151                     CONST.__getattribute__('dir_functest_conf'))
152     else:
153         logger.debug("   %s already exists." %
154                      CONST.__getattribute__('dir_functest_conf'))
155
156     if not os.path.exists(CONST.__getattribute__('dir_functest_data')):
157         os.makedirs(CONST.__getattribute__('dir_functest_data'))
158         logger.info("    %s created." %
159                     CONST.__getattribute__('dir_functest_data'))
160     else:
161         logger.debug("   %s already exists." %
162                      CONST.__getattribute__('dir_functest_data'))
163     if not os.path.exists(CONST.__getattribute__('dir_functest_images')):
164         os.makedirs(CONST.__getattribute__('dir_functest_images'))
165         logger.info("    %s created." %
166                     CONST.__getattribute__('dir_functest_images'))
167     else:
168         logger.debug("   %s already exists." %
169                      CONST.__getattribute__('dir_functest_images'))
170
171
172 def source_rc_file():
173     print_separator()
174
175     logger.info("Sourcing the OpenStack RC file...")
176     os_utils.source_credentials(CONST.__getattribute__('openstack_creds'))
177     for key, value in os.environ.iteritems():
178         if re.search("OS_", key):
179             if key == 'OS_AUTH_URL':
180                 CONST.__setattr__('OS_AUTH_URL', value)
181             elif key == 'OS_USERNAME':
182                 CONST.__setattr__('OS_USERNAME', value)
183             elif key == 'OS_TENANT_NAME':
184                 CONST.__setattr__('OS_TENANT_NAME', value)
185             elif key == 'OS_PASSWORD':
186                 CONST.__setattr__('OS_PASSWORD', value)
187
188
189 def update_config_file():
190     patch_file(CONFIG_PATCH_PATH)
191
192     if pod_arch and pod_arch in arch_filter:
193         patch_file(CONFIG_AARCH64_PATCH_PATH)
194
195     if "TEST_DB_URL" in os.environ:
196         update_db_url()
197
198
199 def patch_file(patch_file_path):
200     logger.debug('Updating file: %s', patch_file_path)
201     with open(patch_file_path) as f:
202         patch_file = yaml.safe_load(f)
203
204     updated = False
205     for key in patch_file:
206         if key in CONST.__getattribute__('DEPLOY_SCENARIO'):
207             new_functest_yaml = dict(ft_utils.merge_dicts(
208                 ft_utils.get_functest_yaml(), patch_file[key]))
209             updated = True
210
211     if updated:
212         os.remove(CONFIG_FUNCTEST_PATH)
213         with open(CONFIG_FUNCTEST_PATH, "w") as f:
214             f.write(yaml.dump(new_functest_yaml, default_style='"'))
215
216
217 def update_db_url():
218     with open(CONFIG_FUNCTEST_PATH) as f:
219         functest_yaml = yaml.safe_load(f)
220
221     with open(CONFIG_FUNCTEST_PATH, "w") as f:
222         functest_yaml["results"]["test_db_url"] = os.environ.get('TEST_DB_URL')
223         f.write(yaml.dump(functest_yaml, default_style='"'))
224
225
226 def verify_deployment():
227     print_separator()
228     logger.info("Verifying OpenStack deployment...")
229     deployment = check_deployment.CheckDeployment()
230     deployment.check_all()
231
232
233 def create_flavor():
234     _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
235                                                  '512',
236                                                  '1',
237                                                  '1',
238                                                  public=True)
239     if flavor_id is None:
240         raise Exception('Failed to create flavor')
241
242
243 def check_environment():
244     msg_not_active = "The Functest environment is not installed."
245     if not os.path.isfile(CONST.__getattribute__('env_active')):
246         raise Exception(msg_not_active)
247
248     with open(CONST.__getattribute__('env_active'), "r") as env_file:
249         s = env_file.read()
250         if not re.search("1", s):
251             raise Exception(msg_not_active)
252
253     logger.info("Functest environment is installed.")
254
255
256 def print_deployment_info():
257     if handler:
258         logger.info('\n\nDeployment information:\n%s' %
259                     handler.get_deployment_info())
260
261
262 def prepare_env(**kwargs):
263     try:
264         if not (kwargs['action'] in actions):
265             logger.error('Argument not valid.')
266             return -1
267         elif kwargs['action'] == "start":
268             logger.info("######### Preparing Functest environment #########\n")
269             verify_deployment()
270             check_env_variables()
271             create_directories()
272             source_rc_file()
273             update_config_file()
274             create_flavor()
275             with open(CONST.__getattribute__('env_active'), "w") as env_file:
276                 env_file.write("1")
277             check_environment()
278         elif kwargs['action'] == "check":
279             check_environment()
280     except Exception as e:
281         logger.error(e)
282         return -1
283     return 0
284
285
286 def main():
287     logging.config.fileConfig(pkg_resources.resource_filename(
288         'functest', 'ci/logging.ini'))
289     logging.captureWarnings(True)
290     parser = PrepareEnvParser()
291     args = parser.parse_args(sys.argv[1:])
292     return prepare_env(**args)