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 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
85 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
87 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
89 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
90 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
92 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
93 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
94 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
95 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
96 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
99 def get_info(file_result):
104 p = subprocess.Popen('cat tempest.log',
105 shell=True, stdout=subprocess.PIPE,
106 stderr=subprocess.STDOUT)
107 for line in p.stdout.readlines():
109 if (len(test_run) < 1):
110 test_run = re.findall("[0-9]*\.[0-9]*s", line)
111 if (len(duration) < 1):
112 duration = re.findall("[0-9]*\ tests", line)
113 regexp = r"(failures=[0-9]+)"
114 if (len(test_failed) < 1):
115 test_failed = re.findall(regexp, line)
117 logger.debug("test_run:" + test_run)
118 logger.debug("duration:" + duration)
121 def create_tempest_resources():
122 keystone_client = os_utils.get_keystone_client()
123 neutron_client = os_utils.get_neutron_client()
124 glance_client = os_utils.get_glance_client()
126 logger.debug("Creating tenant and user for Tempest suite")
127 tenant_id = os_utils.create_tenant(keystone_client,
131 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
133 user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
136 logger.error("Error : Failed to create %s user" % USER_NAME)
138 logger.debug("Creating private network for Tempest suite")
139 network_dic = os_utils.create_network_full(neutron_client,
145 if not os_utils.update_neutron_net(neutron_client,
146 network_dic['net_id'],
148 logger.error("Failed to update private network...")
151 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
153 logger.error("Private network creation failed")
156 logger.debug("Creating image for Tempest suite")
157 # Check if the given image exists
158 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
160 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
162 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
164 image_id = os_utils.create_glance_image(glance_client,
168 logger.error("Failed to create a Glance image...")
170 logger.debug("Image '%s' with ID=%s created successfully."
171 % (GLANCE_IMAGE_NAME, image_id))
174 def configure_tempest(deployment_dir):
176 Add/update needed parameters into tempest.conf file generated by Rally
179 logger.debug("Generating tempest.conf file...")
180 cmd = "rally verify genconfig"
181 ft_utils.execute_command(cmd, logger)
183 logger.debug("Finding tempest.conf file...")
184 tempest_conf_file = deployment_dir + "/tempest.conf"
185 if not os.path.isfile(tempest_conf_file):
186 logger.error("Tempest configuration file %s NOT found."
190 logger.debug("Updating selected tempest.conf parameters...")
191 config = ConfigParser.RawConfigParser()
192 config.read(tempest_conf_file)
193 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
194 config.set('identity', 'tenant_name', TENANT_NAME)
195 config.set('identity', 'username', USER_NAME)
196 config.set('identity', 'password', USER_PASSWORD)
198 if os.getenv('OS_ENDPOINT_TYPE') is not None:
199 services_list = ['compute', 'volume', 'image', 'network',
200 'data-processing', 'object-storage', 'orchestration']
201 sections = config.sections()
202 for service in services_list:
203 if service not in sections:
204 config.add_section(service)
205 config.set(service, 'endpoint_type',
206 os.environ.get("OS_ENDPOINT_TYPE"))
208 with open(tempest_conf_file, 'wb') as config_file:
209 config.write(config_file)
211 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
212 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
216 def configure_tempest_feature(deployment_dir, mode):
217 """Add/update needed parameters into tempest.conf file generated by Rally
221 logger.debug("Finding tempest.conf file...")
222 tempest_conf_file = deployment_dir + "/tempest.conf"
223 if not os.path.isfile(tempest_conf_file):
224 logger.error("Tempest configuration file %s NOT found."
228 logger.debug("Updating selected tempest.conf parameters...")
229 config = ConfigParser.RawConfigParser()
230 config.read(tempest_conf_file)
231 if mode == 'feature_multisite':
232 config.set('service_available', 'kingbird', 'true')
233 cmd = "openstack endpoint show kingbird | grep publicurl |\
235 kingbird_endpoint_details = "".join(os.popen(cmd).read().split())
236 kingbird_endpoint_url = kingbird_endpoint_details.rsplit('/', 1)[0] + \
238 kingbird_api_version = kingbird_endpoint_details.rsplit('/', 1)[1]
240 config.add_section("kingbird")
242 logger.info('kingbird section exist')
243 config.set('kingbird', 'endpoint_type', 'publicURL')
244 config.set('kingbird', 'TIME_TO_SYNC', '20')
245 config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
246 config.set('kingbird', 'api_version', kingbird_api_version)
247 with open(tempest_conf_file, 'wb') as config_file:
248 config.write(config_file)
250 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
251 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
255 def read_file(filename):
256 with open(filename) as src:
257 return [line.strip() for line in src.readlines()]
260 def generate_test_list(deployment_dir, mode):
261 logger.debug("Generating test case list...")
262 if mode == 'defcore':
263 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
264 elif mode == 'custom':
265 if os.path.isfile(TEMPEST_CUSTOM):
266 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
268 logger.error("Tempest test list file %s NOT found."
274 elif mode == 'feature_multisite':
275 testr_mode = " | grep -i kingbird "
279 testr_mode = 'tempest.api.' + mode
280 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
281 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
282 ft_utils.execute_command(cmd, logger)
285 def apply_tempest_blacklist():
286 logger.debug("Applying tempest blacklist...")
287 cases_file = read_file(TEMPEST_RAW_LIST)
288 result_file = open(TEMPEST_LIST, 'w')
291 installer_type = os.getenv('INSTALLER_TYPE')
292 deploy_scenario = os.getenv('DEPLOY_SCENARIO')
293 if (bool(installer_type) * bool(deploy_scenario)):
294 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
295 black_list_file = open(TEMPEST_BLACKLIST)
296 black_list_yaml = yaml.safe_load(black_list_file)
297 black_list_file.close()
298 for item in black_list_yaml:
299 scenarios = item['scenarios']
300 installers = item['installers']
301 if (deploy_scenario in scenarios and
302 installer_type in installers):
303 tests = item['tests']
305 black_tests.append(test)
309 logger.debug("Tempest blacklist file does not exist.")
311 for cases_line in cases_file:
312 for black_tests_line in black_tests:
313 if black_tests_line in cases_line:
316 result_file.write(str(cases_line) + '\n')
320 def run_tempest(OPTION):
322 # the "main" function of the script which launches Rally to run Tempest
323 # :param option: tempest option (smoke, ..)
326 logger.info("Starting Tempest test suite: '%s'." % OPTION)
327 start_time = time.time()
328 stop_time = start_time
329 cmd_line = "rally verify start " + OPTION + " --system-wide"
331 header = ("Tempest environment:\n"
332 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
333 (os.getenv('INSTALLER_TYPE', 'Unknown'),
334 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
335 os.getenv('NODE_NAME', 'Unknown'),
336 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
338 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
339 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
340 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
343 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
344 p = subprocess.Popen(
345 cmd_line, shell=True,
346 stdout=subprocess.PIPE,
351 for line in iter(p.stdout.readline, b''):
352 if re.search("\} tempest\.", line):
353 logger.info(line.replace('\n', ''))
361 cmd_line = "rally verify show"
363 p = subprocess.Popen(
364 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
365 for line in p.stdout:
366 if re.search("Tests\:", line):
371 cmd_line = "rally verify list"
372 cmd = os.popen(cmd_line)
373 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
375 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
376 # Duration | Status |
377 num_tests = output[4]
378 num_failures = output[5]
379 time_start = output[6]
381 # Compute duration (lets assume it does not take more than 60 min)
382 dur_min = int(duration.split(':')[1])
383 dur_sec_float = float(duration.split(':')[2])
384 dur_sec_int = int(round(dur_sec_float, 0))
385 dur_sec_int = dur_sec_int + 60 * dur_min
386 stop_time = time.time()
389 diff = (int(num_tests) - int(num_failures))
390 success_rate = 100 * diff / int(num_tests)
394 if 'smoke' in args.mode:
395 case_name = 'tempest_smoke_serial'
397 case_name = 'tempest_full_parallel'
399 status = ft_utils.check_success_rate(case_name, success_rate)
400 logger.info("Tempest %s success_rate is %s%%, is marked as %s"
401 % (case_name, success_rate, status))
403 # Push results in payload of testcase
405 # add the test in error in the details sections
406 # should be possible to do it during the test
407 logger.debug("Pushing tempest results into DB...")
408 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
409 output = myfile.read()
412 for match in re.findall('(.*?)[. ]*FAILED', output):
415 # Generate json results for DB
416 json_results = {"timestart": time_start, "duration": dur_sec_int,
417 "tests": int(num_tests), "failures": int(num_failures),
418 "errors": error_logs}
419 logger.info("Results: " + str(json_results))
420 # split Tempest smoke and full
423 ft_utils.push_results_to_db("functest",
431 logger.error("Error pushing results into Database '%s'"
443 if not (args.mode in modes):
444 logger.error("Tempest mode not valid. "
445 "Possible values are:\n" + str(modes))
448 if not os.path.exists(TEMPEST_RESULTS_DIR):
449 os.makedirs(TEMPEST_RESULTS_DIR)
451 deployment_dir = ft_utils.get_deployment_dir(logger)
452 configure_tempest(deployment_dir)
453 configure_tempest_feature(deployment_dir, args.mode)
454 create_tempest_resources()
455 generate_test_list(deployment_dir, args.mode)
456 apply_tempest_blacklist()
458 MODE = "--tests-file " + TEMPEST_LIST
460 MODE += " --concur 1"
462 ret_val = run_tempest(MODE)
469 if __name__ == '__main__':