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(logger,
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)
197 with open(tempest_conf_file, 'wb') as config_file:
198 config.write(config_file)
200 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
201 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
205 def configure_tempest_feature(deployment_dir, mode):
207 Add/update needed parameters into tempest.conf file generated by Rally
210 logger.debug("Finding tempest.conf file...")
211 tempest_conf_file = deployment_dir + "/tempest.conf"
212 if not os.path.isfile(tempest_conf_file):
213 logger.error("Tempest configuration file %s NOT found."
217 logger.debug("Updating selected tempest.conf parameters...")
218 config = ConfigParser.RawConfigParser()
219 config.read(tempest_conf_file)
220 if mode == 'feature_multisite':
221 config.set('service_available', 'kingbird', 'true')
222 cmd = "openstack endpoint show kingbird | grep publicurl |\
223 awk '{print $4}' | awk -F '/' '{print $3}'"
224 kingbird_api_version = os.popen(cmd).read()
225 if os.environ.get("INSTALLER_TYPE") == 'fuel':
226 # For MOS based setup, the service is accessible
228 kingbird_conf_path = "/etc/kingbird/kingbird.conf"
229 installer_type = os.getenv('INSTALLER_TYPE', 'Unknown')
230 installer_ip = os.getenv('INSTALLER_IP', 'Unknown')
231 installer_username = ft_utils.get_parameter_from_yaml(
232 "multisite." + installer_type +
233 "_environment.installer_username")
234 installer_password = ft_utils.get_parameter_from_yaml(
235 "multisite." + installer_type +
236 "_environment.installer_password")
237 multisite_controller_ip = ft_utils.get_parameter_from_yaml(
238 "multisite." + installer_type +
239 "_environment.multisite_controller_ip")
241 ssh_options = "-o UserKnownHostsFile=/dev/null -o \
242 StrictHostKeyChecking=no"
244 # Get the controller IP from the fuel node
245 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
246 \'fuel node --env 1| grep controller | grep "True\| 1" \
247 | awk -F\| "{print \$5}"\'' % (installer_password,
251 multisite_controller_ip = \
252 "".join(os.popen(cmd).reawd().split())
254 # Login to controller and get bind host details
255 cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s "ssh %s \\" \
256 grep -e "^bind_" %s \\""' % (installer_password,
260 multisite_controller_ip,
262 bind_details = os.popen(cmd).read()
263 bind_details = "".join(bind_details.split())
264 # Extract port number from the bind details
265 bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
266 # Extract ip address from the bind details
267 bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
269 kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
272 cmd = "openstack endpoint show kingbird | grep publicurl |\
273 awk '{print $4}' | awk -F '/' '{print $3}'"
274 kingbird_endpoint_url = os.popen(cmd).read()
277 config.add_section("kingbird")
279 logger.info('kingbird section exist')
280 config.set('kingbird', 'endpoint_type', 'publicURL')
281 config.set('kingbird', 'TIME_TO_SYNC', '20')
282 config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
283 config.set('kingbird', 'api_version', kingbird_api_version)
284 with open(tempest_conf_file, 'wb') as config_file:
285 config.write(config_file)
287 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
288 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
292 def read_file(filename):
293 with open(filename) as src:
294 return [line.strip() for line in src.readlines()]
297 def generate_test_list(deployment_dir, mode):
298 logger.debug("Generating test case list...")
299 if mode == 'defcore':
300 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
301 elif mode == 'custom':
302 if os.path.isfile(TEMPEST_CUSTOM):
303 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
305 logger.error("Tempest test list file %s NOT found."
311 elif mode == 'feature_multisite':
312 testr_mode = " | grep kingbird "
316 testr_mode = 'tempest.api.' + mode
317 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
318 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
319 ft_utils.execute_command(cmd, logger)
322 def apply_tempest_blacklist():
323 logger.debug("Applying tempest blacklist...")
324 cases_file = read_file(TEMPEST_RAW_LIST)
325 result_file = open(TEMPEST_LIST, 'w')
327 black_file = read_file(TEMPEST_BLACKLIST)
330 logger.debug("Tempest blacklist file does not exist.")
331 for line in cases_file:
332 if line not in black_file:
333 result_file.write(str(line) + '\n')
337 def run_tempest(OPTION):
339 # the "main" function of the script which launches Rally to run Tempest
340 # :param option: tempest option (smoke, ..)
343 logger.info("Starting Tempest test suite: '%s'." % OPTION)
344 start_time = time.time()
345 stop_time = start_time
346 cmd_line = "rally verify start " + OPTION + " --system-wide"
348 header = ("Tempest environment:\n"
349 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
350 (os.getenv('INSTALLER_TYPE', 'Unknown'),
351 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
352 os.getenv('NODE_NAME', 'Unknown'),
353 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
355 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
356 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
357 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
360 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
361 p = subprocess.Popen(
362 cmd_line, shell=True,
363 stdout=subprocess.PIPE,
368 for line in iter(p.stdout.readline, b''):
369 if re.search("\} tempest\.", line):
370 logger.info(line.replace('\n', ''))
378 cmd_line = "rally verify show"
380 p = subprocess.Popen(
381 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
382 for line in p.stdout:
383 if re.search("Tests\:", line):
388 cmd_line = "rally verify list"
389 cmd = os.popen(cmd_line)
390 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
392 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
393 # Duration | Status |
394 num_tests = output[4]
395 num_failures = output[5]
396 time_start = output[6]
398 # Compute duration (lets assume it does not take more than 60 min)
399 dur_min = int(duration.split(':')[1])
400 dur_sec_float = float(duration.split(':')[2])
401 dur_sec_int = int(round(dur_sec_float, 0))
402 dur_sec_int = dur_sec_int + 60 * dur_min
403 stop_time = time.time()
404 # Push results in payload of testcase
406 logger.debug("Pushing tempest results into DB...")
407 # Note criteria hardcoded...TODO move to testcase.yaml
410 diff = (int(num_tests) - int(num_failures))
411 success_rate = 100 * diff / int(num_tests)
415 # For Tempest we assume that the success rate is above 90%
416 if success_rate >= 90:
419 # add the test in error in the details sections
420 # should be possible to do it during the test
421 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
422 output = myfile.read()
425 for match in re.findall('(.*?)[. ]*FAILED', output):
428 # Generate json results for DB
429 json_results = {"timestart": time_start, "duration": dur_sec_int,
430 "tests": int(num_tests), "failures": int(num_failures),
431 "errors": error_logs}
432 logger.info("Results: " + str(json_results))
433 # split Tempest smoke and full
434 if "smoke" in args.mode:
435 case_name = "tempest_smoke_serial"
437 case_name = "tempest_full_parallel"
440 ft_utils.push_results_to_db("functest",
448 logger.error("Error pushing results into Database '%s'"
455 if not (args.mode in modes):
456 logger.error("Tempest mode not valid. "
457 "Possible values are:\n" + str(modes))
460 if not os.path.exists(TEMPEST_RESULTS_DIR):
461 os.makedirs(TEMPEST_RESULTS_DIR)
463 deployment_dir = ft_utils.get_deployment_dir(logger)
464 configure_tempest(deployment_dir)
465 configure_tempest_feature(deployment_dir, args.mode)
466 create_tempest_resources()
467 generate_test_list(deployment_dir, args.mode)
468 apply_tempest_blacklist()
470 MODE = "--tests-file " + TEMPEST_LIST
472 MODE += " --concur 1"
477 if __name__ == '__main__':