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/'
61 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
62 functest_yaml = yaml.safe_load(f)
64 TEST_DB = functest_yaml.get("results").get("test_db_url")
67 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
68 "openstack").get("image_name")
69 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
70 "openstack").get("image_file_name")
71 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
72 "openstack").get("image_disk_format")
73 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
74 "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
75 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
76 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
77 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
78 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
79 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
80 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
82 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
83 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
85 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
86 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
88 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
90 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
91 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
93 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
94 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
95 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
96 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
97 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
100 def get_info(file_result):
105 p = subprocess.Popen('cat tempest.log',
106 shell=True, stdout=subprocess.PIPE,
107 stderr=subprocess.STDOUT)
108 for line in p.stdout.readlines():
110 if (len(test_run) < 1):
111 test_run = re.findall("[0-9]*\.[0-9]*s", line)
112 if (len(duration) < 1):
113 duration = re.findall("[0-9]*\ tests", line)
114 regexp = r"(failures=[0-9]+)"
115 if (len(test_failed) < 1):
116 test_failed = re.findall(regexp, line)
118 logger.debug("test_run:" + test_run)
119 logger.debug("duration:" + duration)
122 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(logger,
148 if not os_utils.update_neutron_net(neutron_client,
149 network_dic['net_id'],
151 logger.error("Failed to update private network...")
154 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
156 logger.error("Private network creation failed")
159 logger.debug("Creating image for Tempest suite")
160 # Check if the given image exists
161 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
163 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
165 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
167 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 logger.debug("Generating tempest.conf file...")
183 cmd = "rally verify genconfig"
184 ft_utils.execute_command(cmd, logger)
186 logger.debug("Finding tempest.conf file...")
187 tempest_conf_file = deployment_dir + "/tempest.conf"
188 if not os.path.isfile(tempest_conf_file):
189 logger.error("Tempest configuration file %s NOT found."
193 logger.debug("Updating selected tempest.conf parameters...")
194 config = ConfigParser.RawConfigParser()
195 config.read(tempest_conf_file)
196 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
197 config.set('identity', 'tenant_name', TENANT_NAME)
198 config.set('identity', 'username', USER_NAME)
199 config.set('identity', 'password', USER_PASSWORD)
200 with open(tempest_conf_file, 'wb') as config_file:
201 config.write(config_file)
203 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
204 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
208 def configure_tempest_feature(deployment_dir, mode):
210 Add/update needed parameters into tempest.conf file generated by Rally
213 logger.debug("Finding tempest.conf file...")
214 tempest_conf_file = deployment_dir + "/tempest.conf"
215 if not os.path.isfile(tempest_conf_file):
216 logger.error("Tempest configuration file %s NOT found."
220 logger.debug("Updating selected tempest.conf parameters...")
221 config = ConfigParser.RawConfigParser()
222 config.read(tempest_conf_file)
223 if mode == 'feature_multisite':
224 config.set('service_available', 'kingbird', 'true')
225 cmd = "openstack endpoint show kingbird | grep publicurl |\
226 awk '{print $4}' | awk -F '/' '{print $3}'"
227 kingbird_endpoint_url = os.popen(cmd).read()
228 cmd = "openstack endpoint show kingbird | grep publicurl |\
229 awk '{print $4}' | awk -F '/' '{print $4}'"
230 kingbird_api_version = os.popen(cmd).read()
232 config.add_section("kingbird")
234 logger.info('kingbird section exist')
235 config.set('kingbird', 'endpoint_type', 'publicURL')
236 config.set('kingbird', 'TIME_TO_SYNC', '20')
237 config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
238 config.set('kingbird', 'api_version', kingbird_api_version)
239 with open(tempest_conf_file, 'wb') as config_file:
240 config.write(config_file)
242 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
243 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
247 def read_file(filename):
248 with open(filename) as src:
249 return [line.strip() for line in src.readlines()]
252 def generate_test_list(deployment_dir, mode):
253 logger.debug("Generating test case list...")
254 if mode == 'defcore':
255 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
256 elif mode == 'custom':
257 if os.path.isfile(TEMPEST_CUSTOM):
258 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
260 logger.error("Tempest test list file %s NOT found."
266 elif mode == 'feature_multisite':
267 testr_mode = " | grep kingbird "
271 testr_mode = 'tempest.api.' + mode
272 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
273 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
274 ft_utils.execute_command(cmd, logger)
277 def apply_tempest_blacklist():
278 logger.debug("Applying tempest blacklist...")
279 cases_file = read_file(TEMPEST_RAW_LIST)
280 result_file = open(TEMPEST_LIST, 'w')
282 black_file = read_file(TEMPEST_BLACKLIST)
285 logger.debug("Tempest blacklist file does not exist.")
286 for line in cases_file:
287 if line not in black_file:
288 result_file.write(str(line) + '\n')
292 def run_tempest(OPTION):
294 # the "main" function of the script which launches Rally to run Tempest
295 # :param option: tempest option (smoke, ..)
298 logger.info("Starting Tempest test suite: '%s'." % OPTION)
299 start_time = time.time()
300 stop_time = start_time
301 cmd_line = "rally verify start " + OPTION + " --system-wide"
303 header = ("Tempest environment:\n"
304 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
305 (os.getenv('INSTALLER_TYPE', 'Unknown'),
306 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
307 os.getenv('NODE_NAME', 'Unknown'),
308 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
310 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
311 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
312 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
315 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
316 p = subprocess.Popen(
317 cmd_line, shell=True,
318 stdout=subprocess.PIPE,
323 for line in iter(p.stdout.readline, b''):
324 if re.search("\} tempest\.", line):
325 logger.info(line.replace('\n', ''))
333 cmd_line = "rally verify show"
335 p = subprocess.Popen(
336 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
337 for line in p.stdout:
338 if re.search("Tests\:", line):
343 cmd_line = "rally verify list"
344 cmd = os.popen(cmd_line)
345 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
347 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
348 # Duration | Status |
349 num_tests = output[4]
350 num_failures = output[5]
351 time_start = output[6]
353 # Compute duration (lets assume it does not take more than 60 min)
354 dur_min = int(duration.split(':')[1])
355 dur_sec_float = float(duration.split(':')[2])
356 dur_sec_int = int(round(dur_sec_float, 0))
357 dur_sec_int = dur_sec_int + 60 * dur_min
358 stop_time = time.time()
359 # Push results in payload of testcase
361 logger.debug("Pushing tempest results into DB...")
362 # Note criteria hardcoded...TODO move to testcase.yaml
365 diff = (int(num_tests) - int(num_failures))
366 success_rate = 100 * diff / int(num_tests)
370 # For Tempest we assume that the success rate is above 90%
371 if success_rate >= 90:
374 # add the test in error in the details sections
375 # should be possible to do it during the test
376 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
377 output = myfile.read()
380 for match in re.findall('(.*?)[. ]*FAILED', output):
383 # Generate json results for DB
384 json_results = {"timestart": time_start, "duration": dur_sec_int,
385 "tests": int(num_tests), "failures": int(num_failures),
386 "errors": error_logs}
387 logger.info("Results: " + str(json_results))
388 # split Tempest smoke and full
389 if "smoke" in args.mode:
390 case_name = "tempest_smoke_serial"
392 case_name = "tempest_full_parallel"
395 ft_utils.push_results_to_db("functest",
403 logger.error("Error pushing results into Database '%s'"
410 if not (args.mode in modes):
411 logger.error("Tempest mode not valid. "
412 "Possible values are:\n" + str(modes))
415 if not os.path.exists(TEMPEST_RESULTS_DIR):
416 os.makedirs(TEMPEST_RESULTS_DIR)
418 deployment_dir = ft_utils.get_deployment_dir(logger)
419 configure_tempest(deployment_dir)
420 configure_tempest_feature(deployment_dir, args.mode)
421 create_tempest_resources()
422 generate_test_list(deployment_dir, args.mode)
423 apply_tempest_blacklist()
425 MODE = "--tests-file " + TEMPEST_LIST
427 MODE += " --concur 1"
432 if __name__ == '__main__':