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
21 import functest.utils.functest_utils as ft_utils
22 import functest.utils.openstack_utils as os_utils
23 from functest.utils.constants import CONST
25 from opnfv.utils import constants as opnfv_constants
26 from opnfv.deployment import factory
28 actions = ['start', 'check']
30 """ logging configuration """
31 logger = logging.getLogger('functest.ci.prepare_env')
33 # set the architecture to default
35 arch_filter = ['aarch64']
37 CONFIG_FUNCTEST_PATH = CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
38 CONFIG_PATCH_PATH = os.path.join(os.path.dirname(
39 CONFIG_FUNCTEST_PATH), "config_patch.yaml")
40 CONFIG_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
41 CONFIG_FUNCTEST_PATH), "config_aarch64_patch.yaml")
42 RALLY_CONF_PATH = os.path.join("/etc/rally/rally.conf")
43 RALLY_AARCH64_PATCH_PATH = os.path.join(os.path.dirname(
44 CONFIG_FUNCTEST_PATH), "rally_aarch64_patch.conf")
47 class PrepareEnvParser(object):
50 self.parser = argparse.ArgumentParser()
51 self.parser.add_argument("action", help="Possible actions are: "
52 "'{d[0]}|{d[1]}' ".format(d=actions),
54 self.parser.add_argument("-d", "--debug", help="Debug mode",
57 def parse_args(self, argv=[]):
58 return vars(self.parser.parse_args(argv))
61 def print_separator():
62 logger.info("==============================================")
65 def check_env_variables():
67 logger.info("Checking environment variables...")
69 if CONST.__getattribute__('INSTALLER_TYPE') is None:
70 logger.warning("The env variable 'INSTALLER_TYPE' is not defined.")
71 CONST.__setattr__('INSTALLER_TYPE', 'undefined')
73 if (CONST.__getattribute__('INSTALLER_TYPE') not in
74 opnfv_constants.INSTALLERS):
75 logger.warning("INSTALLER_TYPE=%s is not a valid OPNFV installer. "
76 "Available OPNFV Installers are : %s. "
77 "Setting INSTALLER_TYPE=undefined."
78 % (CONST.__getattribute__('INSTALLER_TYPE'),
79 opnfv_constants.INSTALLERS))
80 CONST.__setattr__('INSTALLER_TYPE', 'undefined')
82 logger.info(" INSTALLER_TYPE=%s"
83 % CONST.__getattribute__('INSTALLER_TYPE'))
85 if CONST.__getattribute__('INSTALLER_IP') is None:
87 "The env variable 'INSTALLER_IP' is not defined. It is recommended"
88 " to extract some information from the deployment")
90 logger.info(" INSTALLER_IP=%s" %
91 CONST.__getattribute__('INSTALLER_IP'))
93 if CONST.__getattribute__('DEPLOY_SCENARIO') is None:
94 logger.warning("The env variable 'DEPLOY_SCENARIO' is not defined. "
95 "Setting CI_SCENARIO=undefined.")
96 CONST.__setattr__('DEPLOY_SCENARIO', 'undefined')
98 logger.info(" DEPLOY_SCENARIO=%s"
99 % CONST.__getattribute__('DEPLOY_SCENARIO'))
100 if CONST.__getattribute__('CI_DEBUG'):
101 logger.info(" CI_DEBUG=%s" % CONST.__getattribute__('CI_DEBUG'))
103 if CONST.__getattribute__('NODE_NAME'):
104 logger.info(" NODE_NAME=%s" % CONST.__getattribute__('NODE_NAME'))
106 if CONST.__getattribute__('BUILD_TAG'):
107 logger.info(" BUILD_TAG=%s" % CONST.__getattribute__('BUILD_TAG'))
109 if CONST.__getattribute__('IS_CI_RUN'):
110 logger.info(" IS_CI_RUN=%s" % CONST.__getattribute__('IS_CI_RUN'))
113 def get_deployment_handler():
117 installer_params_yaml = os.path.join(
118 CONST.__getattribute__('dir_repo_functest'),
119 'functest/ci/installer_params.yaml')
120 if (CONST.__getattribute__('INSTALLER_IP') and
121 CONST.__getattribute__('INSTALLER_TYPE') and
122 CONST.__getattribute__('INSTALLER_TYPE') in
123 opnfv_constants.INSTALLERS):
125 installer_params = ft_utils.get_parameter_from_yaml(
126 CONST.__getattribute__('INSTALLER_TYPE'),
127 installer_params_yaml)
128 except ValueError as e:
129 logger.debug('Printing deployment info is not supported for %s' %
130 CONST.__getattribute__('INSTALLER_TYPE'))
133 user = installer_params.get('user', None)
134 password = installer_params.get('password', None)
135 pkey = installer_params.get('pkey', None)
137 handler = factory.Factory.get_handler(
138 installer=CONST.__getattribute__('INSTALLER_TYPE'),
139 installer_ip=CONST.__getattribute__('INSTALLER_IP'),
141 installer_pwd=password,
144 pod_arch = handler.get_arch()
145 except Exception as e:
146 logger.debug("Cannot get deployment information. %s" % e)
149 def create_directories():
151 logger.info("Creating needed directories...")
152 if not os.path.exists(CONST.__getattribute__('dir_functest_conf')):
153 os.makedirs(CONST.__getattribute__('dir_functest_conf'))
154 logger.info(" %s created." %
155 CONST.__getattribute__('dir_functest_conf'))
157 logger.debug(" %s already exists." %
158 CONST.__getattribute__('dir_functest_conf'))
160 if not os.path.exists(CONST.__getattribute__('dir_functest_data')):
161 os.makedirs(CONST.__getattribute__('dir_functest_data'))
162 logger.info(" %s created." %
163 CONST.__getattribute__('dir_functest_data'))
165 logger.debug(" %s already exists." %
166 CONST.__getattribute__('dir_functest_data'))
167 if not os.path.exists(CONST.__getattribute__('dir_functest_images')):
168 os.makedirs(CONST.__getattribute__('dir_functest_images'))
169 logger.info(" %s created." %
170 CONST.__getattribute__('dir_functest_images'))
172 logger.debug(" %s already exists." %
173 CONST.__getattribute__('dir_functest_images'))
176 def source_rc_file():
179 if CONST.__getattribute__('openstack_creds') is None:
180 logger.warning("The environment variable 'creds' must be set and"
181 "pointing to the local RC file. Using default: "
182 "/home/opnfv/functest/conf/openstack.creds ...")
184 CONST.__getattribute__('dir_functest_conf'), 'openstack.creds')
186 if not os.path.isfile(CONST.__getattribute__('openstack_creds')):
188 "OpenStack credentials file not provided. "
189 "The OpenStack credentials must be in {}"
190 .format(CONST.__getattribute__('openstack_creds')))
192 logger.info("RC file provided in %s."
193 % CONST.__getattribute__('openstack_creds'))
194 if os.path.getsize(CONST.__getattribute__('openstack_creds')) == 0:
196 "The OpenStack RC file {} is empty."
197 .format(CONST.__getattribute__('openstack_creds')))
199 logger.info("Sourcing the OpenStack RC file...")
200 os_utils.source_credentials(CONST.__getattribute__('openstack_creds'))
201 for key, value in os.environ.iteritems():
202 if re.search("OS_", key):
203 if key == 'OS_AUTH_URL':
204 CONST.__setattr__('OS_AUTH_URL', value)
205 elif key == 'OS_USERNAME':
206 CONST.__setattr__('OS_USERNAME', value)
207 elif key == 'OS_TENANT_NAME':
208 CONST.__setattr__('OS_TENANT_NAME', value)
209 elif key == 'OS_PASSWORD':
210 CONST.__setattr__('OS_PASSWORD', value)
213 def patch_config_file():
214 patch_file(CONFIG_PATCH_PATH)
216 if pod_arch and pod_arch in arch_filter:
217 patch_file(CONFIG_AARCH64_PATCH_PATH)
220 def patch_file(patch_file_path):
221 logger.debug('Updating file: %s', patch_file_path)
222 with open(patch_file_path) as f:
223 patch_file = yaml.safe_load(f)
226 for key in patch_file:
227 if key in CONST.__getattribute__('DEPLOY_SCENARIO'):
228 new_functest_yaml = dict(ft_utils.merge_dicts(
229 ft_utils.get_functest_yaml(), patch_file[key]))
233 os.remove(CONFIG_FUNCTEST_PATH)
234 with open(CONFIG_FUNCTEST_PATH, "w") as f:
235 f.write(yaml.dump(new_functest_yaml, default_style='"'))
239 def verify_deployment():
241 logger.info("Verifying OpenStack services...")
242 cmd = ("%s/functest/ci/check_os.sh" %
243 CONST.__getattribute__('dir_repo_functest'))
245 logger.debug("Executing command: %s" % cmd)
246 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
248 while p.poll() is None:
249 line = p.stdout.readline().rstrip()
252 raise Exception("Problem while running 'check_os.sh'.")
259 if pod_arch and pod_arch in arch_filter:
260 logger.info("Apply aarch64 specific to rally config...")
261 with open(RALLY_AARCH64_PATCH_PATH, "r") as f:
262 rally_patch_conf = f.read()
264 for line in fileinput.input(RALLY_CONF_PATH, inplace=1):
266 if "cirros|testvm" in line:
267 print rally_patch_conf
269 logger.info("Creating Rally environment...")
271 cmd = "rally deployment destroy opnfv-rally"
272 ft_utils.execute_command(cmd, error_msg=(
273 "Deployment %s does not exist."
274 % CONST.__getattribute__('rally_deployment_name')),
277 rally_conf = os_utils.get_credentials_for_rally()
278 with open('rally_conf.json', 'w') as fp:
279 json.dump(rally_conf, fp)
280 cmd = ("rally deployment create "
281 "--file=rally_conf.json --name={0}"
282 .format(CONST.__getattribute__('rally_deployment_name')))
283 error_msg = "Problem while creating Rally deployment"
284 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
286 cmd = "rally deployment check"
287 error_msg = "OpenStack not responding or faulty Rally deployment."
288 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
290 cmd = "rally deployment list"
291 ft_utils.execute_command(cmd,
292 error_msg=("Problem while listing "
293 "Rally deployment."))
295 cmd = "rally plugin list | head -5"
296 ft_utils.execute_command(cmd,
297 error_msg=("Problem while showing "
301 def install_tempest():
302 logger.info("Installing tempest from existing repo...")
303 cmd = ("rally verify list-verifiers | "
304 "grep '{0}' | wc -l".format(
305 CONST.__getattribute__('tempest_deployment_name')))
306 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
307 while p.poll() is None:
308 line = p.stdout.readline().rstrip()
310 logger.debug("Tempest %s does not exist" %
311 CONST.__getattribute__('tempest_deployment_name'))
312 cmd = ("rally verify create-verifier --source {0} "
313 "--name {1} --type tempest --system-wide"
314 .format(CONST.__getattribute__('dir_repo_tempest'),
315 CONST.__getattribute__('tempest_deployment_name')))
316 error_msg = "Problem while installing Tempest."
317 ft_utils.execute_command_raise(cmd, error_msg=error_msg)
321 _, flavor_id = os_utils.get_or_create_flavor('m1.tiny',
326 if flavor_id is None:
327 raise Exception('Failed to create flavor')
330 def check_environment():
331 msg_not_active = "The Functest environment is not installed."
332 if not os.path.isfile(CONST.__getattribute__('env_active')):
333 raise Exception(msg_not_active)
335 with open(CONST.__getattribute__('env_active'), "r") as env_file:
337 if not re.search("1", s):
338 raise Exception(msg_not_active)
340 logger.info("Functest environment is installed.")
343 def print_deployment_info():
345 logger.info('\n\nDeployment information:\n%s' %
346 handler.get_deployment_info())
351 if not (kwargs['action'] in actions):
352 logger.error('Argument not valid.')
354 elif kwargs['action'] == "start":
355 logger.info("######### Preparing Functest environment #########\n")
356 check_env_variables()
357 get_deployment_handler()
365 with open(CONST.__getattribute__('env_active'), "w") as env_file:
368 print_deployment_info()
369 elif kwargs['action'] == "check":
371 except Exception as e:
377 if __name__ == '__main__':
378 logging.config.fileConfig(
379 CONST.__getattribute__('dir_functest_logging_cfg'))
380 parser = PrepareEnvParser()
381 args = parser.parse_args(sys.argv[1:])
382 sys.exit(main(**args))