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
26 from functest.core import testcase
27 from functest.energy import energy
28 from functest.utils.constants import CONST
29 import functest.utils.openstack_utils as os_utils
31 LOGGER = logging.getLogger(__name__)
34 class RallyBase(testcase.OSGCTestCase):
35 """Base class form Rally testcases implementation."""
37 TESTS = ['authenticate', 'glance', 'ceilometer', 'cinder', 'heat',
38 'keystone', 'neutron', 'nova', 'quotas', 'vm', 'all']
39 GLANCE_IMAGE_NAME = CONST.__getattribute__('openstack_image_name')
40 GLANCE_IMAGE_FILENAME = CONST.__getattribute__('openstack_image_file_name')
41 GLANCE_IMAGE_PATH = os.path.join(
42 CONST.__getattribute__('dir_functest_images'),
43 GLANCE_IMAGE_FILENAME)
44 GLANCE_IMAGE_FORMAT = CONST.__getattribute__('openstack_image_disk_format')
45 GLANCE_IMAGE_EXTRA_PROPERTIES = {}
46 if hasattr(CONST, 'openstack_extra_properties'):
47 GLANCE_IMAGE_EXTRA_PROPERTIES = CONST.__getattribute__(
48 'openstack_extra_properties')
49 FLAVOR_NAME = "m1.tiny"
51 RALLY_DIR = pkg_resources.resource_filename(
52 'functest', 'opnfv_tests/openstack/rally')
53 RALLY_SCENARIO_DIR = pkg_resources.resource_filename(
54 'functest', 'opnfv_tests/openstack/rally/scenario')
55 TEMPLATE_DIR = pkg_resources.resource_filename(
56 'functest', 'opnfv_tests/openstack/rally/scenario/templates')
57 SUPPORT_DIR = pkg_resources.resource_filename(
58 'functest', 'opnfv_tests/openstack/rally/scenario/support')
61 ITERATIONS_AMOUNT = 10
63 RESULTS_DIR = os.path.join(CONST.__getattribute__('dir_results'), 'rally')
64 TEMPEST_CONF_FILE = os.path.join(CONST.__getattribute__('dir_results'),
65 'tempest/tempest.conf')
66 BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
67 TEMP_DIR = os.path.join(RALLY_DIR, "var")
69 RALLY_PRIVATE_NET_NAME = CONST.__getattribute__('rally_network_name')
70 RALLY_PRIVATE_SUBNET_NAME = CONST.__getattribute__('rally_subnet_name')
71 RALLY_PRIVATE_SUBNET_CIDR = CONST.__getattribute__('rally_subnet_cidr')
72 RALLY_ROUTER_NAME = CONST.__getattribute__('rally_router_name')
74 def __init__(self, **kwargs):
75 """Initialize RallyBase object."""
76 super(RallyBase, self).__init__(**kwargs)
79 self.scenario_dir = ''
80 self.nova_client = os_utils.get_nova_client()
81 self.neutron_client = os_utils.get_neutron_client()
82 self.network_dict = {}
85 self.image_exists = None
87 self.start_time = None
91 def _build_task_args(self, test_file_name):
92 task_args = {'service_list': [test_file_name]}
93 task_args['image_name'] = self.GLANCE_IMAGE_NAME
94 task_args['flavor_name'] = self.FLAVOR_NAME
95 task_args['glance_image_location'] = self.GLANCE_IMAGE_PATH
96 task_args['glance_image_format'] = self.GLANCE_IMAGE_FORMAT
97 task_args['tmpl_dir'] = self.TEMPLATE_DIR
98 task_args['sup_dir'] = 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
106 ext_net = os_utils.get_external_net(self.neutron_client)
108 task_args['floating_network'] = str(ext_net)
110 task_args['floating_network'] = ''
112 net_id = self.network_dict['net_id']
114 task_args['netid'] = str(net_id)
116 task_args['netid'] = ''
120 def _prepare_test_list(self, test_name):
121 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
122 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
125 if not os.path.exists(scenario_file_name):
126 scenario_file_name = os.path.join(self.scenario_dir,
129 if not os.path.exists(scenario_file_name):
130 raise Exception("The scenario '%s' does not exist."
131 % scenario_file_name)
133 LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
134 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
136 if not os.path.exists(self.TEMP_DIR):
137 os.makedirs(self.TEMP_DIR)
139 self.apply_blacklist(scenario_file_name, test_file_name)
140 return test_file_name
143 def get_task_id(cmd_raw):
145 Get task id from command rally result.
148 :return: task_id as string
150 taskid_re = re.compile('^Task +(.*): started$')
151 for line in cmd_raw.splitlines(True):
153 match = taskid_re.match(line)
155 return match.group(1)
159 def task_succeed(json_raw):
161 Parse JSON from rally JSON results.
166 rally_report = json.loads(json_raw)
167 for report in rally_report:
168 if report is None or report.get('result') is None:
171 for result in report.get('result'):
172 if result is None or len(result.get('error')) > 0:
178 def live_migration_supported():
179 """Determine if live migration is supported."""
180 config = iniparse.ConfigParser()
181 if (config.read(RallyBase.TEMPEST_CONF_FILE) and
182 config.has_section('compute-feature-enabled') and
183 config.has_option('compute-feature-enabled',
185 return config.getboolean('compute-feature-enabled',
191 def get_cmd_output(proc):
192 """Get command stdout."""
194 while proc.poll() is None:
195 line = proc.stdout.readline()
201 """Exclude scenario."""
204 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
205 black_list_yaml = yaml.safe_load(black_list_file)
207 installer_type = CONST.__getattribute__('INSTALLER_TYPE')
208 deploy_scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
209 if (bool(installer_type) and bool(deploy_scenario) and
210 'scenario' in black_list_yaml.keys()):
211 for item in black_list_yaml['scenario']:
212 scenarios = item['scenarios']
213 installers = item['installers']
214 in_it = RallyBase.in_iterable_re
215 if (in_it(deploy_scenario, scenarios) and
216 in_it(installer_type, installers)):
217 tests = item['tests']
218 black_tests.extend(tests)
220 LOGGER.debug("Scenario exclusion not applied.")
225 def in_iterable_re(needle, haystack):
227 Check if given needle is in the iterable haystack, using regex.
229 :param needle: string to be matched
230 :param haystack: iterable of strings (optionally regex patterns)
231 :return: True if needle is eqial to any of the elements in haystack,
232 or if a nonempty regex pattern in haystack is found in needle.
234 # match without regex
235 if needle in haystack:
238 for pattern in haystack:
239 # match if regex pattern is set and found in the needle
240 if pattern and re.search(pattern, needle) is not None:
247 """Exclude functionalities."""
252 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
253 black_list_yaml = yaml.safe_load(black_list_file)
255 if not RallyBase.live_migration_supported():
256 func_list.append("no_live_migration")
258 if 'functionality' in black_list_yaml.keys():
259 for item in black_list_yaml['functionality']:
260 functions = item['functions']
261 for func in func_list:
262 if func in functions:
263 tests = item['tests']
264 black_tests.extend(tests)
265 except Exception: # pylint: disable=broad-except
266 LOGGER.debug("Functionality exclusion not applied.")
271 def apply_blacklist(case_file_name, result_file_name):
272 """Apply blacklist."""
273 LOGGER.debug("Applying blacklist...")
274 cases_file = open(case_file_name, 'r')
275 result_file = open(result_file_name, 'w')
277 black_tests = list(set(RallyBase.excl_func() +
278 RallyBase.excl_scenario()))
281 LOGGER.debug("Blacklisted tests: " + str(black_tests))
284 for cases_line in cases_file:
286 for black_tests_line in black_tests:
287 if re.search(black_tests_line,
288 cases_line.strip().rstrip(':')):
292 result_file.write(str(cases_line))
294 if cases_line.isspace():
301 def file_is_empty(file_name):
302 """Determine is a file is empty."""
304 if os.stat(file_name).st_size > 0:
306 except Exception: # pylint: disable=broad-except
311 def _run_task(self, test_name):
313 LOGGER.info('Starting test scenario "%s" ...', test_name)
315 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
316 if not os.path.exists(task_file):
317 LOGGER.error("Task file '%s' does not exist.", task_file)
318 raise Exception("Task file '%s' does not exist.", task_file)
320 file_name = self._prepare_test_list(test_name)
321 if self.file_is_empty(file_name):
322 LOGGER.info('No tests for scenario "%s"', test_name)
325 cmd_line = ("rally task start --abort-on-sla-failure "
327 "--task-args \"{1}\""
328 .format(task_file, self._build_task_args(test_name)))
329 LOGGER.debug('running command line: %s', cmd_line)
331 proc = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
332 stderr=subprocess.STDOUT, shell=True)
333 output = self._get_output(proc, test_name)
334 task_id = self.get_task_id(output)
335 LOGGER.debug('task_id : %s', task_id)
338 LOGGER.error('Failed to retrieve task_id, validating task...')
339 cmd_line = ("rally task validate "
341 "--task-args \"{1}\""
342 .format(task_file, self._build_task_args(test_name)))
343 LOGGER.debug('running command line: %s', cmd_line)
344 proc = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
345 stderr=subprocess.STDOUT, shell=True)
346 output = self.get_cmd_output(proc)
347 LOGGER.error("Task validation result:" + "\n" + output)
350 # check for result directory and create it otherwise
351 if not os.path.exists(self.RESULTS_DIR):
352 LOGGER.debug('%s does not exist, we create it.',
354 os.makedirs(self.RESULTS_DIR)
356 # write html report file
357 report_html_name = 'opnfv-{}.html'.format(test_name)
358 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
359 cmd_line = "rally task report {} --out {}".format(task_id,
362 LOGGER.debug('running command line: %s', cmd_line)
365 # get and save rally operation JSON result
366 cmd_line = "rally task results %s" % task_id
367 LOGGER.debug('running command line: %s', cmd_line)
368 cmd = os.popen(cmd_line)
369 json_results = cmd.read()
370 report_json_name = 'opnfv-{}.json'.format(test_name)
371 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
372 with open(report_json_dir, 'w') as r_file:
373 LOGGER.debug('saving json file')
374 r_file.write(json_results)
376 # parse JSON operation result
377 if self.task_succeed(json_results):
378 LOGGER.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
380 LOGGER.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
382 def _get_output(self, proc, test_name):
385 overall_duration = 0.0
389 while proc.poll() is None:
390 line = proc.stdout.readline()
391 if ("Load duration" in line or
393 "finished" in line or
394 " Preparing" in line or
398 elif "test scenario" in line:
399 result += "\n" + line
400 elif "Full duration" in line:
401 result += line + "\n\n"
403 # parse output for summary report
405 "| action" not in line and
406 "| Starting" not in line and
407 "| Completed" not in line and
408 "| ITER" not in line and
410 "| total" not in line):
412 elif "| total" in line:
413 percentage = ((line.split('|')[8]).strip(' ')).strip('%')
415 success += float(percentage)
417 LOGGER.info('Percentage error: %s, %s',
420 elif "Full duration" in line:
421 duration = line.split(': ')[1]
423 overall_duration += float(duration)
425 LOGGER.info('Duration error: %s, %s', duration, line)
427 overall_duration = "{:10.2f}".format(overall_duration)
431 success_avg = "{:0.2f}".format(success / nb_totals)
433 scenario_summary = {'test_name': test_name,
434 'overall_duration': overall_duration,
435 'nb_tests': nb_tests,
436 'success': success_avg}
437 self.summary.append(scenario_summary)
439 LOGGER.debug("\n" + result)
443 def _prepare_env(self):
444 LOGGER.debug('Validating the test name...')
445 if self.test_name not in self.TESTS:
446 raise Exception("Test name '%s' is invalid" % self.test_name)
448 LOGGER.debug('Getting or creating image...')
449 self.image_exists, self.image_id = os_utils.get_or_create_image(
450 self.GLANCE_IMAGE_NAME,
451 self.GLANCE_IMAGE_PATH,
452 self.GLANCE_IMAGE_FORMAT,
453 self.GLANCE_IMAGE_EXTRA_PROPERTIES)
454 if self.image_id is None:
455 raise Exception("Failed to get or create image '%s'" %
456 self.GLANCE_IMAGE_NAME)
458 LOGGER.debug("Creating network '%s'...", self.RALLY_PRIVATE_NET_NAME)
459 self.network_dict = os_utils.create_shared_network_full(
460 self.RALLY_PRIVATE_NET_NAME,
461 self.RALLY_PRIVATE_SUBNET_NAME,
462 self.RALLY_ROUTER_NAME,
463 self.RALLY_PRIVATE_SUBNET_CIDR)
464 if self.network_dict is None:
465 raise Exception("Failed to create shared network '%s'" %
466 self.RALLY_PRIVATE_NET_NAME)
468 def _run_tests(self):
469 if self.test_name == 'all':
470 for test in self.TESTS:
471 if test == 'all' or test == 'vm':
475 self._run_task(self.test_name)
477 def _generate_report(self):
482 " Rally Summary Report\n"
484 "+===================+============+===============+===========+"
486 "| Module | Duration | nb. Test Run | Success |"
488 "+===================+============+===============+===========+"
492 # for each scenario we draw a row for the table
496 for item in self.summary:
497 name = "{0:<17}".format(item['test_name'])
498 duration = float(item['overall_duration'])
499 total_duration += duration
500 duration = time.strftime("%M:%S", time.gmtime(duration))
501 duration = "{0:<10}".format(duration)
502 nb_tests = "{0:<13}".format(item['nb_tests'])
503 total_nb_tests += int(item['nb_tests'])
504 success = "{0:<10}".format(str(item['success']) + '%')
505 total_success += float(item['success'])
507 "| " + name + " | " + duration + " | " +
508 nb_tests + " | " + success + "|\n" +
509 "+-------------------+------------"
510 "+---------------+-----------+\n")
511 payload.append({'module': name,
512 'details': {'duration': item['overall_duration'],
513 'nb tests': item['nb_tests'],
514 'success': item['success']}})
516 total_duration_str = time.strftime("%H:%M:%S",
517 time.gmtime(total_duration))
518 total_duration_str2 = "{0:<10}".format(total_duration_str)
519 total_nb_tests_str = "{0:<13}".format(total_nb_tests)
522 self.result = total_success / len(self.summary)
523 except ZeroDivisionError:
526 success_rate = "{:0.2f}".format(self.result)
527 success_rate_str = "{0:<10}".format(str(success_rate) + '%')
528 report += ("+===================+============"
529 "+===============+===========+")
531 report += ("| TOTAL: | " + total_duration_str2 + " | " +
532 total_nb_tests_str + " | " + success_rate_str + "|\n")
533 report += ("+===================+============"
534 "+===============+===========+")
537 LOGGER.info("\n" + report)
538 payload.append({'summary': {'duration': total_duration,
539 'nb tests': total_nb_tests,
540 'nb success': success_rate}})
542 self.details = payload
544 LOGGER.info("Rally '%s' success_rate is %s%%",
545 self.case_name, success_rate)
548 if not self.image_exists:
549 LOGGER.debug("Deleting image '%s' with ID '%s'...",
550 self.GLANCE_IMAGE_NAME, self.image_id)
551 if not os_utils.delete_glance_image(self.nova_client,
553 LOGGER.error("Error deleting the glance image")
555 @energy.enable_recording
556 def run(self, **kwargs):
558 self.start_time = time.time()
562 self._generate_report()
564 res = testcase.TestCase.EX_OK
565 except Exception as exc: # pylint: disable=broad-except
566 LOGGER.error('Error with run: %s', exc)
567 res = testcase.TestCase.EX_RUN_ERROR
569 self.stop_time = time.time()
573 class RallySanity(RallyBase):
574 """Rally sanity testcase implementation."""
576 def __init__(self, **kwargs):
577 """Initialize RallySanity object."""
578 if "case_name" not in kwargs:
579 kwargs["case_name"] = "rally_sanity"
580 super(RallySanity, self).__init__(**kwargs)
582 self.test_name = 'all'
584 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
587 class RallyFull(RallyBase):
588 """Rally full testcase implementation."""
590 def __init__(self, **kwargs):
591 """Initialize RallyFull object."""
592 if "case_name" not in kwargs:
593 kwargs["case_name"] = "rally_full"
594 super(RallyFull, self).__init__(**kwargs)
596 self.test_name = 'all'
598 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')