3 # Copyright (c) 2015 Orange
4 # guyrodrigue.koffi@orange.com
5 # morgan.richomme@orange.com
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # 0.1 (05/2015) initial commit
12 # 0.2 (28/09/2015) extract Tempest, format json result, add ceilometer suite
13 # 0.3 (19/10/2015) remove Tempest from run_rally
14 # and push result into test DB
16 """ tests configuration """
24 import functest.utils.functest_logger as ft_logger
25 import functest.utils.functest_utils as functest_utils
26 import functest.utils.openstack_utils as os_utils
31 tests = ['authenticate', 'glance', 'cinder', 'heat', 'keystone',
32 'neutron', 'nova', 'quotas', 'requests', 'vm', 'all']
33 parser = argparse.ArgumentParser()
34 parser.add_argument("test_name",
35 help="Module name to be tested. "
36 "Possible values are : "
37 "[ {d[0]} | {d[1]} | {d[2]} | {d[3]} | {d[4]} | "
38 "{d[5]} | {d[6]} | {d[7]} | {d[8]} | {d[9]} | "
41 "performs all possible test scenarios"
44 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
45 parser.add_argument("-r", "--report",
46 help="Create json result file",
48 parser.add_argument("-s", "--smoke",
49 help="Smoke test mode",
51 parser.add_argument("-v", "--verbose",
52 help="Print verbose info about the progress",
54 parser.add_argument("-n", "--noclean",
55 help="Don't clean the created resources for this test.",
57 parser.add_argument("-z", "--sanity",
58 help="Sanity test mode, execute only a subset of tests",
61 args = parser.parse_args()
66 RALLY_STDERR = subprocess.STDOUT
68 RALLY_STDERR = open(os.devnull, 'w')
70 """ logging configuration """
71 logger = ft_logger.Logger("run_rally").getLogger()
73 REPO_PATH = os.environ['repos_dir'] + '/functest/'
74 if not os.path.exists(REPO_PATH):
75 logger.error("Functest repository directory not found '%s'" % REPO_PATH)
79 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
80 functest_yaml = yaml.safe_load(f)
83 HOME = os.environ['HOME'] + "/"
84 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get(
85 "directories").get("dir_rally")
86 TEMPLATE_DIR = RALLY_DIR + "scenario/templates"
87 SUPPORT_DIR = RALLY_DIR + "scenario/support"
89 FLAVOR_NAME = "m1.tiny"
92 ITERATIONS_AMOUNT = 10
95 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
97 TEMPEST_CONF_FILE = functest_yaml.get("general").get("directories").get(
98 "dir_results") + '/tempest/tempest.conf'
99 TEST_DB = functest_yaml.get("results").get("test_db_url")
101 PRIVATE_NET_NAME = functest_yaml.get("rally").get("network_name")
102 PRIVATE_SUBNET_NAME = functest_yaml.get("rally").get("subnet_name")
103 PRIVATE_SUBNET_CIDR = functest_yaml.get("rally").get("subnet_cidr")
104 ROUTER_NAME = functest_yaml.get("rally").get("router_name")
106 GLANCE_IMAGE_NAME = functest_yaml.get("general").get("openstack").get(
108 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get("openstack").get(
110 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get("openstack").get(
112 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
113 "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
115 CINDER_VOLUME_TYPE_NAME = "volume_test"
119 neutron_client = None
122 def get_task_id(cmd_raw):
124 get task id from command rally result
126 :return: task_id as string
128 taskid_re = re.compile('^Task +(.*): started$')
129 for line in cmd_raw.splitlines(True):
131 match = taskid_re.match(line)
133 return match.group(1)
137 def task_succeed(json_raw):
139 Parse JSON from rally JSON results
143 rally_report = json.loads(json_raw)
144 for report in rally_report:
145 if report is None or report.get('result') is None:
148 for result in report.get('result'):
149 if result is None or len(result.get('error')) > 0:
155 def live_migration_supported():
156 config = iniparse.ConfigParser()
157 if (config.read(TEMPEST_CONF_FILE) and
158 config.has_section('compute-feature-enabled') and
159 config.has_option('compute-feature-enabled', 'live_migration')):
160 return config.getboolean('compute-feature-enabled', 'live_migration')
165 def build_task_args(test_file_name):
166 task_args = {'service_list': [test_file_name]}
167 task_args['image_name'] = GLANCE_IMAGE_NAME
168 task_args['flavor_name'] = FLAVOR_NAME
169 task_args['glance_image_location'] = GLANCE_IMAGE_PATH
170 task_args['tmpl_dir'] = TEMPLATE_DIR
171 task_args['sup_dir'] = SUPPORT_DIR
172 task_args['users_amount'] = USERS_AMOUNT
173 task_args['tenants_amount'] = TENANTS_AMOUNT
174 task_args['use_existing_users'] = False
175 task_args['iterations'] = ITERATIONS_AMOUNT
176 task_args['concurrency'] = CONCURRENCY
179 task_args['full_mode'] = False
180 task_args['smoke'] = True
182 task_args['full_mode'] = True
183 task_args['smoke'] = args.smoke
185 ext_net = os_utils.get_external_net(neutron_client)
187 task_args['floating_network'] = str(ext_net)
189 task_args['floating_network'] = ''
191 net_id = network_dict['net_id']
192 task_args['netid'] = str(net_id)
193 task_args['live_migration'] = live_migration_supported()
195 auth_url = os.getenv('OS_AUTH_URL')
196 if auth_url is not None:
197 task_args['request_url'] = auth_url.rsplit(":", 1)[0]
199 task_args['request_url'] = ''
204 def get_output(proc, test_name):
208 overall_duration = 0.0
212 while proc.poll() is None:
213 line = proc.stdout.readline()
217 if ("Load duration" in line or
219 "finished" in line or
220 " Preparing" in line or
224 elif "test scenario" in line:
225 result += "\n" + line
226 elif "Full duration" in line:
227 result += line + "\n\n"
229 # parse output for summary report
231 "| action" not in line and
232 "| Starting" not in line and
233 "| Completed" not in line and
234 "| ITER" not in line and
236 "| total" not in line):
238 elif "| total" in line:
239 percentage = ((line.split('|')[8]).strip(' ')).strip('%')
241 success += float(percentage)
243 logger.info('Percentage error: %s, %s' % (percentage, line))
245 elif "Full duration" in line:
246 duration = line.split(': ')[1]
248 overall_duration += float(duration)
250 logger.info('Duration error: %s, %s' % (duration, line))
252 overall_duration = "{:10.2f}".format(overall_duration)
256 success_avg = "{:0.2f}".format(success / nb_totals)
258 scenario_summary = {'test_name': test_name,
259 'overall_duration': overall_duration,
260 'nb_tests': nb_tests,
261 'success': success_avg}
262 SUMMARY.append(scenario_summary)
264 logger.debug("\n" + result)
269 def get_cmd_output(proc):
272 while proc.poll() is None:
273 line = proc.stdout.readline()
279 def run_task(test_name):
281 # the "main" function of the script who launch rally for a task
282 # :param test_name: name for the rally test
286 logger.info('Starting test scenario "{}" ...'.format(test_name))
287 start_time = time.time()
289 task_file = '{}task.yaml'.format(RALLY_DIR)
290 if not os.path.exists(task_file):
291 logger.error("Task file '%s' does not exist." % task_file)
294 test_file_name = '{}opnfv-{}.yaml'.format(RALLY_DIR + "scenario/",
296 if not os.path.exists(test_file_name):
297 logger.error("The scenario '%s' does not exist." % test_file_name)
300 logger.debug('Scenario fetched from : {}'.format(test_file_name))
302 cmd_line = ("rally task start --abort-on-sla-failure " +
303 "--task {} ".format(task_file) +
304 "--task-args \"{}\" ".format(build_task_args(test_name)))
305 logger.debug('running command line : {}'.format(cmd_line))
307 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
308 stderr=RALLY_STDERR, shell=True)
309 output = get_output(p, test_name)
310 task_id = get_task_id(output)
311 logger.debug('task_id : {}'.format(task_id))
314 logger.error('Failed to retrieve task_id, validating task...')
315 cmd_line = ("rally task validate " +
316 "--task {} ".format(task_file) +
317 "--task-args \"{}\" ".format(build_task_args(test_name)))
318 logger.debug('running command line : {}'.format(cmd_line))
319 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
320 stderr=subprocess.STDOUT, shell=True)
321 output = get_cmd_output(p)
322 logger.error("Task validation result:" + "\n" + output)
325 # check for result directory and create it otherwise
326 if not os.path.exists(RESULTS_DIR):
327 logger.debug('%s does not exist, we create it.'.format(RESULTS_DIR))
328 os.makedirs(RESULTS_DIR)
330 # write html report file
331 report_file_name = '{}opnfv-{}.html'.format(RESULTS_DIR, test_name)
332 cmd_line = "rally task report {} --out {}".format(task_id,
335 logger.debug('running command line : {}'.format(cmd_line))
338 # get and save rally operation JSON result
339 cmd_line = "rally task results %s" % task_id
340 logger.debug('running command line : {}'.format(cmd_line))
341 cmd = os.popen(cmd_line)
342 json_results = cmd.read()
343 with open('{}opnfv-{}.json'.format(RESULTS_DIR, test_name), 'w') as f:
344 logger.debug('saving json file')
345 f.write(json_results)
347 with open('{}opnfv-{}.json'
348 .format(RESULTS_DIR, test_name)) as json_file:
349 json_data = json.load(json_file)
351 """ parse JSON operation result """
353 if task_succeed(json_results):
354 logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
357 logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
359 # Push results in payload of testcase
361 stop_time = time.time()
362 logger.debug("Push Rally detailed results into DB")
363 functest_utils.push_results_to_db("functest",
375 global neutron_client
377 nova_client = os_utils.get_nova_client()
378 neutron_client = os_utils.get_neutron_client()
379 glance_client = os_utils.get_glance_client()
380 cinder_client = os_utils.get_cinder_client()
382 start_time = time.time()
385 if not (args.test_name in tests):
386 logger.error('argument not valid')
391 volume_types = os_utils.list_volume_types(cinder_client,
394 volume_type = os_utils.create_volume_type(
395 cinder_client, CINDER_VOLUME_TYPE_NAME)
397 logger.error("Failed to create volume type...")
400 logger.debug("Volume type '%s' created succesfully..."
401 % CINDER_VOLUME_TYPE_NAME)
403 logger.debug("Using existing volume type(s)...")
405 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
409 logger.debug("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
411 image_id = os_utils.create_glance_image(glance_client,
415 logger.error("Failed to create the Glance image...")
418 logger.debug("Image '%s' with ID '%s' created succesfully ."
419 % (GLANCE_IMAGE_NAME, image_id))
421 logger.debug("Using existing image '%s' with ID '%s'..."
422 % (GLANCE_IMAGE_NAME, image_id))
425 logger.debug("Creating network '%s'..." % PRIVATE_NET_NAME)
426 network_dict = os_utils.create_network_full(neutron_client,
432 logger.error("Failed to create network...")
435 if not os_utils.update_neutron_net(neutron_client,
436 network_dict['net_id'],
438 logger.error("Failed to update network...")
441 logger.debug("Network '%s' available..." % PRIVATE_NET_NAME)
443 if args.test_name == "all":
444 for test_name in tests:
445 if not (test_name == 'all' or
449 logger.debug("Test name: " + args.test_name)
450 run_task(args.test_name)
455 " Rally Summary Report\n"
457 "+===================+============+===============+===========+"
459 "| Module | Duration | nb. Test Run | Success |"
461 "+===================+============+===============+===========+"
464 stop_time = time.time()
466 # for each scenario we draw a row for the table
471 name = "{0:<17}".format(s['test_name'])
472 duration = float(s['overall_duration'])
473 total_duration += duration
474 duration = time.strftime("%M:%S", time.gmtime(duration))
475 duration = "{0:<10}".format(duration)
476 nb_tests = "{0:<13}".format(s['nb_tests'])
477 total_nb_tests += int(s['nb_tests'])
478 success = "{0:<10}".format(str(s['success']) + '%')
479 total_success += float(s['success'])
481 "| " + name + " | " + duration + " | " +
482 nb_tests + " | " + success + "|\n" +
483 "+-------------------+------------"
484 "+---------------+-----------+\n")
485 payload.append({'module': name,
486 'details': {'duration': s['overall_duration'],
487 'nb tests': s['nb_tests'],
488 'success': s['success']}})
490 total_duration_str = time.strftime("%H:%M:%S", time.gmtime(total_duration))
491 total_duration_str2 = "{0:<10}".format(total_duration_str)
492 total_nb_tests_str = "{0:<13}".format(total_nb_tests)
493 success_rate = "{:0.2f}".format(total_success / len(SUMMARY))
494 success_rate_str = "{0:<10}".format(str(success_rate) + '%')
495 report += "+===================+============+===============+===========+"
497 report += ("| TOTAL: | " + total_duration_str2 + " | " +
498 total_nb_tests_str + " | " + success_rate_str + "|\n")
499 report += "+===================+============+===============+===========+"
502 logger.info("\n" + report)
503 payload.append({'summary': {'duration': total_duration,
504 'nb tests': total_nb_tests,
505 'nb success': success_rate}})
507 # Generate json results for DB
508 # json_results = {"timestart": time_start, "duration": total_duration,
509 # "tests": int(total_nb_tests),
510 # "success": int(total_success)}
511 # logger.info("Results: "+str(json_results))
513 # Evaluation of the success criteria
515 # for Rally we decided that the overall success rate must be above 90%
516 if float(success_rate) >= 90:
520 case_name = "rally_sanity"
522 case_name = "rally_full"
525 logger.debug("Pushing Rally summary into DB...")
526 functest_utils.push_results_to_db("functest",
537 logger.debug("Deleting image '%s' with ID '%s'..."
538 % (GLANCE_IMAGE_NAME, image_id))
539 if not os_utils.delete_glance_image(nova_client, image_id):
540 logger.error("Error deleting the glance image")
543 logger.debug("Deleting volume type '%s'..."
544 % CINDER_VOLUME_TYPE_NAME)
545 if not os_utils.delete_volume_type(cinder_client, volume_type):
546 logger.error("Error in deleting volume type...")
549 if __name__ == '__main__':