4 # Runs tempest and pushes the results to the DB
7 # morgan.richomme@orange.com
8 # jose.lausuch@ericsson.com
9 # viktor.tikkanen@nokia.com
11 # All rights reserved. This program and the accompanying materials
12 # are made available under the terms of the Apache License, Version 2.0
13 # which accompanies this distribution, and is available at
14 # http://www.apache.org/licenses/LICENSE-2.0
25 import functest.utils.functest_logger as ft_logger
26 import functest.utils.functest_utils as ft_utils
27 import functest.utils.openstack_utils as os_utils
31 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
32 'identity', 'image', 'network', 'object_storage', 'orchestration',
33 'telemetry', 'volume', 'custom', 'defcore', 'feature_multisite']
35 """ tests configuration """
36 parser = argparse.ArgumentParser()
37 parser.add_argument("-d", "--debug",
40 parser.add_argument("-s", "--serial",
41 help="Run tests in one thread",
43 parser.add_argument("-m", "--mode",
44 help="Tempest test mode [smoke, all]",
46 parser.add_argument("-r", "--report",
47 help="Create json result file",
49 parser.add_argument("-n", "--noclean",
50 help="Don't clean the created resources for this test.",
53 args = parser.parse_args()
55 """ logging configuration """
56 logger = ft_logger.Logger("run_tempest").getLogger()
58 REPO_PATH = os.environ['repos_dir'] + '/functest/'
60 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
61 functest_yaml = yaml.safe_load(f)
63 TEST_DB = functest_yaml.get("results").get("test_db_url")
66 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
67 "openstack").get("image_name")
68 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
69 "openstack").get("image_file_name")
70 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
71 "openstack").get("image_disk_format")
72 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
73 "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
74 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
75 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
76 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
77 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
78 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
79 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
81 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
82 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
84 SSH_TIMEOUT = functest_yaml.get("tempest").get("validation").get(
86 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
87 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
89 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
91 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
92 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
94 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
95 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
96 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
97 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
98 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
101 def get_info(file_result):
106 p = subprocess.Popen('cat tempest.log',
107 shell=True, stdout=subprocess.PIPE,
108 stderr=subprocess.STDOUT)
109 for line in p.stdout.readlines():
111 if (len(test_run) < 1):
112 test_run = re.findall("[0-9]*\.[0-9]*s", line)
113 if (len(duration) < 1):
114 duration = re.findall("[0-9]*\ tests", line)
115 regexp = r"(failures=[0-9]+)"
116 if (len(test_failed) < 1):
117 test_failed = re.findall(regexp, line)
119 logger.debug("test_run:" + test_run)
120 logger.debug("duration:" + duration)
123 def create_tempest_resources():
124 keystone_client = os_utils.get_keystone_client()
125 neutron_client = os_utils.get_neutron_client()
126 glance_client = os_utils.get_glance_client()
128 logger.debug("Creating tenant and user for Tempest suite")
129 tenant_id = os_utils.create_tenant(keystone_client,
133 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
135 user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
138 logger.error("Error : Failed to create %s user" % USER_NAME)
140 logger.debug("Creating private network for Tempest suite")
141 network_dic = os_utils.create_network_full(neutron_client,
147 if not os_utils.update_neutron_net(neutron_client,
148 network_dic['net_id'],
150 logger.error("Failed to update private network...")
153 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
155 logger.error("Private network creation failed")
158 logger.debug("Creating image for Tempest suite")
159 # Check if the given image exists
160 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
162 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
164 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
166 image_id = os_utils.create_glance_image(glance_client,
171 logger.error("Failed to create a Glance image...")
173 logger.debug("Image '%s' with ID=%s created successfully."
174 % (GLANCE_IMAGE_NAME, image_id))
177 def configure_tempest(deployment_dir):
179 Add/update needed parameters into tempest.conf file generated by Rally
182 tempest_conf_file = deployment_dir + "/tempest.conf"
183 if os.path.isfile(tempest_conf_file):
184 logger.debug("Deleting old tempest.conf file...")
185 os.remove(tempest_conf_file)
187 logger.debug("Generating new tempest.conf file...")
188 cmd = "rally verify genconfig"
189 ft_utils.execute_command(cmd, logger)
191 logger.debug("Finding tempest.conf file...")
192 if not os.path.isfile(tempest_conf_file):
193 logger.error("Tempest configuration file %s NOT found."
197 logger.debug("Updating selected tempest.conf parameters...")
198 config = ConfigParser.RawConfigParser()
199 config.read(tempest_conf_file)
200 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
201 config.set('identity', 'tenant_name', TENANT_NAME)
202 config.set('identity', 'username', USER_NAME)
203 config.set('identity', 'password', USER_PASSWORD)
204 config.set('validation', 'ssh_timeout', SSH_TIMEOUT)
206 if os.getenv('OS_ENDPOINT_TYPE') is not None:
207 services_list = ['compute', 'volume', 'image', 'network',
208 'data-processing', 'object-storage', 'orchestration']
209 sections = config.sections()
210 for service in services_list:
211 if service not in sections:
212 config.add_section(service)
213 config.set(service, 'endpoint_type',
214 os.environ.get("OS_ENDPOINT_TYPE"))
216 with open(tempest_conf_file, 'wb') as config_file:
217 config.write(config_file)
219 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
220 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
224 def configure_tempest_feature(deployment_dir, mode):
225 """Add/update needed parameters into tempest.conf file generated by Rally
229 logger.debug("Finding tempest.conf file...")
230 tempest_conf_file = deployment_dir + "/tempest.conf"
231 if not os.path.isfile(tempest_conf_file):
232 logger.error("Tempest configuration file %s NOT found."
236 logger.debug("Updating selected tempest.conf parameters...")
237 config = ConfigParser.RawConfigParser()
238 config.read(tempest_conf_file)
239 if mode == 'feature_multisite':
240 config.set('service_available', 'kingbird', 'true')
241 cmd = "openstack endpoint show kingbird | grep publicurl |\
242 awk '{print $4}' | awk -F '/' '{print $4}'"
243 kingbird_api_version = os.popen(cmd).read()
244 if os.environ.get("INSTALLER_TYPE") == 'fuel':
245 # For MOS based setup, the service is accessible
247 kingbird_conf_path = "/etc/kingbird/kingbird.conf"
248 installer_type = os.getenv('INSTALLER_TYPE', 'Unknown')
249 installer_ip = os.getenv('INSTALLER_IP', 'Unknown')
250 installer_username = ft_utils.get_parameter_from_yaml(
251 "multisite." + installer_type +
252 "_environment.installer_username")
253 installer_password = ft_utils.get_parameter_from_yaml(
254 "multisite." + installer_type +
255 "_environment.installer_password")
257 ssh_options = "-o UserKnownHostsFile=/dev/null -o \
258 StrictHostKeyChecking=no"
260 # Get the controller IP from the fuel node
261 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
262 \'fuel node --env 1| grep controller | grep "True\| 1" \
263 | awk -F\| "{print \$5}"\'' % (installer_password,
267 multisite_controller_ip = \
268 "".join(os.popen(cmd).read().split())
270 # Login to controller and get bind host details
271 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s "ssh %s \\" \
272 grep -e "^bind_" %s \\""' % (installer_password,
276 multisite_controller_ip,
278 bind_details = os.popen(cmd).read()
279 bind_details = "".join(bind_details.split())
280 # Extract port number from the bind details
281 bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
282 # Extract ip address from the bind details
283 bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
285 kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
288 cmd = "openstack endpoint show kingbird | grep publicurl |\
289 awk '{print $4}' | awk -F '/' '{print $3}'"
290 kingbird_endpoint_url = os.popen(cmd).read()
292 config.add_section("kingbird")
294 logger.info('kingbird section exist')
295 config.set('kingbird', 'endpoint_type', 'publicURL')
296 config.set('kingbird', 'TIME_TO_SYNC', '20')
297 config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
298 config.set('kingbird', 'api_version', kingbird_api_version)
299 with open(tempest_conf_file, 'wb') as config_file:
300 config.write(config_file)
302 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
303 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
307 def read_file(filename):
308 with open(filename) as src:
309 return [line.strip() for line in src.readlines()]
312 def generate_test_list(deployment_dir, mode):
313 logger.debug("Generating test case list...")
314 if mode == 'defcore':
315 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
316 elif mode == 'custom':
317 if os.path.isfile(TEMPEST_CUSTOM):
318 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
320 logger.error("Tempest test list file %s NOT found."
326 elif mode == 'feature_multisite':
327 testr_mode = " | grep -i kingbird "
331 testr_mode = 'tempest.api.' + mode
332 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
333 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
334 ft_utils.execute_command(cmd, logger)
337 def apply_tempest_blacklist():
338 logger.debug("Applying tempest blacklist...")
339 cases_file = read_file(TEMPEST_RAW_LIST)
340 result_file = open(TEMPEST_LIST, 'w')
343 installer_type = os.getenv('INSTALLER_TYPE')
344 deploy_scenario = os.getenv('DEPLOY_SCENARIO')
345 if (bool(installer_type) * bool(deploy_scenario)):
346 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
347 black_list_file = open(TEMPEST_BLACKLIST)
348 black_list_yaml = yaml.safe_load(black_list_file)
349 black_list_file.close()
350 for item in black_list_yaml:
351 scenarios = item['scenarios']
352 installers = item['installers']
353 if (deploy_scenario in scenarios and
354 installer_type in installers):
355 tests = item['tests']
357 black_tests.append(test)
361 logger.debug("Tempest blacklist file does not exist.")
363 for cases_line in cases_file:
364 for black_tests_line in black_tests:
365 if black_tests_line in cases_line:
368 result_file.write(str(cases_line) + '\n')
372 def run_tempest(OPTION):
374 # the "main" function of the script which launches Rally to run Tempest
375 # :param option: tempest option (smoke, ..)
378 logger.info("Starting Tempest test suite: '%s'." % OPTION)
379 start_time = time.time()
380 stop_time = start_time
381 cmd_line = "rally verify start " + OPTION + " --system-wide"
383 header = ("Tempest environment:\n"
384 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
385 (os.getenv('INSTALLER_TYPE', 'Unknown'),
386 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
387 os.getenv('NODE_NAME', 'Unknown'),
388 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
390 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
391 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
392 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
395 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
396 p = subprocess.Popen(
397 cmd_line, shell=True,
398 stdout=subprocess.PIPE,
403 for line in iter(p.stdout.readline, b''):
404 if re.search("\} tempest\.", line):
405 logger.info(line.replace('\n', ''))
413 cmd_line = "rally verify show"
415 p = subprocess.Popen(
416 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
417 for line in p.stdout:
418 if re.search("Tests\:", line):
423 cmd_line = "rally verify list"
424 cmd = os.popen(cmd_line)
425 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
427 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
428 # Duration | Status |
429 num_tests = output[4]
430 num_failures = output[5]
431 time_start = output[6]
433 # Compute duration (lets assume it does not take more than 60 min)
434 dur_min = int(duration.split(':')[1])
435 dur_sec_float = float(duration.split(':')[2])
436 dur_sec_int = int(round(dur_sec_float, 0))
437 dur_sec_int = dur_sec_int + 60 * dur_min
438 stop_time = time.time()
441 diff = (int(num_tests) - int(num_failures))
442 success_rate = 100 * diff / int(num_tests)
446 if 'smoke' in args.mode:
447 case_name = 'tempest_smoke_serial'
449 case_name = 'tempest_full_parallel'
451 status = ft_utils.check_success_rate(case_name, success_rate)
452 logger.info("Tempest %s success_rate is %s%%, is marked as %s"
453 % (case_name, success_rate, status))
455 # Push results in payload of testcase
457 # add the test in error in the details sections
458 # should be possible to do it during the test
459 logger.debug("Pushing tempest results into DB...")
460 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
461 output = myfile.read()
464 for match in re.findall('(.*?)[. ]*FAILED', output):
467 # Generate json results for DB
468 json_results = {"timestart": time_start, "duration": dur_sec_int,
469 "tests": int(num_tests), "failures": int(num_failures),
470 "errors": error_logs}
471 logger.info("Results: " + str(json_results))
472 # split Tempest smoke and full
475 ft_utils.push_results_to_db("functest",
483 logger.error("Error pushing results into Database '%s'"
495 if not (args.mode in modes):
496 logger.error("Tempest mode not valid. "
497 "Possible values are:\n" + str(modes))
500 if not os.path.exists(TEMPEST_RESULTS_DIR):
501 os.makedirs(TEMPEST_RESULTS_DIR)
503 deployment_dir = ft_utils.get_deployment_dir(logger)
504 configure_tempest(deployment_dir)
505 configure_tempest_feature(deployment_dir, args.mode)
506 create_tempest_resources()
507 generate_test_list(deployment_dir, args.mode)
508 apply_tempest_blacklist()
510 MODE = "--tests-file " + TEMPEST_LIST
512 MODE += " --concur 1"
514 ret_val = run_tempest(MODE)
521 if __name__ == '__main__':