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()
288 stop_time = start_time
290 task_file = '{}task.yaml'.format(RALLY_DIR)
291 if not os.path.exists(task_file):
292 logger.error("Task file '%s' does not exist." % task_file)
295 test_file_name = '{}opnfv-{}.yaml'.format(RALLY_DIR + "scenario/",
297 if not os.path.exists(test_file_name):
298 logger.error("The scenario '%s' does not exist." % test_file_name)
301 logger.debug('Scenario fetched from : {}'.format(test_file_name))
303 cmd_line = ("rally task start --abort-on-sla-failure " +
304 "--task {} ".format(task_file) +
305 "--task-args \"{}\" ".format(build_task_args(test_name)))
306 logger.debug('running command line : {}'.format(cmd_line))
308 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
309 stderr=RALLY_STDERR, shell=True)
310 output = get_output(p, test_name)
311 task_id = get_task_id(output)
312 logger.debug('task_id : {}'.format(task_id))
315 logger.error('Failed to retrieve task_id, validating task...')
316 cmd_line = ("rally task validate " +
317 "--task {} ".format(task_file) +
318 "--task-args \"{}\" ".format(build_task_args(test_name)))
319 logger.debug('running command line : {}'.format(cmd_line))
320 p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
321 stderr=subprocess.STDOUT, shell=True)
322 output = get_cmd_output(p)
323 logger.error("Task validation result:" + "\n" + output)
326 # check for result directory and create it otherwise
327 if not os.path.exists(RESULTS_DIR):
328 logger.debug('%s does not exist, we create it.'.format(RESULTS_DIR))
329 os.makedirs(RESULTS_DIR)
331 # write html report file
332 report_file_name = '{}opnfv-{}.html'.format(RESULTS_DIR, test_name)
333 cmd_line = "rally task report {} --out {}".format(task_id,
336 logger.debug('running command line : {}'.format(cmd_line))
339 # get and save rally operation JSON result
340 cmd_line = "rally task results %s" % task_id
341 logger.debug('running command line : {}'.format(cmd_line))
342 cmd = os.popen(cmd_line)
343 json_results = cmd.read()
344 with open('{}opnfv-{}.json'.format(RESULTS_DIR, test_name), 'w') as f:
345 logger.debug('saving json file')
346 f.write(json_results)
348 with open('{}opnfv-{}.json'
349 .format(RESULTS_DIR, test_name)) as json_file:
350 json_data = json.load(json_file)
352 """ parse JSON operation result """
354 if task_succeed(json_results):
355 logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
358 logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
360 # Push results in payload of testcase
362 stop_time = time.time()
363 logger.debug("Push Rally detailed results into DB")
364 functest_utils.push_results_to_db("functest",
376 global neutron_client
378 nova_client = os_utils.get_nova_client()
379 neutron_client = os_utils.get_neutron_client()
380 glance_client = os_utils.get_glance_client()
381 cinder_client = os_utils.get_cinder_client()
383 start_time = time.time()
384 stop_time = start_time
387 if not (args.test_name in tests):
388 logger.error('argument not valid')
393 volume_types = os_utils.list_volume_types(cinder_client,
396 volume_type = os_utils.create_volume_type(
397 cinder_client, CINDER_VOLUME_TYPE_NAME)
399 logger.error("Failed to create volume type...")
402 logger.debug("Volume type '%s' created succesfully..."
403 % CINDER_VOLUME_TYPE_NAME)
405 logger.debug("Using existing volume type(s)...")
407 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
411 logger.debug("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
413 image_id = os_utils.create_glance_image(glance_client,
417 logger.error("Failed to create the Glance image...")
420 logger.debug("Image '%s' with ID '%s' created succesfully ."
421 % (GLANCE_IMAGE_NAME, image_id))
423 logger.debug("Using existing image '%s' with ID '%s'..."
424 % (GLANCE_IMAGE_NAME, image_id))
427 logger.debug("Creating network '%s'..." % PRIVATE_NET_NAME)
428 network_dict = os_utils.create_network_full(neutron_client,
434 logger.error("Failed to create network...")
437 if not os_utils.update_neutron_net(neutron_client,
438 network_dict['net_id'],
440 logger.error("Failed to update network...")
443 logger.debug("Network '%s' available..." % PRIVATE_NET_NAME)
445 if args.test_name == "all":
446 for test_name in tests:
447 if not (test_name == 'all' or
451 logger.debug("Test name: " + args.test_name)
452 run_task(args.test_name)
457 " Rally Summary Report\n"
459 "+===================+============+===============+===========+"
461 "| Module | Duration | nb. Test Run | Success |"
463 "+===================+============+===============+===========+"
466 stop_time = time.time()
468 # for each scenario we draw a row for the table
473 name = "{0:<17}".format(s['test_name'])
474 duration = float(s['overall_duration'])
475 total_duration += duration
476 duration = time.strftime("%M:%S", time.gmtime(duration))
477 duration = "{0:<10}".format(duration)
478 nb_tests = "{0:<13}".format(s['nb_tests'])
479 total_nb_tests += int(s['nb_tests'])
480 success = "{0:<10}".format(str(s['success']) + '%')
481 total_success += float(s['success'])
483 "| " + name + " | " + duration + " | " +
484 nb_tests + " | " + success + "|\n" +
485 "+-------------------+------------"
486 "+---------------+-----------+\n")
487 payload.append({'module': name,
488 'details': {'duration': s['overall_duration'],
489 'nb tests': s['nb_tests'],
490 'success': s['success']}})
492 total_duration_str = time.strftime("%H:%M:%S", time.gmtime(total_duration))
493 total_duration_str2 = "{0:<10}".format(total_duration_str)
494 total_nb_tests_str = "{0:<13}".format(total_nb_tests)
495 total_success = "{:0.2f}".format(total_success / len(SUMMARY))
496 total_success_str = "{0:<10}".format(str(total_success) + '%')
497 report += "+===================+============+===============+===========+"
499 report += ("| TOTAL: | " + total_duration_str2 + " | " +
500 total_nb_tests_str + " | " + total_success_str + "|\n")
501 report += "+===================+============+===============+===========+"
504 logger.info("\n" + report)
505 payload.append({'summary': {'duration': total_duration,
506 'nb tests': total_nb_tests,
507 'nb success': total_success}})
509 # Generate json results for DB
510 # json_results = {"timestart": time_start, "duration": total_duration,
511 # "tests": int(total_nb_tests),
512 # "success": int(total_success)}
513 # logger.info("Results: "+str(json_results))
515 # Evaluation of the success criteria
517 # for Rally we decided that the overall success rate must be above 90%
518 if float(total_success) >= 90:
522 case_name = "rally_sanity"
524 case_name = "rally_full"
527 logger.debug("Pushing Rally summary into DB...")
528 functest_utils.push_results_to_db("functest",
539 logger.debug("Deleting image '%s' with ID '%s'..."
540 % (GLANCE_IMAGE_NAME, image_id))
541 if not os_utils.delete_glance_image(nova_client, image_id):
542 logger.error("Error deleting the glance image")
545 logger.debug("Deleting volume type '%s'..."
546 % CINDER_VOLUME_TYPE_NAME)
547 if not os_utils.delete_volume_type(cinder_client, volume_type):
548 logger.error("Error in deleting volume type...")
551 if __name__ == '__main__':