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
26 import keystoneclient.v2_0.client as ksclient
27 from neutronclient.v2_0 import client as neutronclient
29 import functest.utils.functest_logger as ft_logger
30 import functest.utils.functest_utils as ft_utils
31 import functest.utils.openstack_utils as os_utils
33 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
34 'identity', 'image', 'network', 'object_storage', 'orchestration',
35 'telemetry', 'volume', 'custom', 'defcore']
37 """ tests configuration """
38 parser = argparse.ArgumentParser()
39 parser.add_argument("-d", "--debug",
42 parser.add_argument("-s", "--serial",
43 help="Run tests in one thread",
45 parser.add_argument("-m", "--mode",
46 help="Tempest test mode [smoke, all]",
48 parser.add_argument("-r", "--report",
49 help="Create json result file",
51 parser.add_argument("-n", "--noclean",
52 help="Don't clean the created resources for this test.",
55 args = parser.parse_args()
57 """ logging configuration """
58 logger = ft_logger.Logger("run_tempest").getLogger()
60 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 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
70 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
71 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
72 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
73 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
74 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
76 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
77 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
79 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
80 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
82 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
84 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
85 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
87 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
88 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
89 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
90 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
91 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
94 def get_info(file_result):
99 p = subprocess.Popen('cat tempest.log',
100 shell=True, stdout=subprocess.PIPE,
101 stderr=subprocess.STDOUT)
102 for line in p.stdout.readlines():
104 if (len(test_run) < 1):
105 test_run = re.findall("[0-9]*\.[0-9]*s", line)
106 if (len(duration) < 1):
107 duration = re.findall("[0-9]*\ tests", line)
108 regexp = r"(failures=[0-9]+)"
109 if (len(test_failed) < 1):
110 test_failed = re.findall(regexp, line)
112 logger.debug("test_run:" + test_run)
113 logger.debug("duration:" + duration)
116 def create_tempest_resources():
117 ks_creds = os_utils.get_credentials("keystone")
118 logger.debug("Creating tenant and user for Tempest suite")
119 keystone = ksclient.Client(**ks_creds)
120 tenant_id = os_utils.create_tenant(keystone,
124 logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
126 user_id = os_utils.create_user(keystone, USER_NAME, USER_PASSWORD,
129 logger.error("Error : Failed to create %s user" % USER_NAME)
131 logger.debug("Creating private network for Tempest suite")
132 creds_neutron = os_utils.get_credentials("neutron")
133 neutron_client = neutronclient.Client(**creds_neutron)
134 network_dic = os_utils.create_network_full(logger,
141 if not os_utils.update_neutron_net(neutron_client,
142 network_dic['net_id'],
144 logger.error("Failed to update private network...")
147 logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
149 logger.error("Private network creation failed")
153 def configure_tempest(deployment_dir):
155 Add/update needed parameters into tempest.conf file generated by Rally
158 logger.debug("Generating tempest.conf file...")
159 cmd = "rally verify genconfig"
160 ft_utils.execute_command(cmd, logger)
162 logger.debug("Finding tempest.conf file...")
163 tempest_conf_file = deployment_dir + "/tempest.conf"
164 if not os.path.isfile(tempest_conf_file):
165 logger.error("Tempest configuration file %s NOT found."
169 logger.debug("Updating selected tempest.conf parameters...")
170 config = ConfigParser.RawConfigParser()
171 config.read(tempest_conf_file)
172 config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
173 config.set('identity', 'tenant_name', TENANT_NAME)
174 config.set('identity', 'username', USER_NAME)
175 config.set('identity', 'password', USER_PASSWORD)
176 with open(tempest_conf_file, 'wb') as config_file:
177 config.write(config_file)
179 # Copy tempest.conf to /home/opnfv/functest/results/tempest/
180 shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
184 def read_file(filename):
185 with open(filename) as src:
186 return [line.strip() for line in src.readlines()]
189 def generate_test_list(deployment_dir, mode):
190 logger.debug("Generating test case list...")
191 if mode == 'defcore':
192 shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
193 elif mode == 'custom':
194 if os.path.isfile(TEMPEST_CUSTOM):
195 shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
197 logger.error("Tempest test list file %s NOT found."
206 testr_mode = 'tempest.api.' + mode
207 cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
208 testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
209 ft_utils.execute_command(cmd, logger)
212 def apply_tempest_blacklist():
213 logger.debug("Applying tempest blacklist...")
214 cases_file = read_file(TEMPEST_RAW_LIST)
215 result_file = open(TEMPEST_LIST, 'w')
217 black_file = read_file(TEMPEST_BLACKLIST)
220 logger.debug("Tempest blacklist file does not exist.")
221 for line in cases_file:
222 if line not in black_file:
223 result_file.write(str(line) + '\n')
227 def run_tempest(OPTION):
229 # the "main" function of the script which launches Rally to run Tempest
230 # :param option: tempest option (smoke, ..)
233 logger.info("Starting Tempest test suite: '%s'." % OPTION)
234 start_time = time.time()
235 stop_time = start_time
236 cmd_line = "rally verify start " + OPTION + " --system-wide"
238 header = ("Tempest environment:\n"
239 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" %
240 (os.getenv('INSTALLER_TYPE', 'Unknown'),
241 os.getenv('DEPLOY_SCENARIO', 'Unknown'),
242 os.getenv('NODE_NAME', 'Unknown'),
243 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
245 f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
246 f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
247 f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
250 subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
256 cmd_line = "rally verify show"
257 ft_utils.execute_command(cmd_line, logger,
258 exit_on_error=True, info=True)
260 cmd_line = "rally verify list"
261 logger.debug('Executing command : {}'.format(cmd_line))
262 cmd = os.popen(cmd_line)
263 output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
265 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
266 # Duration | Status |
267 num_tests = output[4]
268 num_failures = output[5]
269 time_start = output[6]
271 # Compute duration (lets assume it does not take more than 60 min)
272 dur_min = int(duration.split(':')[1])
273 dur_sec_float = float(duration.split(':')[2])
274 dur_sec_int = int(round(dur_sec_float, 0))
275 dur_sec_int = dur_sec_int + 60 * dur_min
276 stop_time = time.time()
277 # Push results in payload of testcase
279 logger.debug("Pushing tempest results into DB...")
280 # Note criteria hardcoded...TODO move to testcase.yaml
283 diff = (int(num_tests) - int(num_failures))
284 success_rate = 100 * diff / int(num_tests)
288 # For Tempest we assume that the success rate is above 90%
289 if success_rate >= 90:
292 # add the test in error in the details sections
293 # should be possible to do it during the test
294 with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
295 output = myfile.read()
298 for match in re.findall('(.*?)[. ]*FAILED', output):
301 # Generate json results for DB
302 json_results = {"timestart": time_start, "duration": dur_sec_int,
303 "tests": int(num_tests), "failures": int(num_failures),
304 "errors": error_logs}
305 logger.info("Results: " + str(json_results))
306 # TODO split Tempest smoke and full
308 ft_utils.push_results_to_db("functest",
316 logger.error("Error pushing results into Database '%s'"
323 if not (args.mode in modes):
324 logger.error("Tempest mode not valid. "
325 "Possible values are:\n" + str(modes))
328 if not os.path.exists(TEMPEST_RESULTS_DIR):
329 os.makedirs(TEMPEST_RESULTS_DIR)
331 deployment_dir = ft_utils.get_deployment_dir(logger)
332 configure_tempest(deployment_dir)
333 create_tempest_resources()
334 generate_test_list(deployment_dir, args.mode)
335 apply_tempest_blacklist()
337 MODE = "--tests-file " + TEMPEST_LIST
339 MODE += " --concur 1"
344 if __name__ == '__main__':