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
24 from xtesting.core import testcase
25 from xtesting.energy import energy
28 from functest.core import singlevm
29 from functest.opnfv_tests.openstack.tempest import conf_utils
30 from functest.utils import config
31 from functest.utils import env
33 LOGGER = logging.getLogger(__name__)
36 class RallyBase(singlevm.VmReady1):
37 """Base class form Rally testcases implementation."""
39 # pylint: disable=too-many-instance-attributes
40 TESTS = ['authenticate', 'glance', 'cinder', 'gnocchi', 'heat',
41 'keystone', 'neutron', 'nova', 'quotas', 'vm', 'all']
43 RALLY_DIR = pkg_resources.resource_filename(
44 'functest', 'opnfv_tests/openstack/rally')
45 RALLY_SCENARIO_DIR = pkg_resources.resource_filename(
46 'functest', 'opnfv_tests/openstack/rally/scenario')
47 TEMPLATE_DIR = pkg_resources.resource_filename(
48 'functest', 'opnfv_tests/openstack/rally/scenario/templates')
49 SUPPORT_DIR = pkg_resources.resource_filename(
50 'functest', 'opnfv_tests/openstack/rally/scenario/support')
53 ITERATIONS_AMOUNT = 10
55 RESULTS_DIR = os.path.join(getattr(config.CONF, 'dir_results'), 'rally')
56 BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
57 TEMP_DIR = os.path.join(RALLY_DIR, "var")
62 def __init__(self, **kwargs):
63 """Initialize RallyBase object."""
64 super(RallyBase, self).__init__(**kwargs)
68 self.scenario_dir = ''
71 self.start_time = None
75 self.flavor_alt = None
77 def _build_task_args(self, test_file_name):
78 """Build arguments for the Rally task."""
79 task_args = {'service_list': [test_file_name]}
80 task_args['image_name'] = str(self.image.name)
81 task_args['flavor_name'] = str(self.flavor.name)
82 task_args['flavor_alt_name'] = str(self.flavor_alt.name)
83 task_args['glance_image_location'] = str(self.filename)
84 task_args['glance_image_format'] = str(self.image_format)
85 task_args['tmpl_dir'] = str(self.TEMPLATE_DIR)
86 task_args['sup_dir'] = str(self.SUPPORT_DIR)
87 task_args['users_amount'] = self.USERS_AMOUNT
88 task_args['tenants_amount'] = self.TENANTS_AMOUNT
89 task_args['use_existing_users'] = False
90 task_args['iterations'] = self.ITERATIONS_AMOUNT
91 task_args['concurrency'] = self.CONCURRENCY
92 task_args['smoke'] = self.smoke
95 task_args['floating_network'] = str(self.ext_net.name)
97 task_args['floating_network'] = ''
100 task_args['netid'] = str(self.network.id)
102 task_args['netid'] = ''
106 def _prepare_test_list(self, test_name):
107 """Build the list of test cases to be executed."""
108 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
109 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
112 if not os.path.exists(scenario_file_name):
113 scenario_file_name = os.path.join(self.scenario_dir,
116 if not os.path.exists(scenario_file_name):
117 raise Exception("The scenario '%s' does not exist."
118 % scenario_file_name)
120 LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
121 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
123 if not os.path.exists(self.TEMP_DIR):
124 os.makedirs(self.TEMP_DIR)
126 self._apply_blacklist(scenario_file_name, test_file_name)
127 return test_file_name
130 def get_task_id(cmd_raw):
132 Get task id from command rally result.
135 :return: task_id as string
137 taskid_re = re.compile('^Task +(.*): started$')
138 for line in cmd_raw.splitlines(True):
140 match = taskid_re.match(line)
142 return match.group(1)
146 def task_succeed(json_raw):
148 Parse JSON from rally JSON results.
153 rally_report = json.loads(json_raw)
154 tasks = rally_report.get('tasks')
157 if task.get('status') != 'finished' or \
158 task.get('pass_sla') is not True:
164 def _migration_supported(self):
165 """Determine if migration is supported."""
166 if self.compute_cnt > 1:
172 def get_cmd_output(proc):
173 """Get command stdout."""
175 for line in proc.stdout:
181 """Exclude scenario."""
184 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
185 black_list_yaml = yaml.safe_load(black_list_file)
187 installer_type = env.get('INSTALLER_TYPE')
188 deploy_scenario = env.get('DEPLOY_SCENARIO')
189 if (bool(installer_type) and bool(deploy_scenario) and
190 'scenario' in black_list_yaml.keys()):
191 for item in black_list_yaml['scenario']:
192 scenarios = item['scenarios']
193 installers = item['installers']
194 in_it = RallyBase.in_iterable_re
195 if (in_it(deploy_scenario, scenarios) and
196 in_it(installer_type, installers)):
197 tests = item['tests']
198 black_tests.extend(tests)
199 except Exception: # pylint: disable=broad-except
200 LOGGER.debug("Scenario exclusion not applied.")
205 def in_iterable_re(needle, haystack):
207 Check if given needle is in the iterable haystack, using regex.
209 :param needle: string to be matched
210 :param haystack: iterable of strings (optionally regex patterns)
211 :return: True if needle is eqial to any of the elements in haystack,
212 or if a nonempty regex pattern in haystack is found in needle.
214 # match without regex
215 if needle in haystack:
218 for pattern in haystack:
219 # match if regex pattern is set and found in the needle
220 if pattern and re.search(pattern, needle) is not None:
226 """Exclude functionalities."""
231 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
232 black_list_yaml = yaml.safe_load(black_list_file)
234 if not self._migration_supported():
235 func_list.append("no_migration")
237 if 'functionality' in black_list_yaml.keys():
238 for item in black_list_yaml['functionality']:
239 functions = item['functions']
240 for func in func_list:
241 if func in functions:
242 tests = item['tests']
243 black_tests.extend(tests)
244 except Exception: # pylint: disable=broad-except
245 LOGGER.debug("Functionality exclusion not applied.")
249 def _apply_blacklist(self, case_file_name, result_file_name):
250 """Apply blacklist."""
251 LOGGER.debug("Applying blacklist...")
252 cases_file = open(case_file_name, 'r')
253 result_file = open(result_file_name, 'w')
255 black_tests = list(set(self.excl_func() +
256 self.excl_scenario()))
259 LOGGER.debug("Blacklisted tests: %s", str(black_tests))
262 for cases_line in cases_file:
264 for black_tests_line in black_tests:
265 if re.search(black_tests_line,
266 cases_line.strip().rstrip(':')):
270 result_file.write(str(cases_line))
272 if cases_line.isspace():
279 def file_is_empty(file_name):
280 """Determine is a file is empty."""
282 if os.stat(file_name).st_size > 0:
284 except Exception: # pylint: disable=broad-except
289 def _save_results(self, test_name, task_id):
290 """ Generate and save task execution results"""
291 # check for result directory and create it otherwise
292 if not os.path.exists(self.RESULTS_DIR):
293 LOGGER.debug('%s does not exist, we create it.',
295 os.makedirs(self.RESULTS_DIR)
297 # put detailed result to log
298 cmd = (["rally", "task", "detailed", "--uuid", task_id])
299 LOGGER.debug('running command: %s', cmd)
300 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
301 LOGGER.info("%s\n%s", " ".join(cmd), output)
303 # save report as JSON
304 report_json_name = 'opnfv-{}.json'.format(test_name)
305 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
306 cmd = (["rally", "task", "report", "--json", "--uuid", task_id,
307 "--out", report_json_dir])
308 LOGGER.debug('running command: %s', cmd)
309 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
310 LOGGER.info("%s\n%s", " ".join(cmd), output)
312 # save report as HTML
313 report_html_name = 'opnfv-{}.html'.format(test_name)
314 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
315 cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
316 "--out", report_html_dir])
317 LOGGER.debug('running command: %s', cmd)
318 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
319 LOGGER.info("%s\n%s", " ".join(cmd), output)
321 json_results = open(report_json_dir).read()
322 self._append_summary(json_results, test_name)
324 # parse JSON operation result
325 if self.task_succeed(json_results):
326 LOGGER.info('Test scenario: "%s" OK.', test_name)
328 LOGGER.info('Test scenario: "%s" Failed.', test_name)
330 def _run_task(self, test_name):
332 LOGGER.info('Starting test scenario "%s" ...', test_name)
334 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
335 if not os.path.exists(task_file):
336 LOGGER.error("Task file '%s' does not exist.", task_file)
337 raise Exception("Task file '{}' does not exist.".format(task_file))
339 file_name = self._prepare_test_list(test_name)
340 if self.file_is_empty(file_name):
341 LOGGER.info('No tests for scenario "%s"', test_name)
344 cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
345 task_file, "--task-args",
346 str(self._build_task_args(test_name))])
347 LOGGER.debug('running command: %s', cmd)
349 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
350 stderr=subprocess.STDOUT)
351 output = self.get_cmd_output(proc)
352 task_id = self.get_task_id(output)
354 LOGGER.debug('task_id : %s', task_id)
357 LOGGER.error('Failed to retrieve task_id, validating task...')
358 cmd = (["rally", "task", "validate", "--task", task_file,
359 "--task-args", str(self._build_task_args(test_name))])
360 LOGGER.debug('running command: %s', cmd)
361 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
362 stderr=subprocess.STDOUT)
363 output = self.get_cmd_output(proc)
364 LOGGER.error("Task validation result:" + "\n" + output)
365 raise Exception("Failed to retrieve task id")
367 self._save_results(test_name, task_id)
369 def _append_summary(self, json_raw, test_name):
370 """Update statistics summary info."""
373 overall_duration = 0.0
375 rally_report = json.loads(json_raw)
376 for task in rally_report.get('tasks'):
377 for subtask in task.get('subtasks'):
378 for workload in subtask.get('workloads'):
379 if workload.get('full_duration'):
380 overall_duration += workload.get('full_duration')
382 if workload.get('data'):
383 nb_tests += len(workload.get('data'))
385 for result in workload.get('data'):
386 if not result.get('error'):
389 scenario_summary = {'test_name': test_name,
390 'overall_duration': overall_duration,
391 'nb_tests': nb_tests,
392 'nb_success': nb_success,
393 'task_status': self.task_succeed(json_raw)}
394 self.summary.append(scenario_summary)
396 def _prepare_env(self):
397 """Create resources needed by test scenarios."""
399 LOGGER.debug('Validating the test name...')
400 if self.test_name not in self.TESTS:
401 raise Exception("Test name '%s' is invalid" % self.test_name)
403 self.compute_cnt = len(self.cloud.list_hypervisors())
404 self.flavor_alt = self.create_flavor_alt()
405 LOGGER.debug("flavor: %s", self.flavor_alt)
407 def _run_tests(self):
409 if self.test_name == 'all':
410 for test in self.TESTS:
411 if test == 'all' or test == 'vm':
415 self._run_task(self.test_name)
417 def _generate_report(self):
418 """Generate test execution summary report."""
425 res_table = prettytable.PrettyTable(
427 field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
428 res_table.align['Module'] = "l"
429 res_table.align['Duration'] = "r"
430 res_table.align['Success'] = "r"
432 # for each scenario we draw a row for the table
433 for item in self.summary:
434 if item['task_status'] is True:
436 total_duration += item['overall_duration']
437 total_nb_tests += item['nb_tests']
438 total_nb_success += item['nb_success']
440 success_avg = 100 * item['nb_success'] / item['nb_tests']
441 except ZeroDivisionError:
443 success_str = str("{:0.2f}".format(success_avg)) + '%'
444 duration_str = time.strftime("%M:%S",
445 time.gmtime(item['overall_duration']))
446 res_table.add_row([item['test_name'], duration_str,
447 item['nb_tests'], success_str])
448 payload.append({'module': item['test_name'],
449 'details': {'duration': item['overall_duration'],
450 'nb tests': item['nb_tests'],
451 'success': success_str}})
453 total_duration_str = time.strftime("%H:%M:%S",
454 time.gmtime(total_duration))
456 self.result = 100 * total_nb_success / total_nb_tests
457 except ZeroDivisionError:
459 success_rate = "{:0.2f}".format(self.result)
460 success_rate_str = str(success_rate) + '%'
461 res_table.add_row(["", "", "", ""])
462 res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
465 LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
466 LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
467 self.case_name, success_rate, nb_modules,
469 payload.append({'summary': {'duration': total_duration,
470 'nb tests': total_nb_tests,
471 'nb success': success_rate}})
472 self.details = payload
475 """Cleanup of OpenStack resources. Should be called on completion."""
476 super(RallyBase, self).clean()
478 self.orig_cloud.delete_flavor(self.flavor_alt.id)
480 def is_successful(self):
481 """The overall result of the test."""
482 for item in self.summary:
483 if item['task_status'] is False:
484 return testcase.TestCase.EX_TESTCASE_FAILED
486 return super(RallyBase, self).is_successful()
488 @energy.enable_recording
489 def run(self, **kwargs):
491 self.start_time = time.time()
493 assert super(RallyBase, self).run(
494 **kwargs) == testcase.TestCase.EX_OK
495 conf_utils.create_rally_deployment()
498 self._generate_report()
499 res = testcase.TestCase.EX_OK
500 except Exception as exc: # pylint: disable=broad-except
501 LOGGER.error('Error with run: %s', exc)
503 res = testcase.TestCase.EX_RUN_ERROR
504 self.stop_time = time.time()
508 class RallySanity(RallyBase):
509 """Rally sanity testcase implementation."""
511 def __init__(self, **kwargs):
512 """Initialize RallySanity object."""
513 if "case_name" not in kwargs:
514 kwargs["case_name"] = "rally_sanity"
515 super(RallySanity, self).__init__(**kwargs)
517 self.test_name = 'all'
519 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
522 class RallyFull(RallyBase):
523 """Rally full testcase implementation."""
525 def __init__(self, **kwargs):
526 """Initialize RallyFull object."""
527 if "case_name" not in kwargs:
528 kwargs["case_name"] = "rally_full"
529 super(RallyFull, self).__init__(**kwargs)
531 self.test_name = 'all'
533 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')