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
30 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
31 'identity', 'image', 'network', 'object_storage', 'orchestration',
32 'telemetry', 'volume', 'custom', 'defcore', 'feature_multisite']
34 """ tests configuration """
35 parser = argparse.ArgumentParser()
36 parser.add_argument("-d", "--debug",
39 parser.add_argument("-s", "--serial",
40 help="Run tests in one thread",
42 parser.add_argument("-m", "--mode",
43 help="Tempest test mode [smoke, all]",
45 parser.add_argument("-r", "--report",
46 help="Create json result file",
48 parser.add_argument("-n", "--noclean",
49 help="Don't clean the created resources for this test.",
52 args = parser.parse_args()
54 """ logging configuration """
55 logger = ft_logger.Logger("run_tempest").getLogger()
57 REPO_PATH = os.environ['repos_dir'] + '/functest/'
59 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
60 functest_yaml = yaml.safe_load(f)
62 TEST_DB = functest_yaml.get("results").get("test_db_url")
65 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
66 "openstack").get("image_name")
67 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
68 "openstack").get("image_file_name")
69 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
70 "openstack").get("image_disk_format")
71 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
72 "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
73 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
74 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
75 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
76 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
77 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
78 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
80 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
81 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
83 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
84 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
86 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
88 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
89 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
91 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
92 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
93 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
94 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
95 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
98 def get_info(file_result):
103 p = subprocess.Popen('cat tempest.log',
104 shell=True, stdout=subprocess.PIPE,
105 stderr=subprocess.STDOUT)
106 for line in p.stdout.readlines():
108 if (len(test_run) < 1):
109 test_run = re.findall("[0-9]*\.[0-9]*s", line)
110 if (len(duration) < 1):
111 duration = re.findall("[0-9]*\ tests", line)
112 regexp = r"(failures=[0-9]+)"
113 if (len(test_failed) < 1):
114 test_failed = re.findall(regexp, line)
116 logger.debug("test_run:" + test_run)
117 logger.debug("duration:" + duration)
120 def create_tempest_resources():
121 keystone_client = os_utils.get_keystone_client()
122 neutron_client = os_utils.get_neutron_client()
123 glance_client = os_utils.get_glance_client()
125 logger.debug("Creating tenant and user for Tempest suite")
126 tenant_id = os_utils.create_tenant(keystone_client,
130 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
132 user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
135 logger.error("Error : Failed to create %s user" % USER_NAME)
137 logger.debug("Creating private network for Tempest suite")
138 network_dic = os_utils.create_network_full(neutron_client,
144 if not os_utils.update_neutron_net(neutron_client,
145 network_dic['net_id'],
147 logger.error("Failed to update private network...")
150 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
152 logger.error("Private network creation failed")
155 logger.debug("Creating image for Tempest suite")
156 # Check if the given image exists
157 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
159 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
161 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
163 image_id = os_utils.create_glance_image(glance_client,
167 logger.error("Failed to create a Glance image...")
169 logger.debug("Image '%s' with ID=%s created successfully."
170 % (GLANCE_IMAGE_NAME, image_id))
173 def configure_tempest(deployment_dir):
175 Add/update needed parameters into tempest.conf file generated by Rally
178 logger.debug("Generating tempest.conf file...")
179 cmd = "rally verify genconfig"
180 ft_utils.execute_command(cmd, logger)
182 logger.debug("Finding tempest.conf file...")
183 tempest_conf_file = deployment_dir + "/tempest.conf"
184 if not os.path.isfile(tempest_conf_file):
185 logger.error("Tempest configuration file %s NOT found."
189 logger.debug("Updating selected tempest.conf parameters...")
190 config = ConfigParser.RawConfigParser()
191 config.read(tempest_conf_file)
192 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
193 config.set('identity', 'tenant_name', TENANT_NAME)
194 config.set('identity', 'username', USER_NAME)
195 config.set('identity', 'password', USER_PASSWORD)
196 with open(tempest_conf_file, 'wb') as config_file:
197 config.write(config_file)
199 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
200 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
204 def configure_tempest_feature(deployment_dir, mode):
206 Add/update needed parameters into tempest.conf file generated by Rally
209 logger.debug("Finding tempest.conf file...")
210 tempest_conf_file = deployment_dir + "/tempest.conf"
211 if not os.path.isfile(tempest_conf_file):
212 logger.error("Tempest configuration file %s NOT found."
216 logger.debug("Updating selected tempest.conf parameters...")
217 config = ConfigParser.RawConfigParser()
218 config.read(tempest_conf_file)
219 if mode == 'feature_multisite':
220 config.set('service_available', 'kingbird', 'true')
221 cmd = "openstack endpoint show kingbird | grep publicurl |\
222 awk '{print $4}' | awk -F '/' '{print $4}'"
223 kingbird_api_version = os.popen(cmd).read()
224 if os.environ.get("INSTALLER_TYPE") == 'fuel':
225 # For MOS based setup, the service is accessible
227 kingbird_conf_path = "/etc/kingbird/kingbird.conf"
228 installer_type = os.getenv('INSTALLER_TYPE', 'Unknown')
229 installer_ip = os.getenv('INSTALLER_IP', 'Unknown')
230 installer_username = ft_utils.get_parameter_from_yaml(
231 "multisite." + installer_type +
232 "_environment.installer_username")
233 installer_password = ft_utils.get_parameter_from_yaml(
234 "multisite." + installer_type +
235 "_environment.installer_password")
236 multisite_controller_ip = ft_utils.get_parameter_from_yaml(
237 "multisite." + installer_type +
238 "_environment.multisite_controller_ip")
240 ssh_options = "-o UserKnownHostsFile=/dev/null -o \
241 StrictHostKeyChecking=no"
243 # Get the controller IP from the fuel node
244 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
245 \'fuel node --env 1| grep controller | grep "True\| 1" \
246 | awk -F\| "{print \$5}"\'' % (installer_password,
250 multisite_controller_ip = \
251 "".join(os.popen(cmd).reawd().split())
253 # Login to controller and get bind host details
254 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s "ssh %s \\" \
255 grep -e "^bind_" %s \\""' % (installer_password,
259 multisite_controller_ip,
261 bind_details = os.popen(cmd).read()
262 bind_details = "".join(bind_details.split())
263 # Extract port number from the bind details
264 bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
265 # Extract ip address from the bind details
266 bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
268 kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
271 cmd = "openstack endpoint show kingbird | grep publicurl |\
272 awk '{print $4}' | awk -F '/' '{print $3}'"
273 kingbird_endpoint_url = os.popen(cmd).read()
276 config.add_section("kingbird")
278 logger.info('kingbird section exist')
279 config.set('kingbird', 'endpoint_type', 'publicURL')
280 config.set('kingbird', 'TIME_TO_SYNC', '20')
281 config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
282 config.set('kingbird', 'api_version', kingbird_api_version)
283 with open(tempest_conf_file, 'wb') as config_file:
284 config.write(config_file)
286 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
287 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
291 def read_file(filename):
292 with open(filename) as src:
293 return [line.strip() for line in src.readlines()]
296 def generate_test_list(deployment_dir, mode):
297 logger.debug("Generating test case list...")
298 if mode == 'defcore':
299 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
300 elif mode == 'custom':
301 if os.path.isfile(TEMPEST_CUSTOM):
302 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
304 logger.error("Tempest test list file %s NOT found."
310 elif mode == 'feature_multisite':
311 testr_mode = " | grep kingbird "
315 testr_mode = 'tempest.api.' + mode
316 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
317 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
318 ft_utils.execute_command(cmd, logger)
321 def apply_tempest_blacklist():
322 logger.debug("Applying tempest blacklist...")
323 cases_file = read_file(TEMPEST_RAW_LIST)
324 result_file = open(TEMPEST_LIST, 'w')
326 black_file = read_file(TEMPEST_BLACKLIST)
329 logger.debug("Tempest blacklist file does not exist.")
330 for line in cases_file:
331 if line not in black_file:
332 result_file.write(str(line) + '\n')
336 def run_tempest(OPTION):
338 # the "main" function of the script which launches Rally to run Tempest
339 # :param option: tempest option (smoke, ..)
342 logger.info("Starting Tempest test suite: '%s'." % OPTION)
343 start_time = time.time()
344 stop_time = start_time
345 cmd_line = "rally verify start " + OPTION + " --system-wide"
347 header = ("Tempest environment:\n"
348 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
349 (os.getenv('INSTALLER_TYPE', 'Unknown'),
350 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
351 os.getenv('NODE_NAME', 'Unknown'),
352 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
354 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
355 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
356 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
359 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
360 p = subprocess.Popen(
361 cmd_line, shell=True,
362 stdout=subprocess.PIPE,
367 for line in iter(p.stdout.readline, b''):
368 if re.search("\} tempest\.", line):
369 logger.info(line.replace('\n', ''))
377 cmd_line = "rally verify show"
379 p = subprocess.Popen(
380 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
381 for line in p.stdout:
382 if re.search("Tests\:", line):
387 cmd_line = "rally verify list"
388 cmd = os.popen(cmd_line)
389 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
391 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
392 # Duration | Status |
393 num_tests = output[4]
394 num_failures = output[5]
395 time_start = output[6]
397 # Compute duration (lets assume it does not take more than 60 min)
398 dur_min = int(duration.split(':')[1])
399 dur_sec_float = float(duration.split(':')[2])
400 dur_sec_int = int(round(dur_sec_float, 0))
401 dur_sec_int = dur_sec_int + 60 * dur_min
402 stop_time = time.time()
406 diff = (int(num_tests) - int(num_failures))
407 success_rate = 100 * diff / int(num_tests)
411 # For Tempest we assume that the success rate is above 90%
412 if "smoke" in args.mode:
413 case_name = "tempest_smoke_serial"
414 # Note criteria hardcoded...TODO read it from testcases.yaml
415 success_criteria = 100
416 if success_rate >= success_criteria:
419 logger.info("Tempest success rate: %s%%. The success criteria to "
420 "pass this test is %s%%. Marking the test as FAILED." %
421 (success_rate, success_criteria))
423 case_name = "tempest_full_parallel"
424 # Note criteria hardcoded...TODO read it from testcases.yaml
425 success_criteria = 80
426 if success_rate >= success_criteria:
429 logger.info("Tempest success rate: %s%%. The success criteria to "
430 "pass this test is %s%%. Marking the test as FAILED." %
431 (success_rate, success_criteria))
433 # Push results in payload of testcase
435 # add the test in error in the details sections
436 # should be possible to do it during the test
437 logger.debug("Pushing tempest results into DB...")
438 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
439 output = myfile.read()
442 for match in re.findall('(.*?)[. ]*FAILED', output):
445 # Generate json results for DB
446 json_results = {"timestart": time_start, "duration": dur_sec_int,
447 "tests": int(num_tests), "failures": int(num_failures),
448 "errors": error_logs}
449 logger.info("Results: " + str(json_results))
450 # split Tempest smoke and full
453 ft_utils.push_results_to_db("functest",
461 logger.error("Error pushing results into Database '%s'"
473 if not (args.mode in modes):
474 logger.error("Tempest mode not valid. "
475 "Possible values are:\n" + str(modes))
478 if not os.path.exists(TEMPEST_RESULTS_DIR):
479 os.makedirs(TEMPEST_RESULTS_DIR)
481 deployment_dir = ft_utils.get_deployment_dir(logger)
482 configure_tempest(deployment_dir)
483 configure_tempest_feature(deployment_dir, args.mode)
484 create_tempest_resources()
485 generate_test_list(deployment_dir, args.mode)
486 apply_tempest_blacklist()
488 MODE = "--tests-file " + TEMPEST_LIST
490 MODE += " --concur 1"
492 ret_val = run_tempest(MODE)
499 if __name__ == '__main__':