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
29 from functest.utils.functest_utils import FUNCTEST_REPO as FUNCTEST_REPO
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 functest_yaml = ft_utils.get_functest_yaml()
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 SSH_TIMEOUT = functest_yaml.get("tempest").get("validation").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 REPO_PATH = FUNCTEST_REPO + '/'
94 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
95 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
96 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
97 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
98 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
101 def get_info(file_result):
106 p = subprocess.Popen('cat tempest.log',
107 shell=True, stdout=subprocess.PIPE,
108 stderr=subprocess.STDOUT)
109 for line in p.stdout.readlines():
111 if (len(test_run) < 1):
112 test_run = re.findall("[0-9]*\.[0-9]*s", line)
113 if (len(duration) < 1):
114 duration = re.findall("[0-9]*\ tests", line)
115 regexp = r"(failures=[0-9]+)"
116 if (len(test_failed) < 1):
117 test_failed = re.findall(regexp, line)
119 logger.debug("test_run:" + test_run)
120 logger.debug("duration:" + duration)
123 def create_tempest_resources():
124 keystone_client = os_utils.get_keystone_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_shared_network_full(PRIVATE_NET_NAME,
146 logger.debug("Creating image for Tempest suite")
147 _, image_id = os_utils.get_or_create_image(GLANCE_IMAGE_NAME,
154 def configure_tempest(deployment_dir):
156 Add/update needed parameters into tempest.conf file generated by Rally
159 tempest_conf_file = deployment_dir + "/tempest.conf"
160 if os.path.isfile(tempest_conf_file):
161 logger.debug("Deleting old tempest.conf file...")
162 os.remove(tempest_conf_file)
164 logger.debug("Generating new tempest.conf file...")
165 cmd = "rally verify genconfig"
166 ft_utils.execute_command(cmd, logger)
168 logger.debug("Finding tempest.conf file...")
169 if not os.path.isfile(tempest_conf_file):
170 logger.error("Tempest configuration file %s NOT found."
174 logger.debug("Updating selected tempest.conf parameters...")
175 config = ConfigParser.RawConfigParser()
176 config.read(tempest_conf_file)
177 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
178 config.set('identity', 'tenant_name', TENANT_NAME)
179 config.set('identity', 'username', USER_NAME)
180 config.set('identity', 'password', USER_PASSWORD)
181 config.set('validation', 'ssh_timeout', SSH_TIMEOUT)
183 if os.getenv('OS_ENDPOINT_TYPE') is not None:
184 services_list = ['compute', 'volume', 'image', 'network',
185 'data-processing', 'object-storage', 'orchestration']
186 sections = config.sections()
187 for service in services_list:
188 if service not in sections:
189 config.add_section(service)
190 config.set(service, 'endpoint_type',
191 os.environ.get("OS_ENDPOINT_TYPE"))
193 with open(tempest_conf_file, 'wb') as config_file:
194 config.write(config_file)
196 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
197 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
201 def read_file(filename):
202 with open(filename) as src:
203 return [line.strip() for line in src.readlines()]
206 def generate_test_list(deployment_dir, mode):
207 logger.debug("Generating test case list...")
208 if mode == 'defcore':
209 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
210 elif mode == 'custom':
211 if os.path.isfile(TEMPEST_CUSTOM):
212 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
214 logger.error("Tempest test list file %s NOT found."
220 elif mode == 'feature_multisite':
221 testr_mode = " | grep -i kingbird "
225 testr_mode = 'tempest.api.' + mode
226 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
227 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
228 ft_utils.execute_command(cmd, logger)
231 def apply_tempest_blacklist():
232 logger.debug("Applying tempest blacklist...")
233 cases_file = read_file(TEMPEST_RAW_LIST)
234 result_file = open(TEMPEST_LIST, 'w')
237 installer_type = os.getenv('INSTALLER_TYPE')
238 deploy_scenario = os.getenv('DEPLOY_SCENARIO')
239 if (bool(installer_type) * bool(deploy_scenario)):
240 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
241 black_list_file = open(TEMPEST_BLACKLIST)
242 black_list_yaml = yaml.safe_load(black_list_file)
243 black_list_file.close()
244 for item in black_list_yaml:
245 scenarios = item['scenarios']
246 installers = item['installers']
247 if (deploy_scenario in scenarios and
248 installer_type in installers):
249 tests = item['tests']
251 black_tests.append(test)
255 logger.debug("Tempest blacklist file does not exist.")
257 for cases_line in cases_file:
258 for black_tests_line in black_tests:
259 if black_tests_line in cases_line:
262 result_file.write(str(cases_line) + '\n')
266 def run_tempest(OPTION):
268 # the "main" function of the script which launches Rally to run Tempest
269 # :param option: tempest option (smoke, ..)
272 logger.info("Starting Tempest test suite: '%s'." % OPTION)
273 start_time = time.time()
274 stop_time = start_time
275 cmd_line = "rally verify start " + OPTION + " --system-wide"
277 header = ("Tempest environment:\n"
278 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
279 (os.getenv('INSTALLER_TYPE', 'Unknown'),
280 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
281 os.getenv('NODE_NAME', 'Unknown'),
282 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
284 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
285 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
286 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
289 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
290 p = subprocess.Popen(
291 cmd_line, shell=True,
292 stdout=subprocess.PIPE,
297 for line in iter(p.stdout.readline, b''):
298 if re.search("\} tempest\.", line):
299 logger.info(line.replace('\n', ''))
307 cmd_line = "rally verify show"
309 p = subprocess.Popen(
310 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
311 for line in p.stdout:
312 if re.search("Tests\:", line):
317 cmd_line = "rally verify list"
318 cmd = os.popen(cmd_line)
319 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
321 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
322 # Duration | Status |
323 num_tests = output[4]
324 num_failures = output[5]
325 time_start = output[6]
327 # Compute duration (lets assume it does not take more than 60 min)
328 dur_min = int(duration.split(':')[1])
329 dur_sec_float = float(duration.split(':')[2])
330 dur_sec_int = int(round(dur_sec_float, 0))
331 dur_sec_int = dur_sec_int + 60 * dur_min
332 stop_time = time.time()
335 diff = (int(num_tests) - int(num_failures))
336 success_rate = 100 * diff / int(num_tests)
340 if 'smoke' in args.mode:
341 case_name = 'tempest_smoke_serial'
342 elif 'feature' in args.mode:
343 case_name = args.mode.replace("feature_", "")
345 case_name = 'tempest_full_parallel'
347 status = ft_utils.check_success_rate(case_name, success_rate)
348 logger.info("Tempest %s success_rate is %s%%, is marked as %s"
349 % (case_name, success_rate, status))
351 # Push results in payload of testcase
353 # add the test in error in the details sections
354 # should be possible to do it during the test
355 logger.debug("Pushing tempest results into DB...")
356 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
357 output = myfile.read()
360 for match in re.findall('(.*?)[. ]*FAILED', output):
363 # Generate json results for DB
364 json_results = {"timestart": time_start, "duration": dur_sec_int,
365 "tests": int(num_tests), "failures": int(num_failures),
366 "errors": error_logs}
367 logger.info("Results: " + str(json_results))
368 # split Tempest smoke and full
371 ft_utils.push_results_to_db("functest",
379 logger.error("Error pushing results into Database '%s'"
391 if not (args.mode in modes):
392 logger.error("Tempest mode not valid. "
393 "Possible values are:\n" + str(modes))
396 if not os.path.exists(TEMPEST_RESULTS_DIR):
397 os.makedirs(TEMPEST_RESULTS_DIR)
399 deployment_dir = ft_utils.get_deployment_dir(logger)
400 create_tempest_resources()
404 configure_tempest(deployment_dir)
406 MODE = " --tempest-config " + args.conf
408 generate_test_list(deployment_dir, args.mode)
409 apply_tempest_blacklist()
411 MODE += " --tests-file " + TEMPEST_LIST
413 MODE += " --concur 1"
415 ret_val = run_tempest(MODE)
422 if __name__ == '__main__':