3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
11 """Tempest testcases implementation."""
13 from __future__ import division
24 from six.moves import configparser
25 from xtesting.core import testcase
28 from functest.core import singlevm
29 from functest.opnfv_tests.openstack.rally import rally
30 from functest.utils import config
31 from functest.utils import env
32 from functest.utils import functest_utils
34 LOGGER = logging.getLogger(__name__)
37 class TempestCommon(singlevm.VmReady2):
38 # pylint: disable=too-many-instance-attributes,too-many-public-methods
39 """TempestCommon testcases implementation class."""
42 filename_alt = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
44 tempest_conf_yaml = pkg_resources.resource_filename(
46 'opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml')
47 tempest_custom = pkg_resources.resource_filename(
49 'opnfv_tests/openstack/tempest/custom_tests/test_list.txt')
50 tempest_blacklist = pkg_resources.resource_filename(
52 'opnfv_tests/openstack/tempest/custom_tests/blacklist.yaml')
54 def __init__(self, **kwargs):
55 if "case_name" not in kwargs:
56 kwargs["case_name"] = 'tempest'
57 super(TempestCommon, self).__init__(**kwargs)
58 assert self.orig_cloud
61 if self.orig_cloud.get_role("admin"):
62 self.role_name = "admin"
63 elif self.orig_cloud.get_role("Admin"):
64 self.role_name = "Admin"
66 raise Exception("Cannot detect neither admin nor Admin")
67 self.orig_cloud.grant_role(
68 self.role_name, user=self.project.user.id,
69 project=self.project.project.id,
70 domain=self.project.domain.id)
71 self.orig_cloud.grant_role(
72 self.role_name, user=self.project.user.id,
73 domain=self.project.domain.id)
74 self.deployment_id = None
75 self.verifier_id = None
76 self.verifier_repo_dir = None
77 self.deployment_dir = None
78 self.verification_id = None
79 self.res_dir = os.path.join(
80 getattr(config.CONF, 'dir_results'), self.case_name)
81 self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
82 self.list = os.path.join(self.res_dir, 'test_list.txt')
85 self.flavor_alt = None
88 self.services = kwargs['run']['args']['services']
89 except Exception: # pylint: disable=broad-except
91 self.neutron_extensions = []
93 self.neutron_extensions = kwargs['run']['args'][
95 except Exception: # pylint: disable=broad-except
97 self.deny_skipping = kwargs.get("deny_skipping", False)
99 def check_services(self):
100 """Check the mandatory services."""
101 for service in self.services:
103 self.cloud.search_services(service)[0]
104 except Exception: # pylint: disable=broad-except
105 self.is_skipped = True
108 def check_extensions(self):
109 """Check the mandatory network extensions."""
110 extensions = self.cloud.get_network_extensions()
111 for network_extension in self.neutron_extensions:
112 if network_extension not in extensions:
114 "Cannot find Neutron extension: %s", network_extension)
115 self.is_skipped = True
118 def check_requirements(self):
119 self.check_services()
120 self.check_extensions()
125 def read_file(filename):
126 """Read file and return content as a stripped list."""
127 with open(filename) as src:
128 return [line.strip() for line in src.readlines()]
131 def get_verifier_result(verif_id):
132 """Retrieve verification results."""
139 cmd = ["rally", "verify", "show", "--uuid", verif_id]
140 LOGGER.info("Showing result for a verification: '%s'.", cmd)
141 proc = subprocess.Popen(cmd,
142 stdout=subprocess.PIPE,
143 stderr=subprocess.STDOUT)
144 for line in proc.stdout:
145 LOGGER.info(line.decode("utf-8").rstrip())
146 new_line = line.decode("utf-8").replace(' ', '').split('|')
147 if 'Tests' in new_line:
149 if 'Testscount' in new_line:
150 result['num_tests'] = int(new_line[2])
151 elif 'Success' in new_line:
152 result['num_success'] = int(new_line[2])
153 elif 'Skipped' in new_line:
154 result['num_skipped'] = int(new_line[2])
155 elif 'Failures' in new_line:
156 result['num_failures'] = int(new_line[2])
160 def backup_tempest_config(conf_file, res_dir):
162 Copy config file to tempest results directory
164 if not os.path.exists(res_dir):
166 shutil.copyfile(conf_file,
167 os.path.join(res_dir, 'tempest.conf'))
170 def create_verifier():
171 """Create new verifier"""
172 LOGGER.info("Create verifier from existing repo...")
173 cmd = ['rally', 'verify', 'delete-verifier',
174 '--id', str(getattr(config.CONF, 'tempest_verifier_name')),
177 output = subprocess.check_output(cmd)
178 LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
179 except subprocess.CalledProcessError:
182 cmd = ['rally', 'verify', 'create-verifier',
183 '--source', str(getattr(config.CONF, 'dir_repo_tempest')),
184 '--name', str(getattr(config.CONF, 'tempest_verifier_name')),
185 '--type', 'tempest', '--system-wide']
186 output = subprocess.check_output(cmd)
187 LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
188 return TempestCommon.get_verifier_id()
191 def get_verifier_id():
193 Returns verifier id for current Tempest
195 cmd = ("rally verify list-verifiers | awk '/" +
196 getattr(config.CONF, 'tempest_verifier_name') +
198 proc = subprocess.Popen(cmd, shell=True,
199 stdout=subprocess.PIPE,
200 stderr=subprocess.STDOUT)
201 verifier_uuid = proc.stdout.readline().rstrip()
202 return verifier_uuid.decode("utf-8")
205 def get_verifier_repo_dir(verifier_id):
207 Returns installed verifier repo directory for Tempest
209 return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
211 'verifier-{}'.format(verifier_id),
215 def get_verifier_deployment_dir(verifier_id, deployment_id):
217 Returns Rally deployment directory for current verifier
219 return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
221 'verifier-{}'.format(verifier_id),
222 'for-deployment-{}'.format(deployment_id))
225 def update_tempest_conf_file(conf_file, rconfig):
226 """Update defined paramters into tempest config file"""
227 with open(TempestCommon.tempest_conf_yaml) as yfile:
228 conf_yaml = yaml.safe_load(yfile)
230 sections = rconfig.sections()
231 for section in conf_yaml:
232 if section not in sections:
233 rconfig.add_section(section)
234 sub_conf = conf_yaml.get(section)
235 for key, value in sub_conf.items():
236 rconfig.set(section, key, value)
238 with open(conf_file, 'w') as config_file:
239 rconfig.write(config_file)
242 def configure_tempest_update_params(
243 tempest_conf_file, image_id=None, flavor_id=None,
244 compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
245 admin_role_name='admin', cidr='192.168.120.0/24',
246 domain_id='default'):
247 # pylint: disable=too-many-branches,too-many-arguments
248 # pylint: disable=too-many-statements,too-many-locals
250 Add/update needed parameters into tempest.conf file
252 LOGGER.debug("Updating selected tempest.conf parameters...")
253 rconfig = configparser.RawConfigParser()
254 rconfig.read(tempest_conf_file)
256 'compute', 'volume_device_name', env.get('VOLUME_DEVICE_NAME'))
257 if image_id is not None:
258 rconfig.set('compute', 'image_ref', image_id)
259 if image_alt_id is not None:
260 rconfig.set('compute', 'image_ref_alt', image_alt_id)
261 if flavor_id is not None:
262 rconfig.set('compute', 'flavor_ref', flavor_id)
263 if flavor_alt_id is not None:
264 rconfig.set('compute', 'flavor_ref_alt', flavor_alt_id)
266 # enable multinode tests
267 rconfig.set('compute', 'min_compute_nodes', compute_cnt)
268 rconfig.set('compute-feature-enabled', 'live_migration', True)
269 filters = ['RetryFilter', 'AvailabilityZoneFilter', 'ComputeFilter',
270 'ComputeCapabilitiesFilter', 'ImagePropertiesFilter',
271 'ServerGroupAntiAffinityFilter',
272 'ServerGroupAffinityFilter']
274 'compute-feature-enabled', 'scheduler_available_filters',
275 functest_utils.convert_list_to_ini(filters))
276 if os.environ.get('OS_REGION_NAME'):
277 rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
278 if env.get("NEW_USER_ROLE").lower() != "member":
280 'auth', 'tempest_roles',
281 functest_utils.convert_list_to_ini([env.get("NEW_USER_ROLE")]))
282 if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
283 rconfig.set('auth', 'use_dynamic_credentials', False)
284 account_file = os.path.join(
285 getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
286 assert os.path.exists(
287 account_file), "{} doesn't exist".format(account_file)
288 rconfig.set('auth', 'test_accounts_file', account_file)
289 rconfig.set('identity', 'auth_version', 'v3')
290 rconfig.set('identity', 'admin_role', admin_role_name)
291 rconfig.set('identity', 'default_domain_id', domain_id)
292 if not rconfig.has_section('network'):
293 rconfig.add_section('network')
294 rconfig.set('network', 'default_network', cidr)
295 rconfig.set('network', 'project_network_cidr', cidr)
296 rconfig.set('network', 'project_networks_reachable', False)
298 'identity', 'v3_endpoint_type',
299 os.environ.get('OS_INTERFACE', 'public'))
301 sections = rconfig.sections()
303 'compute', 'volume', 'image', 'network', 'data-processing',
304 'object-storage', 'orchestration']
305 for service in services_list:
306 if service not in sections:
307 rconfig.add_section(service)
308 rconfig.set(service, 'endpoint_type',
309 os.environ.get('OS_INTERFACE', 'public'))
311 LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
312 'into tempest.conf file')
313 TempestCommon.update_tempest_conf_file(tempest_conf_file, rconfig)
316 def configure_verifier(deployment_dir):
318 Execute rally verify configure-verifier, which generates tempest.conf
320 cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
321 '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
322 output = subprocess.check_output(cmd)
323 LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
325 LOGGER.debug("Looking for tempest.conf file...")
326 tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
327 if not os.path.isfile(tempest_conf_file):
328 LOGGER.error("Tempest configuration file %s NOT found.",
331 return tempest_conf_file
333 def generate_test_list(self, **kwargs):
334 """Generate test list based on the test mode."""
335 LOGGER.debug("Generating test case list...")
336 self.backup_tempest_config(self.conf_file, '/etc')
337 if kwargs.get('mode') == 'custom':
338 if os.path.isfile(self.tempest_custom):
340 self.tempest_custom, self.list)
342 raise Exception("Tempest test list file %s NOT found."
343 % self.tempest_custom)
345 testr_mode = kwargs.get(
346 'mode', r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$')
347 cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
348 self.verifier_repo_dir, testr_mode, self.list)
349 output = subprocess.check_output(cmd, shell=True)
350 LOGGER.info("%s\n%s", cmd, output.decode("utf-8"))
351 os.remove('/etc/tempest.conf')
353 def apply_tempest_blacklist(self):
354 """Exclude blacklisted test cases."""
355 LOGGER.debug("Applying tempest blacklist...")
356 if os.path.exists(self.raw_list):
357 os.remove(self.raw_list)
358 os.rename(self.list, self.raw_list)
359 cases_file = self.read_file(self.raw_list)
360 result_file = open(self.list, 'w')
363 deploy_scenario = env.get('DEPLOY_SCENARIO')
364 if bool(deploy_scenario):
365 # if DEPLOY_SCENARIO is set we read the file
366 black_list_file = open(self.tempest_blacklist)
367 black_list_yaml = yaml.safe_load(black_list_file)
368 black_list_file.close()
369 for item in black_list_yaml:
370 scenarios = item['scenarios']
371 in_it = rally.RallyBase.in_iterable_re
372 if in_it(deploy_scenario, scenarios):
373 tests = item['tests']
374 black_tests.extend(tests)
375 except Exception: # pylint: disable=broad-except
377 LOGGER.debug("Tempest blacklist file does not exist.")
379 for cases_line in cases_file:
380 for black_tests_line in black_tests:
381 if re.search(black_tests_line, cases_line):
384 result_file.write(str(cases_line) + '\n')
387 def run_verifier_tests(self, **kwargs):
388 """Execute tempest test cases."""
389 cmd = ["rally", "verify", "start", "--load-list",
391 cmd.extend(kwargs.get('option', []))
392 LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
395 os.path.join(self.res_dir, "tempest.log"), 'w+')
397 proc = subprocess.Popen(
399 stdout=subprocess.PIPE,
400 stderr=subprocess.STDOUT,
404 for line in iter(proc.stdout.readline, b''):
405 if re.search(r"\} tempest\.", line.decode("utf-8")):
406 LOGGER.info(line.rstrip())
407 elif re.search(r'(?=\(UUID=(.*)\))', line.decode("utf-8")):
408 self.verification_id = re.search(
409 r'(?=\(UUID=(.*)\))', line.decode("utf-8")).group(1)
410 f_stdout.write(line.decode("utf-8"))
414 if self.verification_id is None:
415 raise Exception('Verification UUID not found')
416 LOGGER.info('Verification UUID: %s', self.verification_id)
419 "{}/tempest.log".format(self.deployment_dir),
420 "{}/tempest.debug.log".format(self.res_dir))
422 def parse_verifier_result(self):
423 """Parse and save test results."""
424 stat = self.get_verifier_result(self.verification_id)
426 num_executed = stat['num_tests'] - stat['num_skipped']
428 self.result = 100 * stat['num_success'] / num_executed
429 except ZeroDivisionError:
431 if stat['num_tests'] > 0:
432 LOGGER.info("All tests have been skipped")
434 LOGGER.error("No test has been executed")
437 with open(os.path.join(self.res_dir,
438 "rally.log"), 'r') as logfile:
439 output = logfile.read()
441 success_testcases = []
442 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} success ',
444 success_testcases.append(match)
445 failed_testcases = []
446 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} fail',
448 failed_testcases.append(match)
449 skipped_testcases = []
450 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} skip(?::| )',
452 skipped_testcases.append(match)
454 self.details = {"tests_number": stat['num_tests'],
455 "success_number": stat['num_success'],
456 "skipped_number": stat['num_skipped'],
457 "failures_number": stat['num_failures'],
458 "success": success_testcases,
459 "skipped": skipped_testcases,
460 "failures": failed_testcases}
461 except Exception: # pylint: disable=broad-except
464 LOGGER.info("Tempest %s success_rate is %s%%",
465 self.case_name, self.result)
467 def update_rally_regex(self, rally_conf='/etc/rally/rally.conf'):
468 """Set image name as tempest img_name_regex"""
469 rconfig = configparser.RawConfigParser()
470 rconfig.read(rally_conf)
471 if not rconfig.has_section('openstack'):
472 rconfig.add_section('openstack')
473 rconfig.set('openstack', 'img_name_regex', '^{}$'.format(
475 with open(rally_conf, 'w') as config_file:
476 rconfig.write(config_file)
478 def update_default_role(self, rally_conf='/etc/rally/rally.conf'):
479 """Detect and update the default role if required"""
480 role = self.get_default_role(self.cloud)
483 rconfig = configparser.RawConfigParser()
484 rconfig.read(rally_conf)
485 if not rconfig.has_section('openstack'):
486 rconfig.add_section('openstack')
487 rconfig.set('openstack', 'swift_operator_role', role.name)
488 with open(rally_conf, 'w') as config_file:
489 rconfig.write(config_file)
492 def clean_rally_conf(rally_conf='/etc/rally/rally.conf'):
493 """Clean Rally config"""
494 rconfig = configparser.RawConfigParser()
495 rconfig.read(rally_conf)
496 if rconfig.has_option('openstack', 'img_name_regex'):
497 rconfig.remove_option('openstack', 'img_name_regex')
498 if rconfig.has_option('openstack', 'swift_operator_role'):
499 rconfig.remove_option('openstack', 'swift_operator_role')
500 with open(rally_conf, 'w') as config_file:
501 rconfig.write(config_file)
503 def update_network_section(self):
504 """Update network section in tempest.conf"""
505 rconfig = configparser.RawConfigParser()
506 rconfig.read(self.conf_file)
507 if not rconfig.has_section('network'):
508 rconfig.add_section('network')
509 rconfig.set('network', 'public_network_id', self.ext_net.id)
510 rconfig.set('network', 'floating_network_name', self.ext_net.name)
511 with open(self.conf_file, 'w') as config_file:
512 rconfig.write(config_file)
514 def update_compute_section(self):
515 """Update compute section in tempest.conf"""
516 rconfig = configparser.RawConfigParser()
517 rconfig.read(self.conf_file)
518 if not rconfig.has_section('compute'):
519 rconfig.add_section('compute')
520 rconfig.set('compute', 'fixed_network_name', self.network.name)
521 with open(self.conf_file, 'w') as config_file:
522 rconfig.write(config_file)
524 def update_scenario_section(self):
525 """Update scenario section in tempest.conf"""
526 rconfig = configparser.RawConfigParser()
527 rconfig.read(self.conf_file)
529 config.CONF, '{}_image'.format(self.case_name), self.filename)
530 if not rconfig.has_section('scenario'):
531 rconfig.add_section('scenario')
532 rconfig.set('scenario', 'img_file', os.path.basename(filename))
533 rconfig.set('scenario', 'img_dir', os.path.dirname(filename))
534 rconfig.set('scenario', 'img_disk_format', getattr(
535 config.CONF, '{}_image_format'.format(self.case_name),
537 extra_properties = self.extra_properties.copy()
538 if env.get('IMAGE_PROPERTIES'):
539 extra_properties.update(
540 functest_utils.convert_ini_to_dict(
541 env.get('IMAGE_PROPERTIES')))
542 extra_properties.update(
543 getattr(config.CONF, '{}_extra_properties'.format(
544 self.case_name), {}))
546 'scenario', 'img_properties',
547 functest_utils.convert_dict_to_ini(extra_properties))
548 with open(self.conf_file, 'w') as config_file:
549 rconfig.write(config_file)
551 def configure(self, **kwargs): # pylint: disable=unused-argument
553 Create all openstack resources for tempest-based testcases and write
556 if not os.path.exists(self.res_dir):
557 os.makedirs(self.res_dir)
558 self.deployment_id = rally.RallyBase.create_rally_deployment(
559 environ=self.project.get_environ())
560 if not self.deployment_id:
561 raise Exception("Deployment create failed")
562 self.verifier_id = self.create_verifier()
563 if not self.verifier_id:
564 raise Exception("Verifier create failed")
565 self.verifier_repo_dir = self.get_verifier_repo_dir(
567 self.deployment_dir = self.get_verifier_deployment_dir(
568 self.verifier_id, self.deployment_id)
570 compute_cnt = len(self.orig_cloud.list_hypervisors())
572 self.image_alt = self.publish_image_alt()
573 self.flavor_alt = self.create_flavor_alt()
574 LOGGER.debug("flavor: %s", self.flavor_alt)
576 self.conf_file = self.configure_verifier(self.deployment_dir)
577 if not self.conf_file:
578 raise Exception("Tempest verifier configuring failed")
579 self.configure_tempest_update_params(
581 image_id=self.image.id,
582 flavor_id=self.flavor.id,
583 compute_cnt=compute_cnt,
584 image_alt_id=self.image_alt.id,
585 flavor_alt_id=self.flavor_alt.id,
586 admin_role_name=self.role_name, cidr=self.cidr,
587 domain_id=self.project.domain.id)
588 self.update_network_section()
589 self.update_compute_section()
590 self.update_scenario_section()
591 self.backup_tempest_config(self.conf_file, self.res_dir)
593 def run(self, **kwargs):
594 self.start_time = time.time()
596 assert super(TempestCommon, self).run(
597 **kwargs) == testcase.TestCase.EX_OK
598 if not os.path.exists(self.res_dir):
599 os.makedirs(self.res_dir)
600 self.update_rally_regex()
601 self.update_default_role()
602 rally.RallyBase.update_rally_logs(self.res_dir)
603 shutil.copy("/etc/rally/rally.conf", self.res_dir)
604 self.configure(**kwargs)
605 self.generate_test_list(**kwargs)
606 self.apply_tempest_blacklist()
607 self.run_verifier_tests(**kwargs)
608 self.parse_verifier_result()
609 rally.RallyBase.verify_report(
610 os.path.join(self.res_dir, "tempest-report.html"),
611 self.verification_id)
612 rally.RallyBase.verify_report(
613 os.path.join(self.res_dir, "tempest-report.xml"),
614 self.verification_id, "junit-xml")
615 res = testcase.TestCase.EX_OK
616 except Exception: # pylint: disable=broad-except
617 LOGGER.exception('Error with run')
619 res = testcase.TestCase.EX_RUN_ERROR
620 self.stop_time = time.time()
625 Cleanup all OpenStack objects. Should be called on completion.
627 self.clean_rally_conf()
628 rally.RallyBase.clean_rally_logs()
630 self.cloud.delete_image(self.image_alt)
632 self.orig_cloud.delete_flavor(self.flavor_alt.id)
633 super(TempestCommon, self).clean()
635 def is_successful(self):
636 """The overall result of the test."""
637 skips = self.details.get("skipped_number", 0)
638 if skips > 0 and self.deny_skipping:
639 return testcase.TestCase.EX_TESTCASE_FAILED
640 return super(TempestCommon, self).is_successful()
643 class TempestScenario(TempestCommon):
644 """Tempest scenario testcase implementation class."""
649 def run(self, **kwargs):
650 self.orig_cloud.set_compute_quotas(
651 self.project.project.name,
652 instances=self.quota_instances,
653 cores=self.quota_cores)
654 return super(TempestScenario, self).run(**kwargs)