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, 'image_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 for report in rally_report:
185 if report is None or report.get('result') is None:
188 for result in report.get('result'):
189 if result is None or result.get('error'):
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: " + 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 _run_task(self, test_name):
321 LOGGER.info('Starting test scenario "%s" ...', test_name)
323 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
324 if not os.path.exists(task_file):
325 LOGGER.error("Task file '%s' does not exist.", task_file)
326 raise Exception("Task file '%s' does not exist.", task_file)
328 file_name = self._prepare_test_list(test_name)
329 if self.file_is_empty(file_name):
330 LOGGER.info('No tests for scenario "%s"', test_name)
333 cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
334 task_file, "--task-args",
335 str(self._build_task_args(test_name))])
336 LOGGER.debug('running command: %s', cmd)
338 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
339 stderr=subprocess.STDOUT)
340 output = self.get_cmd_output(proc)
341 task_id = self.get_task_id(output)
343 LOGGER.debug('task_id : %s', task_id)
346 LOGGER.error('Failed to retrieve task_id, validating task...')
347 cmd = (["rally", "task", "validate", "--task", task_file,
348 "--task-args", str(self._build_task_args(test_name))])
349 LOGGER.debug('running command: %s', cmd)
350 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
351 stderr=subprocess.STDOUT)
352 output = self.get_cmd_output(proc)
353 LOGGER.error("Task validation result:" + "\n" + output)
356 # check for result directory and create it otherwise
357 if not os.path.exists(self.RESULTS_DIR):
358 LOGGER.debug('%s does not exist, we create it.',
360 os.makedirs(self.RESULTS_DIR)
362 # get and save rally operation JSON result
363 cmd = (["rally", "task", "detailed", task_id])
364 LOGGER.debug('running command: %s', cmd)
365 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
366 stderr=subprocess.STDOUT)
367 json_detailed = self.get_cmd_output(proc)
368 LOGGER.info('%s', json_detailed)
370 cmd = (["rally", "task", "results", task_id])
371 LOGGER.debug('running command: %s', cmd)
372 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
373 stderr=subprocess.STDOUT)
374 json_results = self.get_cmd_output(proc)
375 self._append_summary(json_results, test_name)
376 report_json_name = 'opnfv-{}.json'.format(test_name)
377 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
378 with open(report_json_dir, 'w') as r_file:
379 LOGGER.debug('saving json file')
380 r_file.write(json_results)
382 # write html report file
383 report_html_name = 'opnfv-{}.html'.format(test_name)
384 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
385 cmd = (["rally", "task", "report", task_id, "--out", report_html_dir])
386 LOGGER.debug('running command: %s', cmd)
387 subprocess.Popen(cmd, stdout=subprocess.PIPE,
388 stderr=subprocess.STDOUT)
390 # parse JSON operation result
391 if self.task_succeed(json_results):
392 LOGGER.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
394 LOGGER.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
396 def _append_summary(self, json_raw, test_name):
397 """Update statistics summary info."""
400 overall_duration = 0.0
402 rally_report = json.loads(json_raw)
403 for report in rally_report:
404 if report.get('full_duration'):
405 overall_duration += report.get('full_duration')
407 if report.get('result'):
408 for result in report.get('result'):
410 if not result.get('error'):
413 scenario_summary = {'test_name': test_name,
414 'overall_duration': overall_duration,
415 'nb_tests': nb_tests,
416 'nb_success': nb_success}
417 self.summary.append(scenario_summary)
419 def _prepare_env(self):
420 """Create resources needed by test scenarios."""
422 LOGGER.debug('Validating the test name...')
423 if self.test_name not in self.TESTS:
424 raise Exception("Test name '%s' is invalid" % self.test_name)
426 network_name = self.RALLY_PRIVATE_NET_NAME + self.guid
427 subnet_name = self.RALLY_PRIVATE_SUBNET_NAME + self.guid
428 router_name = self.RALLY_ROUTER_NAME + self.guid
429 self.image_name = self.GLANCE_IMAGE_NAME + self.guid
430 self.flavor_name = self.FLAVOR_NAME + self.guid
431 self.flavor_alt_name = self.FLAVOR_ALT_NAME + self.guid
432 self.compute_cnt = len(self.cloud.list_hypervisors())
433 self.ext_net = functest_utils.get_external_network(self.cloud)
434 if self.ext_net is None:
435 raise Exception("No external network found")
437 LOGGER.debug("Creating image '%s'...", self.image_name)
438 self.image = self.cloud.create_image(
440 filename=self.GLANCE_IMAGE_PATH,
441 disk_format=self.GLANCE_IMAGE_FORMAT,
442 meta=self.GLANCE_IMAGE_EXTRA_PROPERTIES,
444 if self.image is None:
445 raise Exception("Failed to create image")
447 LOGGER.debug("Creating network '%s'...", network_name)
449 if hasattr(config.CONF, 'rally_network_type'):
450 provider["network_type"] = getattr(
451 config.CONF, 'rally_network_type')
452 if hasattr(config.CONF, 'rally_physical_network'):
453 provider["physical_network"] = getattr(
454 config.CONF, 'rally_physical_network')
455 if hasattr(config.CONF, 'rally_segmentation_id'):
456 provider["segmentation_id"] = getattr(
457 config.CONF, 'rally_segmentation_id')
459 self.network = self.cloud.create_network(
460 network_name, shared=True, provider=provider)
461 if self.network is None:
462 raise Exception("Failed to create private network")
464 self.subnet = self.cloud.create_subnet(
466 subnet_name=subnet_name,
467 cidr=self.RALLY_PRIVATE_SUBNET_CIDR,
469 dns_nameservers=[env.get('NAMESERVER')])
470 if self.subnet is None:
471 raise Exception("Failed to create private subnet")
473 LOGGER.debug("Creating router '%s'...", router_name)
474 self.router = self.cloud.create_router(
475 router_name, ext_gateway_net_id=self.ext_net.id)
476 if self.router is None:
477 raise Exception("Failed to create router")
478 self.cloud.add_router_interface(self.router, subnet_id=self.subnet.id)
480 LOGGER.debug("Creating flavor '%s'...", self.flavor_name)
481 self.flavor = self.cloud.create_flavor(
482 self.flavor_name, self.FLAVOR_RAM, 1, 1)
483 if self.flavor is None:
484 raise Exception("Failed to create flavor")
485 self.cloud.set_flavor_specs(
486 self.flavor.id, self.FLAVOR_EXTRA_SPECS)
488 LOGGER.debug("Creating flavor '%s'...", self.flavor_alt_name)
489 self.flavor_alt = self.cloud.create_flavor(
490 self.flavor_alt_name, self.FLAVOR_RAM_ALT, 1, 1)
491 if self.flavor_alt is None:
492 raise Exception("Failed to create flavor")
493 self.cloud.set_flavor_specs(
494 self.flavor_alt.id, self.FLAVOR_EXTRA_SPECS)
496 def _run_tests(self):
498 if self.test_name == 'all':
499 for test in self.TESTS:
500 if test == 'all' or test == 'vm':
504 self._run_task(self.test_name)
506 def _generate_report(self):
507 """Generate test execution summary report."""
513 res_table = prettytable.PrettyTable(
515 field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
516 res_table.align['Module'] = "l"
517 res_table.align['Duration'] = "r"
518 res_table.align['Success'] = "r"
520 # for each scenario we draw a row for the table
521 for item in self.summary:
522 total_duration += item['overall_duration']
523 total_nb_tests += item['nb_tests']
524 total_nb_success += item['nb_success']
526 success_avg = 100 * item['nb_success'] / item['nb_tests']
527 except ZeroDivisionError:
529 success_str = str("{:0.2f}".format(success_avg)) + '%'
530 duration_str = time.strftime("%M:%S",
531 time.gmtime(item['overall_duration']))
532 res_table.add_row([item['test_name'], duration_str,
533 item['nb_tests'], success_str])
534 payload.append({'module': item['test_name'],
535 'details': {'duration': item['overall_duration'],
536 'nb tests': item['nb_tests'],
537 'success': success_str}})
539 total_duration_str = time.strftime("%H:%M:%S",
540 time.gmtime(total_duration))
542 self.result = 100 * total_nb_success / total_nb_tests
543 except ZeroDivisionError:
545 success_rate = "{:0.2f}".format(self.result)
546 success_rate_str = str(success_rate) + '%'
547 res_table.add_row(["", "", "", ""])
548 res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
551 LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
552 LOGGER.info("Rally '%s' success_rate is %s%%",
553 self.case_name, success_rate)
554 payload.append({'summary': {'duration': total_duration,
555 'nb tests': total_nb_tests,
556 'nb success': success_rate}})
557 self.details = payload
560 """Cleanup of OpenStack resources. Should be called on completion."""
562 self.cloud.delete_flavor(self.flavor_alt.id)
564 self.cloud.delete_flavor(self.flavor.id)
565 if self.router and self.subnet:
566 self.cloud.remove_router_interface(self.router, self.subnet.id)
568 self.cloud.delete_router(self.router.id)
570 self.cloud.delete_subnet(self.subnet.id)
572 self.cloud.delete_network(self.network.id)
574 self.cloud.delete_image(self.image.id)
576 @energy.enable_recording
577 def run(self, **kwargs):
579 self.start_time = time.time()
581 conf_utils.create_rally_deployment()
584 self._generate_report()
585 res = testcase.TestCase.EX_OK
586 except Exception as exc: # pylint: disable=broad-except
587 LOGGER.error('Error with run: %s', exc)
588 res = testcase.TestCase.EX_RUN_ERROR
592 self.stop_time = time.time()
596 class RallySanity(RallyBase):
597 """Rally sanity testcase implementation."""
599 def __init__(self, **kwargs):
600 """Initialize RallySanity object."""
601 if "case_name" not in kwargs:
602 kwargs["case_name"] = "rally_sanity"
603 super(RallySanity, self).__init__(**kwargs)
605 self.test_name = 'all'
607 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
610 class RallyFull(RallyBase):
611 """Rally full testcase implementation."""
613 def __init__(self, **kwargs):
614 """Initialize RallyFull object."""
615 if "case_name" not in kwargs:
616 kwargs["case_name"] = "rally_full"
617 super(RallyFull, self).__init__(**kwargs)
619 self.test_name = 'all'
621 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')