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 functest_yaml = ft_utils.get_functest_yaml()
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 SSH_TIMEOUT = functest_yaml.get("tempest").get("validation").get(
87 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
88 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
90 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
92 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
93 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
95 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
96 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
97 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
98 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
99 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
102 def get_info(file_result):
107 p = subprocess.Popen('cat tempest.log',
108 shell=True, stdout=subprocess.PIPE,
109 stderr=subprocess.STDOUT)
110 for line in p.stdout.readlines():
112 if (len(test_run) < 1):
113 test_run = re.findall("[0-9]*\.[0-9]*s", line)
114 if (len(duration) < 1):
115 duration = re.findall("[0-9]*\ tests", line)
116 regexp = r"(failures=[0-9]+)"
117 if (len(test_failed) < 1):
118 test_failed = re.findall(regexp, line)
120 logger.debug("test_run:" + test_run)
121 logger.debug("duration:" + duration)
124 def create_tempest_resources():
125 keystone_client = os_utils.get_keystone_client()
127 logger.debug("Creating tenant and user for Tempest suite")
128 tenant_id = os_utils.create_tenant(keystone_client,
132 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
134 user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
137 logger.error("Error : Failed to create %s user" % USER_NAME)
139 logger.debug("Creating private network for Tempest suite")
140 network_dic = os_utils.create_shared_network_full(PRIVATE_NET_NAME,
147 logger.debug("Creating image for Tempest suite")
148 _, image_id = os_utils.get_or_create_image(GLANCE_IMAGE_NAME,
155 def configure_tempest(deployment_dir):
157 Add/update needed parameters into tempest.conf file generated by Rally
160 tempest_conf_file = deployment_dir + "/tempest.conf"
161 if os.path.isfile(tempest_conf_file):
162 logger.debug("Deleting old tempest.conf file...")
163 os.remove(tempest_conf_file)
165 logger.debug("Generating new tempest.conf file...")
166 cmd = "rally verify genconfig"
167 ft_utils.execute_command(cmd, logger)
169 logger.debug("Finding tempest.conf file...")
170 if not os.path.isfile(tempest_conf_file):
171 logger.error("Tempest configuration file %s NOT found."
175 logger.debug("Updating selected tempest.conf parameters...")
176 config = ConfigParser.RawConfigParser()
177 config.read(tempest_conf_file)
178 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
179 config.set('identity', 'tenant_name', TENANT_NAME)
180 config.set('identity', 'username', USER_NAME)
181 config.set('identity', 'password', USER_PASSWORD)
182 config.set('validation', 'ssh_timeout', SSH_TIMEOUT)
184 if os.getenv('OS_ENDPOINT_TYPE') is not None:
185 services_list = ['compute', 'volume', 'image', 'network',
186 'data-processing', 'object-storage', 'orchestration']
187 sections = config.sections()
188 for service in services_list:
189 if service not in sections:
190 config.add_section(service)
191 config.set(service, 'endpoint_type',
192 os.environ.get("OS_ENDPOINT_TYPE"))
194 with open(tempest_conf_file, 'wb') as config_file:
195 config.write(config_file)
197 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
198 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
202 def read_file(filename):
203 with open(filename) as src:
204 return [line.strip() for line in src.readlines()]
207 def generate_test_list(deployment_dir, mode):
208 logger.debug("Generating test case list...")
209 if mode == 'defcore':
210 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
211 elif mode == 'custom':
212 if os.path.isfile(TEMPEST_CUSTOM):
213 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
215 logger.error("Tempest test list file %s NOT found."
221 elif mode == 'feature_multisite':
222 testr_mode = " | grep -i kingbird "
226 testr_mode = 'tempest.api.' + mode
227 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
228 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
229 ft_utils.execute_command(cmd, logger)
232 def apply_tempest_blacklist():
233 logger.debug("Applying tempest blacklist...")
234 cases_file = read_file(TEMPEST_RAW_LIST)
235 result_file = open(TEMPEST_LIST, 'w')
238 installer_type = os.getenv('INSTALLER_TYPE')
239 deploy_scenario = os.getenv('DEPLOY_SCENARIO')
240 if (bool(installer_type) * bool(deploy_scenario)):
241 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
242 black_list_file = open(TEMPEST_BLACKLIST)
243 black_list_yaml = yaml.safe_load(black_list_file)
244 black_list_file.close()
245 for item in black_list_yaml:
246 scenarios = item['scenarios']
247 installers = item['installers']
248 if (deploy_scenario in scenarios and
249 installer_type in installers):
250 tests = item['tests']
252 black_tests.append(test)
256 logger.debug("Tempest blacklist file does not exist.")
258 for cases_line in cases_file:
259 for black_tests_line in black_tests:
260 if black_tests_line in cases_line:
263 result_file.write(str(cases_line) + '\n')
267 def run_tempest(OPTION):
269 # the "main" function of the script which launches Rally to run Tempest
270 # :param option: tempest option (smoke, ..)
273 logger.info("Starting Tempest test suite: '%s'." % OPTION)
274 start_time = time.time()
275 stop_time = start_time
276 cmd_line = "rally verify start " + OPTION + " --system-wide"
278 header = ("Tempest environment:\n"
279 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
280 (os.getenv('INSTALLER_TYPE', 'Unknown'),
281 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
282 os.getenv('NODE_NAME', 'Unknown'),
283 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
285 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
286 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
287 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
290 # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
291 p = subprocess.Popen(
292 cmd_line, shell=True,
293 stdout=subprocess.PIPE,
298 for line in iter(p.stdout.readline, b''):
299 if re.search("\} tempest\.", line):
300 logger.info(line.replace('\n', ''))
308 cmd_line = "rally verify show"
310 p = subprocess.Popen(
311 cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
312 for line in p.stdout:
313 if re.search("Tests\:", line):
318 cmd_line = "rally verify list"
319 cmd = os.popen(cmd_line)
320 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
322 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
323 # Duration | Status |
324 num_tests = output[4]
325 num_failures = output[5]
326 time_start = output[6]
328 # Compute duration (lets assume it does not take more than 60 min)
329 dur_min = int(duration.split(':')[1])
330 dur_sec_float = float(duration.split(':')[2])
331 dur_sec_int = int(round(dur_sec_float, 0))
332 dur_sec_int = dur_sec_int + 60 * dur_min
333 stop_time = time.time()
336 diff = (int(num_tests) - int(num_failures))
337 success_rate = 100 * diff / int(num_tests)
341 if 'smoke' in args.mode:
342 case_name = 'tempest_smoke_serial'
343 elif 'feature' in args.mode:
344 case_name = args.mode.replace("feature_", "")
346 case_name = 'tempest_full_parallel'
348 status = ft_utils.check_success_rate(case_name, success_rate)
349 logger.info("Tempest %s success_rate is %s%%, is marked as %s"
350 % (case_name, success_rate, status))
352 # Push results in payload of testcase
354 # add the test in error in the details sections
355 # should be possible to do it during the test
356 logger.debug("Pushing tempest results into DB...")
357 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
358 output = myfile.read()
361 for match in re.findall('(.*?)[. ]*FAILED', output):
364 # Generate json results for DB
365 json_results = {"timestart": time_start, "duration": dur_sec_int,
366 "tests": int(num_tests), "failures": int(num_failures),
367 "errors": error_logs}
368 logger.info("Results: " + str(json_results))
369 # split Tempest smoke and full
372 ft_utils.push_results_to_db("functest",
380 logger.error("Error pushing results into Database '%s'"
392 if not (args.mode in modes):
393 logger.error("Tempest mode not valid. "
394 "Possible values are:\n" + str(modes))
397 if not os.path.exists(TEMPEST_RESULTS_DIR):
398 os.makedirs(TEMPEST_RESULTS_DIR)
400 deployment_dir = ft_utils.get_deployment_dir(logger)
401 create_tempest_resources()
405 configure_tempest(deployment_dir)
407 MODE = " --tempest-config " + args.conf
409 generate_test_list(deployment_dir, args.mode)
410 apply_tempest_blacklist()
412 MODE += " --tests-file " + TEMPEST_LIST
414 MODE += " --concur 1"
416 ret_val = run_tempest(MODE)
423 if __name__ == '__main__':