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
20 from functest.core import testcase_base
21 from functest.utils.constants import CONST
22 import functest.utils.functest_logger as ft_logger
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.openstack_utils as os_utils
26 logger = ft_logger.Logger('Rally').getLogger()
29 class RallyBase(testcase_base.TestcaseBase):
30 TESTS = ['authenticate', 'glance', 'cinder', 'heat', 'keystone',
31 'neutron', 'nova', 'quotas', 'requests', 'vm', 'all']
32 GLANCE_IMAGE_NAME = CONST.openstack_image_name
33 GLANCE_IMAGE_FILENAME = CONST.openstack_image_file_name
34 GLANCE_IMAGE_PATH = os.path.join(CONST.dir_functest_data,
35 GLANCE_IMAGE_FILENAME)
36 GLANCE_IMAGE_FORMAT = CONST.openstack_image_disk_format
37 FLAVOR_NAME = "m1.tiny"
39 RALLY_DIR = os.path.join(CONST.dir_repo_functest, CONST.dir_rally)
40 RALLY_SCENARIO_DIR = os.path.join(RALLY_DIR, "scenario")
41 TEMPLATE_DIR = os.path.join(RALLY_SCENARIO_DIR, "templates")
42 SUPPORT_DIR = os.path.join(RALLY_SCENARIO_DIR, "support")
45 ITERATIONS_AMOUNT = 10
47 RESULTS_DIR = os.path.join(CONST.dir_results, 'rally')
48 TEMPEST_CONF_FILE = os.path.join(CONST.dir_results,
49 'tempest/tempest.conf')
50 BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
51 TEMP_DIR = os.path.join(RALLY_DIR, "var")
53 CINDER_VOLUME_TYPE_NAME = "volume_test"
54 RALLY_PRIVATE_NET_NAME = CONST.rally_network_name
55 RALLY_PRIVATE_SUBNET_NAME = CONST.rally_subnet_name
56 RALLY_PRIVATE_SUBNET_CIDR = CONST.rally_subnet_cidr
57 RALLY_ROUTER_NAME = CONST.rally_router_name
60 super(RallyBase, self).__init__()
63 self.scenario_dir = ''
64 self.nova_client = os_utils.get_nova_client()
65 self.neutron_client = os_utils.get_neutron_client()
66 self.cinder_client = os_utils.get_cinder_client()
67 self.network_dict = {}
68 self.volume_type = None
70 def _build_task_args(self, test_file_name):
71 task_args = {'service_list': [test_file_name]}
72 task_args['image_name'] = self.GLANCE_IMAGE_NAME
73 task_args['flavor_name'] = self.FLAVOR_NAME
74 task_args['glance_image_location'] = self.GLANCE_IMAGE_PATH
75 task_args['glance_image_format'] = self.GLANCE_IMAGE_FORMAT
76 task_args['tmpl_dir'] = self.TEMPLATE_DIR
77 task_args['sup_dir'] = self.SUPPORT_DIR
78 task_args['users_amount'] = self.USERS_AMOUNT
79 task_args['tenants_amount'] = self.TENANTS_AMOUNT
80 task_args['use_existing_users'] = False
81 task_args['iterations'] = self.ITERATIONS_AMOUNT
82 task_args['concurrency'] = self.CONCURRENCY
83 task_args['smoke'] = self.smoke
85 ext_net = os_utils.get_external_net(self.neutron_client)
87 task_args['floating_network'] = str(ext_net)
89 task_args['floating_network'] = ''
91 net_id = self.network_dict['net_id']
93 task_args['netid'] = str(net_id)
95 task_args['netid'] = ''
97 auth_url = CONST.OS_AUTH_URL
98 if auth_url is not None:
99 task_args['request_url'] = auth_url.rsplit(":", 1)[0]
101 task_args['request_url'] = ''
105 def _prepare_test_list(self, test_name):
106 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
107 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
110 if not os.path.exists(scenario_file_name):
111 scenario_file_name = os.path.join(self.scenario_dir,
114 if not os.path.exists(scenario_file_name):
115 raise Exception("The scenario '%s' does not exist."
116 % scenario_file_name)
118 logger.debug('Scenario fetched from : {}'.format(scenario_file_name))
119 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
121 if not os.path.exists(self.TEMP_DIR):
122 os.makedirs(self.TEMP_DIR)
124 self.apply_blacklist(scenario_file_name, test_file_name)
125 return test_file_name
128 def get_task_id(cmd_raw):
130 get task id from command rally result
132 :return: task_id as string
134 taskid_re = re.compile('^Task +(.*): started$')
135 for line in cmd_raw.splitlines(True):
137 match = taskid_re.match(line)
139 return match.group(1)
143 def task_succeed(json_raw):
145 Parse JSON from rally JSON results
149 rally_report = json.loads(json_raw)
150 for report in rally_report:
151 if report is None or report.get('result') is None:
154 for result in report.get('result'):
155 if result is None or len(result.get('error')) > 0:
161 def live_migration_supported():
162 config = iniparse.ConfigParser()
163 if (config.read(RallyBase.TEMPEST_CONF_FILE) and
164 config.has_section('compute-feature-enabled') and
165 config.has_option('compute-feature-enabled',
167 return config.getboolean('compute-feature-enabled',
173 def get_cmd_output(proc):
175 while proc.poll() is None:
176 line = proc.stdout.readline()
184 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
185 black_list_yaml = yaml.safe_load(black_list_file)
187 installer_type = CONST.INSTALLER_TYPE
188 deploy_scenario = CONST.DEPLOY_SCENARIO
189 if (bool(installer_type) * bool(deploy_scenario)):
190 if 'scenario' in black_list_yaml.keys():
191 for item in black_list_yaml['scenario']:
192 scenarios = item['scenarios']
193 installers = item['installers']
194 if (deploy_scenario in scenarios and
195 installer_type in installers):
196 tests = item['tests']
197 black_tests.extend(tests)
199 logger.debug("Scenario exclusion not applied.")
209 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
210 black_list_yaml = yaml.safe_load(black_list_file)
212 if not RallyBase.live_migration_supported():
213 func_list.append("no_live_migration")
215 if 'functionality' in black_list_yaml.keys():
216 for item in black_list_yaml['functionality']:
217 functions = item['functions']
218 for func in func_list:
219 if func in functions:
220 tests = item['tests']
221 black_tests.extend(tests)
223 logger.debug("Functionality exclusion not applied.")
228 def apply_blacklist(case_file_name, result_file_name):
229 logger.debug("Applying blacklist...")
230 cases_file = open(case_file_name, 'r')
231 result_file = open(result_file_name, 'w')
233 black_tests = list(set(RallyBase.excl_func() +
234 RallyBase.excl_scenario()))
237 for cases_line in cases_file:
239 for black_tests_line in black_tests:
240 if re.search(black_tests_line,
241 cases_line.strip().rstrip(':')):
245 result_file.write(str(cases_line))
247 if cases_line.isspace():
254 def file_is_empty(file_name):
256 if os.stat(file_name).st_size > 0:
263 def _run_task(self, test_name):
264 logger.info('Starting test scenario "{}" ...'.format(test_name))
266 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
267 if not os.path.exists(task_file):
268 logger.error("Task file '%s' does not exist." % task_file)
269 raise Exception("Task file '%s' does not exist." % task_file)
271 file_name = self._prepare_test_list(test_name)
272 if self.file_is_empty(file_name):
273 logger.info('No tests for scenario "{}"'.format(test_name))
276 cmd_line = ("rally task start --abort-on-sla-failure "
278 "--task-args \"{1}\""
279 .format(task_file, self._build_task_args(test_name)))
280 logger.debug('running command line: {}'.format(cmd_line))
282 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
283 stderr=subprocess.STDOUT, shell=True)
284 output = self._get_output(p, test_name)
285 task_id = self.get_task_id(output)
286 logger.debug('task_id : {}'.format(task_id))
289 logger.error('Failed to retrieve task_id, validating task...')
290 cmd_line = ("rally task validate "
292 "--task-args \"{1}\""
293 .format(task_file, self.__build_task_args(test_name)))
294 logger.debug('running command line: {}'.format(cmd_line))
295 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
296 stderr=subprocess.STDOUT, shell=True)
297 output = self.get_cmd_output(p)
298 logger.error("Task validation result:" + "\n" + output)
301 # check for result directory and create it otherwise
302 if not os.path.exists(self.RESULTS_DIR):
303 logger.debug('{} does not exist, we create it.'
304 .format(self.RESULTS_DIR))
305 os.makedirs(self.RESULTS_DIR)
307 # write html report file
308 report_html_name = 'opnfv-{}.html'.format(test_name)
309 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
310 cmd_line = "rally task report {} --out {}".format(task_id,
313 logger.debug('running command line: {}'.format(cmd_line))
316 # get and save rally operation JSON result
317 cmd_line = "rally task results %s" % task_id
318 logger.debug('running command line: {}'.format(cmd_line))
319 cmd = os.popen(cmd_line)
320 json_results = cmd.read()
321 report_json_name = 'opnfv-{}.json'.format(test_name)
322 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
323 with open(report_json_dir, 'w') as f:
324 logger.debug('saving json file')
325 f.write(json_results)
327 """ parse JSON operation result """
328 if self.task_succeed(json_results):
329 logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
331 logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
333 def _get_output(self, proc, test_name):
336 overall_duration = 0.0
340 while proc.poll() is None:
341 line = proc.stdout.readline()
342 if ("Load duration" in line or
344 "finished" in line or
345 " Preparing" in line or
349 elif "test scenario" in line:
350 result += "\n" + line
351 elif "Full duration" in line:
352 result += line + "\n\n"
354 # parse output for summary report
356 "| action" not in line and
357 "| Starting" not in line and
358 "| Completed" not in line and
359 "| ITER" not in line and
361 "| total" not in line):
363 elif "| total" in line:
364 percentage = ((line.split('|')[8]).strip(' ')).strip('%')
366 success += float(percentage)
368 logger.info('Percentage error: %s, %s' %
371 elif "Full duration" in line:
372 duration = line.split(': ')[1]
374 overall_duration += float(duration)
376 logger.info('Duration error: %s, %s' % (duration, line))
378 overall_duration = "{:10.2f}".format(overall_duration)
382 success_avg = "{:0.2f}".format(success / nb_totals)
384 scenario_summary = {'test_name': test_name,
385 'overall_duration': overall_duration,
386 'nb_tests': nb_tests,
387 'success': success_avg}
388 self.summary.append(scenario_summary)
390 logger.debug("\n" + result)
394 def _prepare_env(self):
395 logger.debug('Validating the test name...')
396 if not (self.test_name in self.TESTS):
397 raise Exception("Test name '%s' is invalid" % self.test_name)
399 volume_types = os_utils.list_volume_types(self.cinder_client,
402 logger.debug("Using existing volume type(s)...")
404 logger.debug('Creating volume type...')
405 self.volume_type = os_utils.create_volume_type(
406 self.cinder_client, self.CINDER_VOLUME_TYPE_NAME)
407 if self.volume_type is None:
408 raise Exception("Failed to create volume type '%s'" %
409 self.CINDER_VOLUME_TYPE_NAME)
410 logger.debug("Volume type '%s' is created succesfully." %
411 self.CINDER_VOLUME_TYPE_NAME)
413 logger.debug('Getting or creating image...')
414 self.image_exists, self.image_id = os_utils.get_or_create_image(
415 self.GLANCE_IMAGE_NAME,
416 self.GLANCE_IMAGE_PATH,
417 self.GLANCE_IMAGE_FORMAT)
418 if self.image_id is None:
419 raise Exception("Failed to get or create image '%s'" %
420 self.GLANCE_IMAGE_NAME)
422 logger.debug("Creating network '%s'..." % self.RALLY_PRIVATE_NET_NAME)
423 self.network_dict = os_utils.create_shared_network_full(
424 self.RALLY_PRIVATE_NET_NAME,
425 self.RALLY_PRIVATE_SUBNET_NAME,
426 self.RALLY_ROUTER_NAME,
427 self.RALLY_PRIVATE_SUBNET_CIDR)
428 if self.network_dict is None:
429 raise Exception("Failed to create shared network '%s'" %
430 self.RALLY_PRIVATE_NET_NAME)
432 def _run_tests(self):
433 if self.test_name == 'all':
434 for test in self.TESTS:
435 if (test == 'all' or test == 'vm'):
439 self._run_task(self.test_name)
441 def _generate_report(self):
446 " Rally Summary Report\n"
448 "+===================+============+===============+===========+"
450 "| Module | Duration | nb. Test Run | Success |"
452 "+===================+============+===============+===========+"
456 # for each scenario we draw a row for the table
460 for s in self.summary:
461 name = "{0:<17}".format(s['test_name'])
462 duration = float(s['overall_duration'])
463 total_duration += duration
464 duration = time.strftime("%M:%S", time.gmtime(duration))
465 duration = "{0:<10}".format(duration)
466 nb_tests = "{0:<13}".format(s['nb_tests'])
467 total_nb_tests += int(s['nb_tests'])
468 success = "{0:<10}".format(str(s['success']) + '%')
469 total_success += float(s['success'])
471 "| " + name + " | " + duration + " | " +
472 nb_tests + " | " + success + "|\n" +
473 "+-------------------+------------"
474 "+---------------+-----------+\n")
475 payload.append({'module': name,
476 'details': {'duration': s['overall_duration'],
477 'nb tests': s['nb_tests'],
478 'success': s['success']}})
480 total_duration_str = time.strftime("%H:%M:%S",
481 time.gmtime(total_duration))
482 total_duration_str2 = "{0:<10}".format(total_duration_str)
483 total_nb_tests_str = "{0:<13}".format(total_nb_tests)
485 if len(self.summary):
486 success_rate = total_success / len(self.summary)
489 success_rate = "{:0.2f}".format(success_rate)
490 success_rate_str = "{0:<10}".format(str(success_rate) + '%')
491 report += ("+===================+============"
492 "+===============+===========+")
494 report += ("| TOTAL: | " + total_duration_str2 + " | " +
495 total_nb_tests_str + " | " + success_rate_str + "|\n")
496 report += ("+===================+============"
497 "+===============+===========+")
500 logger.info("\n" + report)
501 payload.append({'summary': {'duration': total_duration,
502 'nb tests': total_nb_tests,
503 'nb success': success_rate}})
505 self.criteria = ft_utils.check_success_rate(
506 self.case_name, success_rate)
507 self.details = payload
509 logger.info("Rally '%s' success_rate is %s%%, is marked as %s"
510 % (self.case_name, success_rate, self.criteria))
514 logger.debug("Deleting volume type '%s'..." % self.volume_type)
515 os_utils.delete_volume_type(self.cinder_client, self.volume_type)
517 if not self.image_exists:
518 logger.debug("Deleting image '%s' with ID '%s'..."
519 % (self.GLANCE_IMAGE_NAME, self.image_id))
520 if not os_utils.delete_glance_image(self.nova_client,
522 logger.error("Error deleting the glance image")
525 self.start_time = time.time()
529 self._generate_report()
531 except Exception as e:
532 logger.error('Error with run: %s' % e)
533 return testcase_base.TestcaseBase.EX_RUN_ERROR
534 self.stop_time = time.time()
537 class RallySanity(RallyBase):
539 super(RallySanity, self).__init__()
540 self.case_name = 'rally_sanity'
542 self.test_name = 'all'
544 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
547 class RallyFull(RallyBase):
549 super(RallyFull, self).__init__()
550 self.case_name = 'rally_full'
552 self.test_name = 'all'
554 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')