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 # get keystone auth endpoint
98 task_args['request_url'] = CONST.OS_AUTH_URL or ''
102 def _prepare_test_list(self, test_name):
103 test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
104 scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
107 if not os.path.exists(scenario_file_name):
108 scenario_file_name = os.path.join(self.scenario_dir,
111 if not os.path.exists(scenario_file_name):
112 raise Exception("The scenario '%s' does not exist."
113 % scenario_file_name)
115 logger.debug('Scenario fetched from : {}'.format(scenario_file_name))
116 test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
118 if not os.path.exists(self.TEMP_DIR):
119 os.makedirs(self.TEMP_DIR)
121 self.apply_blacklist(scenario_file_name, test_file_name)
122 return test_file_name
125 def get_task_id(cmd_raw):
127 get task id from command rally result
129 :return: task_id as string
131 taskid_re = re.compile('^Task +(.*): started$')
132 for line in cmd_raw.splitlines(True):
134 match = taskid_re.match(line)
136 return match.group(1)
140 def task_succeed(json_raw):
142 Parse JSON from rally JSON results
146 rally_report = json.loads(json_raw)
147 for report in rally_report:
148 if report is None or report.get('result') is None:
151 for result in report.get('result'):
152 if result is None or len(result.get('error')) > 0:
158 def live_migration_supported():
159 config = iniparse.ConfigParser()
160 if (config.read(RallyBase.TEMPEST_CONF_FILE) and
161 config.has_section('compute-feature-enabled') and
162 config.has_option('compute-feature-enabled',
164 return config.getboolean('compute-feature-enabled',
170 def get_cmd_output(proc):
172 while proc.poll() is None:
173 line = proc.stdout.readline()
181 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
182 black_list_yaml = yaml.safe_load(black_list_file)
184 installer_type = CONST.INSTALLER_TYPE
185 deploy_scenario = CONST.DEPLOY_SCENARIO
186 if (bool(installer_type) * bool(deploy_scenario)):
187 if 'scenario' in black_list_yaml.keys():
188 for item in black_list_yaml['scenario']:
189 scenarios = item['scenarios']
190 installers = item['installers']
191 if (deploy_scenario in scenarios and
192 installer_type in installers):
193 tests = item['tests']
194 black_tests.extend(tests)
196 logger.debug("Scenario exclusion not applied.")
206 with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
207 black_list_yaml = yaml.safe_load(black_list_file)
209 if not RallyBase.live_migration_supported():
210 func_list.append("no_live_migration")
212 if 'functionality' in black_list_yaml.keys():
213 for item in black_list_yaml['functionality']:
214 functions = item['functions']
215 for func in func_list:
216 if func in functions:
217 tests = item['tests']
218 black_tests.extend(tests)
220 logger.debug("Functionality exclusion not applied.")
225 def apply_blacklist(case_file_name, result_file_name):
226 logger.debug("Applying blacklist...")
227 cases_file = open(case_file_name, 'r')
228 result_file = open(result_file_name, 'w')
230 black_tests = list(set(RallyBase.excl_func() +
231 RallyBase.excl_scenario()))
234 for cases_line in cases_file:
236 for black_tests_line in black_tests:
237 if re.search(black_tests_line,
238 cases_line.strip().rstrip(':')):
242 result_file.write(str(cases_line))
244 if cases_line.isspace():
251 def file_is_empty(file_name):
253 if os.stat(file_name).st_size > 0:
260 def _run_task(self, test_name):
261 logger.info('Starting test scenario "{}" ...'.format(test_name))
263 task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
264 if not os.path.exists(task_file):
265 logger.error("Task file '%s' does not exist." % task_file)
266 raise Exception("Task file '%s' does not exist." % task_file)
268 file_name = self._prepare_test_list(test_name)
269 if self.file_is_empty(file_name):
270 logger.info('No tests for scenario "{}"'.format(test_name))
273 cmd_line = ("rally task start --abort-on-sla-failure "
275 "--task-args \"{1}\""
276 .format(task_file, self._build_task_args(test_name)))
277 logger.debug('running command line: {}'.format(cmd_line))
279 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
280 stderr=subprocess.STDOUT, shell=True)
281 output = self._get_output(p, test_name)
282 task_id = self.get_task_id(output)
283 logger.debug('task_id : {}'.format(task_id))
286 logger.error('Failed to retrieve task_id, validating task...')
287 cmd_line = ("rally task validate "
289 "--task-args \"{1}\""
290 .format(task_file, self.__build_task_args(test_name)))
291 logger.debug('running command line: {}'.format(cmd_line))
292 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
293 stderr=subprocess.STDOUT, shell=True)
294 output = self.get_cmd_output(p)
295 logger.error("Task validation result:" + "\n" + output)
298 # check for result directory and create it otherwise
299 if not os.path.exists(self.RESULTS_DIR):
300 logger.debug('{} does not exist, we create it.'
301 .format(self.RESULTS_DIR))
302 os.makedirs(self.RESULTS_DIR)
304 # write html report file
305 report_html_name = 'opnfv-{}.html'.format(test_name)
306 report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
307 cmd_line = "rally task report {} --out {}".format(task_id,
310 logger.debug('running command line: {}'.format(cmd_line))
313 # get and save rally operation JSON result
314 cmd_line = "rally task results %s" % task_id
315 logger.debug('running command line: {}'.format(cmd_line))
316 cmd = os.popen(cmd_line)
317 json_results = cmd.read()
318 report_json_name = 'opnfv-{}.json'.format(test_name)
319 report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
320 with open(report_json_dir, 'w') as f:
321 logger.debug('saving json file')
322 f.write(json_results)
324 """ parse JSON operation result """
325 if self.task_succeed(json_results):
326 logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
328 logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
330 def _get_output(self, proc, test_name):
333 overall_duration = 0.0
337 while proc.poll() is None:
338 line = proc.stdout.readline()
339 if ("Load duration" in line or
341 "finished" in line or
342 " Preparing" in line or
346 elif "test scenario" in line:
347 result += "\n" + line
348 elif "Full duration" in line:
349 result += line + "\n\n"
351 # parse output for summary report
353 "| action" not in line and
354 "| Starting" not in line and
355 "| Completed" not in line and
356 "| ITER" not in line and
358 "| total" not in line):
360 elif "| total" in line:
361 percentage = ((line.split('|')[8]).strip(' ')).strip('%')
363 success += float(percentage)
365 logger.info('Percentage error: %s, %s' %
368 elif "Full duration" in line:
369 duration = line.split(': ')[1]
371 overall_duration += float(duration)
373 logger.info('Duration error: %s, %s' % (duration, line))
375 overall_duration = "{:10.2f}".format(overall_duration)
379 success_avg = "{:0.2f}".format(success / nb_totals)
381 scenario_summary = {'test_name': test_name,
382 'overall_duration': overall_duration,
383 'nb_tests': nb_tests,
384 'success': success_avg}
385 self.summary.append(scenario_summary)
387 logger.debug("\n" + result)
391 def _prepare_env(self):
392 logger.debug('Validating the test name...')
393 if not (self.test_name in self.TESTS):
394 raise Exception("Test name '%s' is invalid" % self.test_name)
396 volume_types = os_utils.list_volume_types(self.cinder_client,
399 logger.debug("Using existing volume type(s)...")
401 logger.debug('Creating volume type...')
402 self.volume_type = os_utils.create_volume_type(
403 self.cinder_client, self.CINDER_VOLUME_TYPE_NAME)
404 if self.volume_type is None:
405 raise Exception("Failed to create volume type '%s'" %
406 self.CINDER_VOLUME_TYPE_NAME)
407 logger.debug("Volume type '%s' is created succesfully." %
408 self.CINDER_VOLUME_TYPE_NAME)
410 logger.debug('Getting or creating image...')
411 self.image_exists, self.image_id = os_utils.get_or_create_image(
412 self.GLANCE_IMAGE_NAME,
413 self.GLANCE_IMAGE_PATH,
414 self.GLANCE_IMAGE_FORMAT)
415 if self.image_id is None:
416 raise Exception("Failed to get or create image '%s'" %
417 self.GLANCE_IMAGE_NAME)
419 logger.debug("Creating network '%s'..." % self.RALLY_PRIVATE_NET_NAME)
420 self.network_dict = os_utils.create_shared_network_full(
421 self.RALLY_PRIVATE_NET_NAME,
422 self.RALLY_PRIVATE_SUBNET_NAME,
423 self.RALLY_ROUTER_NAME,
424 self.RALLY_PRIVATE_SUBNET_CIDR)
425 if self.network_dict is None:
426 raise Exception("Failed to create shared network '%s'" %
427 self.RALLY_PRIVATE_NET_NAME)
429 def _run_tests(self):
430 if self.test_name == 'all':
431 for test in self.TESTS:
432 if (test == 'all' or test == 'vm'):
436 self._run_task(self.test_name)
438 def _generate_report(self):
443 " Rally Summary Report\n"
445 "+===================+============+===============+===========+"
447 "| Module | Duration | nb. Test Run | Success |"
449 "+===================+============+===============+===========+"
453 # for each scenario we draw a row for the table
457 for s in self.summary:
458 name = "{0:<17}".format(s['test_name'])
459 duration = float(s['overall_duration'])
460 total_duration += duration
461 duration = time.strftime("%M:%S", time.gmtime(duration))
462 duration = "{0:<10}".format(duration)
463 nb_tests = "{0:<13}".format(s['nb_tests'])
464 total_nb_tests += int(s['nb_tests'])
465 success = "{0:<10}".format(str(s['success']) + '%')
466 total_success += float(s['success'])
468 "| " + name + " | " + duration + " | " +
469 nb_tests + " | " + success + "|\n" +
470 "+-------------------+------------"
471 "+---------------+-----------+\n")
472 payload.append({'module': name,
473 'details': {'duration': s['overall_duration'],
474 'nb tests': s['nb_tests'],
475 'success': s['success']}})
477 total_duration_str = time.strftime("%H:%M:%S",
478 time.gmtime(total_duration))
479 total_duration_str2 = "{0:<10}".format(total_duration_str)
480 total_nb_tests_str = "{0:<13}".format(total_nb_tests)
482 if len(self.summary):
483 success_rate = total_success / len(self.summary)
486 success_rate = "{:0.2f}".format(success_rate)
487 success_rate_str = "{0:<10}".format(str(success_rate) + '%')
488 report += ("+===================+============"
489 "+===============+===========+")
491 report += ("| TOTAL: | " + total_duration_str2 + " | " +
492 total_nb_tests_str + " | " + success_rate_str + "|\n")
493 report += ("+===================+============"
494 "+===============+===========+")
497 logger.info("\n" + report)
498 payload.append({'summary': {'duration': total_duration,
499 'nb tests': total_nb_tests,
500 'nb success': success_rate}})
502 self.criteria = ft_utils.check_success_rate(
503 self.case_name, success_rate)
504 self.details = payload
506 logger.info("Rally '%s' success_rate is %s%%, is marked as %s"
507 % (self.case_name, success_rate, self.criteria))
511 logger.debug("Deleting volume type '%s'..." % self.volume_type)
512 os_utils.delete_volume_type(self.cinder_client, self.volume_type)
514 if not self.image_exists:
515 logger.debug("Deleting image '%s' with ID '%s'..."
516 % (self.GLANCE_IMAGE_NAME, self.image_id))
517 if not os_utils.delete_glance_image(self.nova_client,
519 logger.error("Error deleting the glance image")
522 self.start_time = time.time()
526 self._generate_report()
528 except Exception as e:
529 logger.error('Error with run: %s' % e)
530 return testcase_base.TestcaseBase.EX_RUN_ERROR
531 self.stop_time = time.time()
533 # If we are here, it means that the test case was successfully executed
534 # criteria is managed by the criteria Field
535 return testcase_base.TestcaseBase.EX_OK
538 class RallySanity(RallyBase):
540 super(RallySanity, self).__init__()
541 self.case_name = 'rally_sanity'
543 self.test_name = 'all'
545 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
548 class RallyFull(RallyBase):
550 super(RallyFull, self).__init__()
551 self.case_name = 'rally_full'
553 self.test_name = 'all'
555 self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')