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.VmReady2):
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)
65 assert self.orig_cloud
67 if self.orig_cloud.get_role("admin"):
69 elif self.orig_cloud.get_role("Admin"):
72 raise Exception("Cannot detect neither admin nor Admin")
73 self.orig_cloud.grant_role(
74 role_name, user=self.project.user.id,
75 project=self.project.project.id,
76 domain=self.project.domain.id)
80 self.scenario_dir = ''
83 self.start_time = None
87 self.flavor_alt = None
89 def _build_task_args(self, test_file_name):
90 """Build arguments for the Rally task."""
91 task_args = {'service_list': [test_file_name]}
92 task_args['image_name'] = str(self.image.name)
93 task_args['flavor_name'] = str(self.flavor.name)
94 task_args['flavor_alt_name'] = str(self.flavor_alt.name)
95 task_args['glance_image_location'] = str(self.filename)
96 task_args['glance_image_format'] = str(self.image_format)
97 task_args['tmpl_dir'] = str(self.TEMPLATE_DIR)
98 task_args['sup_dir'] = str(self.SUPPORT_DIR)
99 task_args['users_amount'] = self.USERS_AMOUNT
100 task_args['tenants_amount'] = self.TENANTS_AMOUNT
101 task_args['use_existing_users'] = False
102 task_args['iterations'] = self.ITERATIONS_AMOUNT
103 task_args['concurrency'] = self.CONCURRENCY
104 task_args['smoke'] = self.smoke
107 task_args['floating_network'] = str(self.ext_net.name)
109 task_args['floating_network'] = ''
112 task_args['netid'] = str(self.network.id)
114 task_args['netid'] = ''
118 def _prepare_test_list(self, test_name):
119 """Build the list of test cases to be executed."""
120 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
121 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
124 if not os.path.exists(scenario_file_name):
125 scenario_file_name = os.path.join(self.scenario_dir,
128 if not os.path.exists(scenario_file_name):
129 raise Exception("The scenario '%s' does not exist."
130 % scenario_file_name)
132 LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
133 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
135 if not os.path.exists(self.TEMP_DIR):
136 os.makedirs(self.TEMP_DIR)
138 self._apply_blacklist(scenario_file_name, test_file_name)
139 return test_file_name
142 def get_task_id(cmd_raw):
144 Get task id from command rally result.
147 :return: task_id as string
149 taskid_re = re.compile('^Task +(.*): started$')
150 for line in cmd_raw.splitlines(True):
152 match = taskid_re.match(line)
154 return match.group(1)
158 def task_succeed(json_raw):
160 Parse JSON from rally JSON results.
165 rally_report = json.loads(json_raw)
166 tasks = rally_report.get('tasks')
169 if task.get('status') != 'finished' or \
170 task.get('pass_sla') is not True:
176 def _migration_supported(self):
177 """Determine if migration is supported."""
178 if self.compute_cnt > 1:
185 """Exclude scenario."""
188 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
189 black_list_yaml = yaml.safe_load(black_list_file)
191 installer_type = env.get('INSTALLER_TYPE')
192 deploy_scenario = env.get('DEPLOY_SCENARIO')
193 if (bool(installer_type) and bool(deploy_scenario) and
194 'scenario' in black_list_yaml.keys()):
195 for item in black_list_yaml['scenario']:
196 scenarios = item['scenarios']
197 installers = item['installers']
198 in_it = RallyBase.in_iterable_re
199 if (in_it(deploy_scenario, scenarios) and
200 in_it(installer_type, installers)):
201 tests = item['tests']
202 black_tests.extend(tests)
203 except Exception: # pylint: disable=broad-except
204 LOGGER.debug("Scenario exclusion not applied.")
209 def in_iterable_re(needle, haystack):
211 Check if given needle is in the iterable haystack, using regex.
213 :param needle: string to be matched
214 :param haystack: iterable of strings (optionally regex patterns)
215 :return: True if needle is eqial to any of the elements in haystack,
216 or if a nonempty regex pattern in haystack is found in needle.
218 # match without regex
219 if needle in haystack:
222 for pattern in haystack:
223 # match if regex pattern is set and found in the needle
224 if pattern and re.search(pattern, needle) is not None:
230 """Exclude functionalities."""
235 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
236 black_list_yaml = yaml.safe_load(black_list_file)
238 if not self._migration_supported():
239 func_list.append("no_migration")
241 if 'functionality' in black_list_yaml.keys():
242 for item in black_list_yaml['functionality']:
243 functions = item['functions']
244 for func in func_list:
245 if func in functions:
246 tests = item['tests']
247 black_tests.extend(tests)
248 except Exception: # pylint: disable=broad-except
249 LOGGER.debug("Functionality exclusion not applied.")
253 def _apply_blacklist(self, case_file_name, result_file_name):
254 """Apply blacklist."""
255 LOGGER.debug("Applying blacklist...")
256 cases_file = open(case_file_name, 'r')
257 result_file = open(result_file_name, 'w')
259 black_tests = list(set(self.excl_func() +
260 self.excl_scenario()))
263 LOGGER.debug("Blacklisted tests: %s", str(black_tests))
266 for cases_line in cases_file:
268 for black_tests_line in black_tests:
269 if re.search(black_tests_line,
270 cases_line.strip().rstrip(':')):
274 result_file.write(str(cases_line))
276 if cases_line.isspace():
283 def file_is_empty(file_name):
284 """Determine is a file is empty."""
286 if os.stat(file_name).st_size > 0:
288 except Exception: # pylint: disable=broad-except
293 def _save_results(self, test_name, task_id):
294 """ Generate and save task execution results"""
295 # check for result directory and create it otherwise
296 if not os.path.exists(self.RESULTS_DIR):
297 LOGGER.debug('%s does not exist, we create it.',
299 os.makedirs(self.RESULTS_DIR)
301 # put detailed result to log
302 cmd = (["rally", "task", "detailed", "--uuid", task_id])
303 LOGGER.debug('running command: %s', cmd)
304 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
305 LOGGER.info("%s\n%s", " ".join(cmd), output)
307 # save report as JSON
308 report_json_name = 'opnfv-{}.json'.format(test_name)
309 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
310 cmd = (["rally", "task", "report", "--json", "--uuid", task_id,
311 "--out", report_json_dir])
312 LOGGER.debug('running command: %s', cmd)
313 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
314 LOGGER.info("%s\n%s", " ".join(cmd), output)
316 # save report as HTML
317 report_html_name = 'opnfv-{}.html'.format(test_name)
318 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
319 cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
320 "--out", report_html_dir])
321 LOGGER.debug('running command: %s', cmd)
322 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
323 LOGGER.info("%s\n%s", " ".join(cmd), output)
325 json_results = open(report_json_dir).read()
326 self._append_summary(json_results, test_name)
328 # parse JSON operation result
329 if self.task_succeed(json_results):
330 LOGGER.info('Test scenario: "%s" OK.', test_name)
332 LOGGER.info('Test scenario: "%s" Failed.', test_name)
334 def _run_task(self, test_name):
336 LOGGER.info('Starting test scenario "%s" ...', test_name)
338 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
339 if not os.path.exists(task_file):
340 LOGGER.error("Task file '%s' does not exist.", task_file)
341 raise Exception("Task file '{}' does not exist.".format(task_file))
343 file_name = self._prepare_test_list(test_name)
344 if self.file_is_empty(file_name):
345 LOGGER.info('No tests for scenario "%s"', test_name)
348 cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
349 task_file, "--task-args",
350 str(self._build_task_args(test_name))])
351 LOGGER.debug('running command: %s', cmd)
352 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
353 stderr=subprocess.STDOUT)
354 output = proc.communicate()[0]
356 task_id = self.get_task_id(output)
357 LOGGER.debug('task_id : %s', task_id)
359 LOGGER.error("Failed to retrieve task_id")
360 LOGGER.error("Result:\n%s", output)
361 raise Exception("Failed to retrieve task id")
363 self._save_results(test_name, task_id)
365 def _append_summary(self, json_raw, test_name):
366 """Update statistics summary info."""
369 overall_duration = 0.0
371 rally_report = json.loads(json_raw)
372 for task in rally_report.get('tasks'):
373 for subtask in task.get('subtasks'):
374 for workload in subtask.get('workloads'):
375 if workload.get('full_duration'):
376 overall_duration += workload.get('full_duration')
378 if workload.get('data'):
379 nb_tests += len(workload.get('data'))
381 for result in workload.get('data'):
382 if not result.get('error'):
385 scenario_summary = {'test_name': test_name,
386 'overall_duration': overall_duration,
387 'nb_tests': nb_tests,
388 'nb_success': nb_success,
389 'task_status': self.task_succeed(json_raw)}
390 self.summary.append(scenario_summary)
392 def _prepare_env(self):
393 """Create resources needed by test scenarios."""
395 LOGGER.debug('Validating the test name...')
396 if self.test_name not in self.TESTS:
397 raise Exception("Test name '%s' is invalid" % self.test_name)
399 self.compute_cnt = len(self.cloud.list_hypervisors())
400 self.flavor_alt = self.create_flavor_alt()
401 LOGGER.debug("flavor: %s", self.flavor_alt)
403 def _run_tests(self):
405 if self.test_name == 'all':
406 for test in self.TESTS:
407 if test == 'all' or test == 'vm':
411 self._run_task(self.test_name)
413 def _generate_report(self):
414 """Generate test execution summary report."""
421 res_table = prettytable.PrettyTable(
423 field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
424 res_table.align['Module'] = "l"
425 res_table.align['Duration'] = "r"
426 res_table.align['Success'] = "r"
428 # for each scenario we draw a row for the table
429 for item in self.summary:
430 if item['task_status'] is True:
432 total_duration += item['overall_duration']
433 total_nb_tests += item['nb_tests']
434 total_nb_success += item['nb_success']
436 success_avg = 100 * item['nb_success'] / item['nb_tests']
437 except ZeroDivisionError:
439 success_str = str("{:0.2f}".format(success_avg)) + '%'
440 duration_str = time.strftime("%M:%S",
441 time.gmtime(item['overall_duration']))
442 res_table.add_row([item['test_name'], duration_str,
443 item['nb_tests'], success_str])
444 payload.append({'module': item['test_name'],
445 'details': {'duration': item['overall_duration'],
446 'nb tests': item['nb_tests'],
447 'success': success_str}})
449 total_duration_str = time.strftime("%H:%M:%S",
450 time.gmtime(total_duration))
452 self.result = 100 * total_nb_success / total_nb_tests
453 except ZeroDivisionError:
455 success_rate = "{:0.2f}".format(self.result)
456 success_rate_str = str(success_rate) + '%'
457 res_table.add_row(["", "", "", ""])
458 res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
461 LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
462 LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
463 self.case_name, success_rate, nb_modules,
465 payload.append({'summary': {'duration': total_duration,
466 'nb tests': total_nb_tests,
467 'nb success': success_rate}})
468 self.details = payload
471 """Cleanup of OpenStack resources. Should be called on completion."""
473 self.orig_cloud.delete_flavor(self.flavor_alt.id)
474 super(RallyBase, self).clean()
476 def is_successful(self):
477 """The overall result of the test."""
478 for item in self.summary:
479 if item['task_status'] is False:
480 return testcase.TestCase.EX_TESTCASE_FAILED
482 return super(RallyBase, self).is_successful()
484 @energy.enable_recording
485 def run(self, **kwargs):
487 self.start_time = time.time()
489 assert super(RallyBase, self).run(
490 **kwargs) == testcase.TestCase.EX_OK
493 OS_USERNAME=self.project.user.name,
494 OS_PROJECT_NAME=self.project.project.name,
495 OS_PROJECT_ID=self.project.project.id,
496 OS_PASSWORD=self.project.password)
497 conf_utils.create_rally_deployment(environ=environ)
500 self._generate_report()
501 res = testcase.TestCase.EX_OK
502 except Exception as exc: # pylint: disable=broad-except
503 LOGGER.error('Error with run: %s', exc)
505 res = testcase.TestCase.EX_RUN_ERROR
506 self.stop_time = time.time()
510 class RallySanity(RallyBase):
511 """Rally sanity testcase implementation."""
513 def __init__(self, **kwargs):
514 """Initialize RallySanity object."""
515 if "case_name" not in kwargs:
516 kwargs["case_name"] = "rally_sanity"
517 super(RallySanity, self).__init__(**kwargs)
519 self.test_name = 'all'
521 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
524 class RallyFull(RallyBase):
525 """Rally full testcase implementation."""
527 def __init__(self, **kwargs):
528 """Initialize RallyFull object."""
529 if "case_name" not in kwargs:
530 kwargs["case_name"] = "rally_full"
531 super(RallyFull, self).__init__(**kwargs)
533 self.test_name = 'all'
535 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')