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.",
52 parser.add_argument("-c", "--conf",
53 help="User-specified Tempest config file location",
56 args = parser.parse_args()
58 """ logging configuration """
59 logger = ft_logger.Logger("run_tempest").getLogger()
61 REPO_PATH = os.environ['repos_dir'] + '/functest/'
63 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
64 functest_yaml = yaml.safe_load(f)
66 TEST_DB = functest_yaml.get("results").get("test_db_url")
69 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
70 "openstack").get("image_name")
71 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
72 "openstack").get("image_file_name")
73 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
74 "openstack").get("image_disk_format")
75 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
76 "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
77 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
78 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
79 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
80 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
81 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
82 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
84 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
85 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
87 SSH_TIMEOUT = functest_yaml.get("tempest").get("validation").get(
89 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
90 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
92 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
94 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
95 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
97 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
98 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
99 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
100 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
101 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
104 def get_info(file_result):
109 p = subprocess.Popen('cat tempest.log',
110 shell=True, stdout=subprocess.PIPE,
111 stderr=subprocess.STDOUT)
112 for line in p.stdout.readlines():
114 if (len(test_run) < 1):
115 test_run = re.findall("[0-9]*\.[0-9]*s", line)
116 if (len(duration) < 1):
117 duration = re.findall("[0-9]*\ tests", line)
118 regexp = r"(failures=[0-9]+)"
119 if (len(test_failed) < 1):
120 test_failed = re.findall(regexp, line)
122 logger.debug("test_run:" + test_run)
123 logger.debug("duration:" + duration)
126 def create_tempest_resources():
127 keystone_client = os_utils.get_keystone_client()
128 neutron_client = os_utils.get_neutron_client()
129 glance_client = os_utils.get_glance_client()
131 logger.debug("Creating tenant and user for Tempest suite")
132 tenant_id = os_utils.create_tenant(keystone_client,
136 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
138 user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
141 logger.error("Error : Failed to create %s user" % USER_NAME)
143 logger.debug("Creating private network for Tempest suite")
144 network_dic = os_utils.create_network_full(neutron_client,
150 if not os_utils.update_neutron_net(neutron_client,
151 network_dic['net_id'],
153 logger.error("Failed to update private network...")
156 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
158 logger.error("Private network creation failed")
161 logger.debug("Creating image for Tempest suite")
162 # Check if the given image exists
163 image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
165 logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
167 logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
169 image_id = os_utils.create_glance_image(glance_client,
174 logger.error("Failed to create a Glance image...")
176 logger.debug("Image '%s' with ID=%s created successfully."
177 % (GLANCE_IMAGE_NAME, image_id))
180 def configure_tempest(deployment_dir):
182 Add/update needed parameters into tempest.conf file generated by Rally
185 tempest_conf_file = deployment_dir + "/tempest.conf"
186 if os.path.isfile(tempest_conf_file):
187 logger.debug("Deleting old tempest.conf file...")
188 os.remove(tempest_conf_file)
190 logger.debug("Generating new tempest.conf file...")
191 cmd = "rally verify genconfig"
192 ft_utils.execute_command(cmd, logger)
194 logger.debug("Finding tempest.conf file...")
195 if not os.path.isfile(tempest_conf_file):
196 logger.error("Tempest configuration file %s NOT found."
200 logger.debug("Updating selected tempest.conf parameters...")
201 config = ConfigParser.RawConfigParser()
202 config.read(tempest_conf_file)
203 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
204 config.set('identity', 'tenant_name', TENANT_NAME)
205 config.set('identity', 'username', USER_NAME)
206 config.set('identity', 'password', USER_PASSWORD)
207 config.set('validation', 'ssh_timeout', SSH_TIMEOUT)
209 if os.getenv('OS_ENDPOINT_TYPE') is not None:
210 services_list = ['compute', 'volume', 'image', 'network',
211 'data-processing', 'object-storage', 'orchestration']
212 sections = config.sections()
213 for service in services_list:
214 if service not in sections:
215 config.add_section(service)
216 config.set(service, 'endpoint_type',
217 os.environ.get("OS_ENDPOINT_TYPE"))
219 with open(tempest_conf_file, 'wb') as config_file:
220 config.write(config_file)
222 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
223 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
227 def read_file(filename):
228 with open(filename) as src:
229 return [line.strip() for line in src.readlines()]
232 def generate_test_list(deployment_dir, mode):
233 logger.debug("Generating test case list...")
234 if mode == 'defcore':
235 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
236 elif mode == 'custom':
237 if os.path.isfile(TEMPEST_CUSTOM):
238 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
240 logger.error("Tempest test list file %s NOT found."
246 elif mode == 'feature_multisite':
247 testr_mode = " | grep -i kingbird "
251 testr_mode = 'tempest.api.' + mode
252 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
253 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
254 ft_utils.execute_command(cmd, logger)
257 def apply_tempest_blacklist():
258 logger.debug("Applying tempest blacklist...")
259 cases_file = read_file(TEMPEST_RAW_LIST)
260 result_file = open(TEMPEST_LIST, 'w')
263 installer_type = os.getenv('INSTALLER_TYPE')
264 deploy_scenario = os.getenv('DEPLOY_SCENARIO')
265 if (bool(installer_type) * bool(deploy_scenario)):
266 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
267 black_list_file = open(TEMPEST_BLACKLIST)
268 black_list_yaml = yaml.safe_load(black_list_file)
269 black_list_file.close()
270 for item in black_list_yaml:
271 scenarios = item['scenarios']
272 installers = item['installers']
273 if (deploy_scenario in scenarios and
274 installer_type in installers):
275 tests = item['tests']
277 black_tests.append(test)
281 logger.debug("Tempest blacklist file does not exist.")
283 for cases_line in cases_file:
284 for black_tests_line in black_tests:
285 if black_tests_line in cases_line:
288 result_file.write(str(cases_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()
361 diff = (int(num_tests) - int(num_failures))
362 success_rate = 100 * diff / int(num_tests)
366 if 'smoke' in args.mode:
367 case_name = 'tempest_smoke_serial'
368 elif 'feature' in args.mode:
369 case_name = args.mode.replace("feature_", "")
371 case_name = 'tempest_full_parallel'
373 status = ft_utils.check_success_rate(case_name, success_rate)
374 logger.info("Tempest %s success_rate is %s%%, is marked as %s"
375 % (case_name, success_rate, status))
377 # Push results in payload of testcase
379 # add the test in error in the details sections
380 # should be possible to do it during the test
381 logger.debug("Pushing tempest results into DB...")
382 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
383 output = myfile.read()
386 for match in re.findall('(.*?)[. ]*FAILED', output):
389 # Generate json results for DB
390 json_results = {"timestart": time_start, "duration": dur_sec_int,
391 "tests": int(num_tests), "failures": int(num_failures),
392 "errors": error_logs}
393 logger.info("Results: " + str(json_results))
394 # split Tempest smoke and full
397 ft_utils.push_results_to_db("functest",
405 logger.error("Error pushing results into Database '%s'"
417 if not (args.mode in modes):
418 logger.error("Tempest mode not valid. "
419 "Possible values are:\n" + str(modes))
422 if not os.path.exists(TEMPEST_RESULTS_DIR):
423 os.makedirs(TEMPEST_RESULTS_DIR)
425 deployment_dir = ft_utils.get_deployment_dir(logger)
426 create_tempest_resources()
430 configure_tempest(deployment_dir)
432 MODE = " --tempest-config " + args.conf
434 generate_test_list(deployment_dir, args.mode)
435 apply_tempest_blacklist()
437 MODE += " --tests-file " + TEMPEST_LIST
439 MODE += " --concur 1"
441 ret_val = run_tempest(MODE)
448 if __name__ == '__main__':