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 """Rally testcases implementation."""
13 from __future__ import division
23 import os_client_config
26 from xtesting.core import testcase
27 from xtesting.energy import energy
30 from functest.opnfv_tests.openstack.tempest import conf_utils
31 from functest.utils import config
32 from functest.utils import functest_utils
33 from functest.utils import env
35 LOGGER = logging.getLogger(__name__)
38 class RallyBase(testcase.TestCase):
39 """Base class form Rally testcases implementation."""
41 # pylint: disable=too-many-instance-attributes
42 TESTS = ['authenticate', 'glance', 'cinder', 'gnocchi', 'heat',
43 'keystone', 'neutron', 'nova', 'quotas', 'vm', 'all']
44 GLANCE_IMAGE_NAME = getattr(config.CONF, 'openstack_image_name')
45 GLANCE_IMAGE_FILENAME = getattr(config.CONF, 'openstack_image_file_name')
46 GLANCE_IMAGE_PATH = os.path.join(getattr(
47 config.CONF, 'dir_functest_images'), GLANCE_IMAGE_FILENAME)
48 GLANCE_IMAGE_FORMAT = getattr(config.CONF, 'openstack_image_disk_format')
49 GLANCE_IMAGE_EXTRA_PROPERTIES = getattr(
50 config.CONF, 'openstack_extra_properties', {})
51 FLAVOR_NAME = getattr(config.CONF, 'rally_flavor_name')
52 FLAVOR_ALT_NAME = getattr(config.CONF, 'rally_flavor_alt_name')
55 FLAVOR_EXTRA_SPECS = getattr(config.CONF, 'flavor_extra_specs', {})
56 if FLAVOR_EXTRA_SPECS:
60 RALLY_DIR = pkg_resources.resource_filename(
61 'functest', 'opnfv_tests/openstack/rally')
62 RALLY_SCENARIO_DIR = pkg_resources.resource_filename(
63 'functest', 'opnfv_tests/openstack/rally/scenario')
64 TEMPLATE_DIR = pkg_resources.resource_filename(
65 'functest', 'opnfv_tests/openstack/rally/scenario/templates')
66 SUPPORT_DIR = pkg_resources.resource_filename(
67 'functest', 'opnfv_tests/openstack/rally/scenario/support')
70 ITERATIONS_AMOUNT = 10
72 RESULTS_DIR = os.path.join(getattr(config.CONF, 'dir_results'), 'rally')
73 BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
74 TEMP_DIR = os.path.join(RALLY_DIR, "var")
76 RALLY_PRIVATE_NET_NAME = getattr(config.CONF, 'rally_network_name')
77 RALLY_PRIVATE_SUBNET_NAME = str(getattr(config.CONF, 'rally_subnet_name'))
78 RALLY_PRIVATE_SUBNET_CIDR = getattr(config.CONF, 'rally_subnet_cidr')
79 RALLY_ROUTER_NAME = getattr(config.CONF, 'rally_router_name')
81 def __init__(self, **kwargs):
82 """Initialize RallyBase object."""
83 super(RallyBase, self).__init__(**kwargs)
84 self.cloud = os_client_config.make_shade()
85 self.guid = '-' + str(uuid.uuid4())
89 self.scenario_dir = ''
90 self.image_name = None
92 self.flavor_name = None
93 self.flavor_alt_name = None
96 self.start_time = None
102 self.flavor_alt = None
107 def _build_task_args(self, test_file_name):
108 """Build arguments for the Rally task."""
109 task_args = {'service_list': [test_file_name]}
110 task_args['image_name'] = str(self.image_name)
111 task_args['flavor_name'] = str(self.flavor_name)
112 task_args['flavor_alt_name'] = str(self.flavor_alt_name)
113 task_args['glance_image_location'] = str(self.GLANCE_IMAGE_PATH)
114 task_args['glance_image_format'] = str(self.GLANCE_IMAGE_FORMAT)
115 task_args['tmpl_dir'] = str(self.TEMPLATE_DIR)
116 task_args['sup_dir'] = str(self.SUPPORT_DIR)
117 task_args['users_amount'] = self.USERS_AMOUNT
118 task_args['tenants_amount'] = self.TENANTS_AMOUNT
119 task_args['use_existing_users'] = False
120 task_args['iterations'] = self.ITERATIONS_AMOUNT
121 task_args['concurrency'] = self.CONCURRENCY
122 task_args['smoke'] = self.smoke
125 task_args['floating_network'] = str(self.ext_net.name)
127 task_args['floating_network'] = ''
130 task_args['netid'] = str(self.network.id)
132 task_args['netid'] = ''
136 def _prepare_test_list(self, test_name):
137 """Build the list of test cases to be executed."""
138 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
139 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
142 if not os.path.exists(scenario_file_name):
143 scenario_file_name = os.path.join(self.scenario_dir,
146 if not os.path.exists(scenario_file_name):
147 raise Exception("The scenario '%s' does not exist."
148 % scenario_file_name)
150 LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
151 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
153 if not os.path.exists(self.TEMP_DIR):
154 os.makedirs(self.TEMP_DIR)
156 self._apply_blacklist(scenario_file_name, test_file_name)
157 return test_file_name
160 def get_task_id(cmd_raw):
162 Get task id from command rally result.
165 :return: task_id as string
167 taskid_re = re.compile('^Task +(.*): started$')
168 for line in cmd_raw.splitlines(True):
170 match = taskid_re.match(line)
172 return match.group(1)
176 def task_succeed(json_raw):
178 Parse JSON from rally JSON results.
183 rally_report = json.loads(json_raw)
184 tasks = rally_report.get('tasks')
187 if task.get('status') != 'finished' or \
188 task.get('pass_sla') is not True:
194 def _migration_supported(self):
195 """Determine if migration is supported."""
196 if self.compute_cnt > 1:
202 def get_cmd_output(proc):
203 """Get command stdout."""
205 for line in proc.stdout:
211 """Exclude scenario."""
214 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
215 black_list_yaml = yaml.safe_load(black_list_file)
217 installer_type = env.get('INSTALLER_TYPE')
218 deploy_scenario = env.get('DEPLOY_SCENARIO')
219 if (bool(installer_type) and bool(deploy_scenario) and
220 'scenario' in black_list_yaml.keys()):
221 for item in black_list_yaml['scenario']:
222 scenarios = item['scenarios']
223 installers = item['installers']
224 in_it = RallyBase.in_iterable_re
225 if (in_it(deploy_scenario, scenarios) and
226 in_it(installer_type, installers)):
227 tests = item['tests']
228 black_tests.extend(tests)
229 except Exception: # pylint: disable=broad-except
230 LOGGER.debug("Scenario exclusion not applied.")
235 def in_iterable_re(needle, haystack):
237 Check if given needle is in the iterable haystack, using regex.
239 :param needle: string to be matched
240 :param haystack: iterable of strings (optionally regex patterns)
241 :return: True if needle is eqial to any of the elements in haystack,
242 or if a nonempty regex pattern in haystack is found in needle.
244 # match without regex
245 if needle in haystack:
248 for pattern in haystack:
249 # match if regex pattern is set and found in the needle
250 if pattern and re.search(pattern, needle) is not None:
256 """Exclude functionalities."""
261 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
262 black_list_yaml = yaml.safe_load(black_list_file)
264 if not self._migration_supported():
265 func_list.append("no_migration")
267 if 'functionality' in black_list_yaml.keys():
268 for item in black_list_yaml['functionality']:
269 functions = item['functions']
270 for func in func_list:
271 if func in functions:
272 tests = item['tests']
273 black_tests.extend(tests)
274 except Exception: # pylint: disable=broad-except
275 LOGGER.debug("Functionality exclusion not applied.")
279 def _apply_blacklist(self, case_file_name, result_file_name):
280 """Apply blacklist."""
281 LOGGER.debug("Applying blacklist...")
282 cases_file = open(case_file_name, 'r')
283 result_file = open(result_file_name, 'w')
285 black_tests = list(set(self.excl_func() +
286 self.excl_scenario()))
289 LOGGER.debug("Blacklisted tests: %s", str(black_tests))
292 for cases_line in cases_file:
294 for black_tests_line in black_tests:
295 if re.search(black_tests_line,
296 cases_line.strip().rstrip(':')):
300 result_file.write(str(cases_line))
302 if cases_line.isspace():
309 def file_is_empty(file_name):
310 """Determine is a file is empty."""
312 if os.stat(file_name).st_size > 0:
314 except Exception: # pylint: disable=broad-except
319 def _save_results(self, test_name, task_id):
320 """ Generate and save task execution results"""
321 # check for result directory and create it otherwise
322 if not os.path.exists(self.RESULTS_DIR):
323 LOGGER.debug('%s does not exist, we create it.',
325 os.makedirs(self.RESULTS_DIR)
327 # put detailed result to log
328 cmd = (["rally", "task", "detailed", "--uuid", task_id])
329 LOGGER.debug('running command: %s', cmd)
330 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
331 stderr=subprocess.STDOUT)
332 json_detailed = self.get_cmd_output(proc)
333 LOGGER.info('%s', json_detailed)
335 # save report as JSON
336 cmd = (["rally", "task", "report", "--json", "--uuid", task_id])
337 LOGGER.debug('running command: %s', cmd)
338 with open(os.devnull, 'w') as devnull:
339 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
341 json_results = self.get_cmd_output(proc)
342 report_json_name = 'opnfv-{}.json'.format(test_name)
343 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
344 with open(report_json_dir, 'w') as r_file:
345 LOGGER.debug('saving json file')
346 r_file.write(json_results)
348 # save report as HTML
349 report_html_name = 'opnfv-{}.html'.format(test_name)
350 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
351 cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
352 "--out", report_html_dir])
353 LOGGER.debug('running command: %s', cmd)
354 with open(os.devnull, 'w') as devnull:
355 subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=devnull)
357 self._append_summary(json_results, test_name)
359 # parse JSON operation result
360 if self.task_succeed(json_results):
361 LOGGER.info('Test scenario: "%s" OK.', test_name)
363 LOGGER.info('Test scenario: "%s" Failed.', test_name)
365 def _run_task(self, test_name):
367 LOGGER.info('Starting test scenario "%s" ...', test_name)
369 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
370 if not os.path.exists(task_file):
371 LOGGER.error("Task file '%s' does not exist.", task_file)
372 raise Exception("Task file '{}' does not exist.".format(task_file))
374 file_name = self._prepare_test_list(test_name)
375 if self.file_is_empty(file_name):
376 LOGGER.info('No tests for scenario "%s"', test_name)
379 cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
380 task_file, "--task-args",
381 str(self._build_task_args(test_name))])
382 LOGGER.debug('running command: %s', cmd)
384 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
385 stderr=subprocess.STDOUT)
386 output = self.get_cmd_output(proc)
387 task_id = self.get_task_id(output)
389 LOGGER.debug('task_id : %s', task_id)
392 LOGGER.error('Failed to retrieve task_id, validating task...')
393 cmd = (["rally", "task", "validate", "--task", task_file,
394 "--task-args", str(self._build_task_args(test_name))])
395 LOGGER.debug('running command: %s', cmd)
396 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
397 stderr=subprocess.STDOUT)
398 output = self.get_cmd_output(proc)
399 LOGGER.error("Task validation result:" + "\n" + output)
400 raise Exception("Failed to retrieve task id")
402 self._save_results(test_name, task_id)
404 def _append_summary(self, json_raw, test_name):
405 """Update statistics summary info."""
408 overall_duration = 0.0
410 rally_report = json.loads(json_raw)
411 for task in rally_report.get('tasks'):
412 for subtask in task.get('subtasks'):
413 for workload in subtask.get('workloads'):
414 if workload.get('full_duration'):
415 overall_duration += workload.get('full_duration')
417 if workload.get('data'):
418 nb_tests += len(workload.get('data'))
420 for result in workload.get('data'):
421 if not result.get('error'):
424 scenario_summary = {'test_name': test_name,
425 'overall_duration': overall_duration,
426 'nb_tests': nb_tests,
427 'nb_success': nb_success,
428 'task_status': self.task_succeed(json_raw)}
429 self.summary.append(scenario_summary)
431 def _prepare_env(self):
432 """Create resources needed by test scenarios."""
434 LOGGER.debug('Validating the test name...')
435 if self.test_name not in self.TESTS:
436 raise Exception("Test name '%s' is invalid" % self.test_name)
438 network_name = self.RALLY_PRIVATE_NET_NAME + self.guid
439 subnet_name = self.RALLY_PRIVATE_SUBNET_NAME + self.guid
440 router_name = self.RALLY_ROUTER_NAME + self.guid
441 self.image_name = self.GLANCE_IMAGE_NAME + self.guid
442 self.flavor_name = self.FLAVOR_NAME + self.guid
443 self.flavor_alt_name = self.FLAVOR_ALT_NAME + self.guid
444 self.compute_cnt = len(self.cloud.list_hypervisors())
445 self.ext_net = functest_utils.get_external_network(self.cloud)
446 if self.ext_net is None:
447 raise Exception("No external network found")
449 LOGGER.debug("Creating image '%s'...", self.image_name)
450 self.image = self.cloud.create_image(
452 filename=self.GLANCE_IMAGE_PATH,
453 disk_format=self.GLANCE_IMAGE_FORMAT,
454 meta=self.GLANCE_IMAGE_EXTRA_PROPERTIES,
456 if self.image is None:
457 raise Exception("Failed to create image")
459 LOGGER.debug("Creating network '%s'...", network_name)
461 if hasattr(config.CONF, 'rally_network_type'):
462 provider["network_type"] = getattr(
463 config.CONF, 'rally_network_type')
464 if hasattr(config.CONF, 'rally_physical_network'):
465 provider["physical_network"] = getattr(
466 config.CONF, 'rally_physical_network')
467 if hasattr(config.CONF, 'rally_segmentation_id'):
468 provider["segmentation_id"] = getattr(
469 config.CONF, 'rally_segmentation_id')
471 self.network = self.cloud.create_network(
472 network_name, shared=True, provider=provider)
473 if self.network is None:
474 raise Exception("Failed to create private network")
476 self.subnet = self.cloud.create_subnet(
478 subnet_name=subnet_name,
479 cidr=self.RALLY_PRIVATE_SUBNET_CIDR,
481 dns_nameservers=[env.get('NAMESERVER')])
482 if self.subnet is None:
483 raise Exception("Failed to create private subnet")
485 LOGGER.debug("Creating router '%s'...", router_name)
486 self.router = self.cloud.create_router(
487 router_name, ext_gateway_net_id=self.ext_net.id)
488 if self.router is None:
489 raise Exception("Failed to create router")
490 self.cloud.add_router_interface(self.router, subnet_id=self.subnet.id)
492 LOGGER.debug("Creating flavor '%s'...", self.flavor_name)
493 self.flavor = self.cloud.create_flavor(
494 self.flavor_name, self.FLAVOR_RAM, 1, 1)
495 if self.flavor is None:
496 raise Exception("Failed to create flavor")
497 self.cloud.set_flavor_specs(
498 self.flavor.id, self.FLAVOR_EXTRA_SPECS)
500 LOGGER.debug("Creating flavor '%s'...", self.flavor_alt_name)
501 self.flavor_alt = self.cloud.create_flavor(
502 self.flavor_alt_name, self.FLAVOR_RAM_ALT, 1, 1)
503 if self.flavor_alt is None:
504 raise Exception("Failed to create flavor")
505 self.cloud.set_flavor_specs(
506 self.flavor_alt.id, self.FLAVOR_EXTRA_SPECS)
508 def _run_tests(self):
510 if self.test_name == 'all':
511 for test in self.TESTS:
512 if test == 'all' or test == 'vm':
516 self._run_task(self.test_name)
518 def _generate_report(self):
519 """Generate test execution summary report."""
526 res_table = prettytable.PrettyTable(
528 field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
529 res_table.align['Module'] = "l"
530 res_table.align['Duration'] = "r"
531 res_table.align['Success'] = "r"
533 # for each scenario we draw a row for the table
534 for item in self.summary:
535 if item['task_status'] is True:
537 total_duration += item['overall_duration']
538 total_nb_tests += item['nb_tests']
539 total_nb_success += item['nb_success']
541 success_avg = 100 * item['nb_success'] / item['nb_tests']
542 except ZeroDivisionError:
544 success_str = str("{:0.2f}".format(success_avg)) + '%'
545 duration_str = time.strftime("%M:%S",
546 time.gmtime(item['overall_duration']))
547 res_table.add_row([item['test_name'], duration_str,
548 item['nb_tests'], success_str])
549 payload.append({'module': item['test_name'],
550 'details': {'duration': item['overall_duration'],
551 'nb tests': item['nb_tests'],
552 'success': success_str}})
554 total_duration_str = time.strftime("%H:%M:%S",
555 time.gmtime(total_duration))
557 self.result = 100 * total_nb_success / total_nb_tests
558 except ZeroDivisionError:
560 success_rate = "{:0.2f}".format(self.result)
561 success_rate_str = str(success_rate) + '%'
562 res_table.add_row(["", "", "", ""])
563 res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
566 LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
567 LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
568 self.case_name, success_rate, nb_modules,
570 payload.append({'summary': {'duration': total_duration,
571 'nb tests': total_nb_tests,
572 'nb success': success_rate}})
573 self.details = payload
576 """Cleanup of OpenStack resources. Should be called on completion."""
578 self.cloud.delete_flavor(self.flavor_alt.id)
580 self.cloud.delete_flavor(self.flavor.id)
581 if self.router and self.subnet:
582 self.cloud.remove_router_interface(self.router, self.subnet.id)
584 self.cloud.delete_router(self.router.id)
586 self.cloud.delete_subnet(self.subnet.id)
588 self.cloud.delete_network(self.network.id)
590 self.cloud.delete_image(self.image.id)
592 def is_successful(self):
593 """The overall result of the test."""
594 for item in self.summary:
595 if item['task_status'] is False:
596 return testcase.TestCase.EX_TESTCASE_FAILED
598 return super(RallyBase, self).is_successful()
600 @energy.enable_recording
601 def run(self, **kwargs):
603 self.start_time = time.time()
605 conf_utils.create_rally_deployment()
608 self._generate_report()
609 res = testcase.TestCase.EX_OK
610 except Exception as exc: # pylint: disable=broad-except
611 LOGGER.error('Error with run: %s', exc)
612 res = testcase.TestCase.EX_RUN_ERROR
616 self.stop_time = time.time()
620 class RallySanity(RallyBase):
621 """Rally sanity testcase implementation."""
623 def __init__(self, **kwargs):
624 """Initialize RallySanity object."""
625 if "case_name" not in kwargs:
626 kwargs["case_name"] = "rally_sanity"
627 super(RallySanity, self).__init__(**kwargs)
629 self.test_name = 'all'
631 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
634 class RallyFull(RallyBase):
635 """Rally full testcase implementation."""
637 def __init__(self, **kwargs):
638 """Initialize RallyFull object."""
639 if "case_name" not in kwargs:
640 kwargs["case_name"] = "rally_full"
641 super(RallyFull, self).__init__(**kwargs)
643 self.test_name = 'all'
645 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')