Show real time tempest test execution
[functest.git] / testcases / OpenStack / tempest / run_tempest.py
1 #!/usr/bin/env python
2 #
3 # Description:
4 #    Runs tempest and pushes the results to the DB
5 #
6 # Authors:
7 #    morgan.richomme@orange.com
8 #    jose.lausuch@ericsson.com
9 #    viktor.tikkanen@nokia.com
10 #
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
15 #
16 import ConfigParser
17 import argparse
18 import os
19 import re
20 import shutil
21 import subprocess
22 import sys
23 import time
24
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
28 import yaml
29
30
31 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
32          'identity', 'image', 'network', 'object_storage', 'orchestration',
33          'telemetry', 'volume', 'custom', 'defcore', 'feature_multisite']
34
35 """ tests configuration """
36 parser = argparse.ArgumentParser()
37 parser.add_argument("-d", "--debug",
38                     help="Debug mode",
39                     action="store_true")
40 parser.add_argument("-s", "--serial",
41                     help="Run tests in one thread",
42                     action="store_true")
43 parser.add_argument("-m", "--mode",
44                     help="Tempest test mode [smoke, all]",
45                     default="smoke")
46 parser.add_argument("-r", "--report",
47                     help="Create json result file",
48                     action="store_true")
49 parser.add_argument("-n", "--noclean",
50                     help="Don't clean the created resources for this test.",
51                     action="store_true")
52
53 args = parser.parse_args()
54
55 """ logging configuration """
56 logger = ft_logger.Logger("run_tempest").getLogger()
57
58 REPO_PATH = os.environ['repos_dir'] + '/functest/'
59
60
61 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
62     functest_yaml = yaml.safe_load(f)
63 f.close()
64 TEST_DB = functest_yaml.get("results").get("test_db_url")
65
66 MODE = "smoke"
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(
81     "tenant_description")
82 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
83 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
84     "user_password")
85 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
86 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
87     "dir_rally_inst")
88 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
89     "dir_results")
90 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
91 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
92     "dir_tempest_cases")
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'
98
99
100 def get_info(file_result):
101     test_run = ""
102     duration = ""
103     test_failed = ""
104
105     p = subprocess.Popen('cat tempest.log',
106                          shell=True, stdout=subprocess.PIPE,
107                          stderr=subprocess.STDOUT)
108     for line in p.stdout.readlines():
109         # print line,
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)
117
118     logger.debug("test_run:" + test_run)
119     logger.debug("duration:" + duration)
120
121
122 def create_tempest_resources():
123
124     keystone_client = os_utils.get_keystone_client()
125     neutron_client = os_utils.get_neutron_client()
126     glance_client = os_utils.get_glance_client()
127
128     logger.debug("Creating tenant and user for Tempest suite")
129     tenant_id = os_utils.create_tenant(keystone_client,
130                                        TENANT_NAME,
131                                        TENANT_DESCRIPTION)
132     if tenant_id == '':
133         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
134
135     user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
136                                    None, tenant_id)
137     if user_id == '':
138         logger.error("Error : Failed to create %s user" % USER_NAME)
139
140     logger.debug("Creating private network for Tempest suite")
141     network_dic = os_utils.create_network_full(logger,
142                                                neutron_client,
143                                                PRIVATE_NET_NAME,
144                                                PRIVATE_SUBNET_NAME,
145                                                ROUTER_NAME,
146                                                PRIVATE_SUBNET_CIDR)
147     if network_dic:
148         if not os_utils.update_neutron_net(neutron_client,
149                                            network_dic['net_id'],
150                                            shared=True):
151             logger.error("Failed to update private network...")
152             exit(-1)
153         else:
154             logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
155     else:
156         logger.error("Private network creation failed")
157         exit(-1)
158
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)
162     if image_id != '':
163         logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
164     else:
165         logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
166                                                           GLANCE_IMAGE_PATH))
167         image_id = os_utils.create_glance_image(glance_client,
168                                                 GLANCE_IMAGE_NAME,
169                                                 GLANCE_IMAGE_PATH)
170         if not image_id:
171             logger.error("Failed to create a Glance image...")
172             exit(-1)
173         logger.debug("Image '%s' with ID=%s created successfully."
174                      % (GLANCE_IMAGE_NAME, image_id))
175
176
177 def configure_tempest(deployment_dir):
178     """
179     Add/update needed parameters into tempest.conf file generated by Rally
180     """
181
182     logger.debug("Generating tempest.conf file...")
183     cmd = "rally verify genconfig"
184     ft_utils.execute_command(cmd, logger)
185
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."
190                      % tempest_conf_file)
191         exit(-1)
192
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)
202
203     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
204     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
205     return True
206
207
208 def configure_tempest_feature(deployment_dir, mode):
209     """
210     Add/update needed parameters into tempest.conf file generated by Rally
211     """
212
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."
217                      % tempest_conf_file)
218         exit(-1)
219
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()
231         try:
232             config.add_section("kingbird")
233         except:
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)
241
242     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
243     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
244     return True
245
246
247 def read_file(filename):
248     with open(filename) as src:
249         return [line.strip() for line in src.readlines()]
250
251
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)
259         else:
260             logger.error("Tempest test list file %s NOT found."
261                          % TEMPEST_CUSTOM)
262             exit(-1)
263     else:
264         if mode == 'smoke':
265             testr_mode = "smoke"
266         elif mode == 'feature_multisite':
267             testr_mode = " | grep kingbird "
268         elif mode == 'full':
269             testr_mode = ""
270         else:
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)
275
276
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')
281     try:
282         black_file = read_file(TEMPEST_BLACKLIST)
283     except:
284         black_file = ''
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')
289     result_file.close()
290
291
292 def run_tempest(OPTION):
293     #
294     # the "main" function of the script which launches Rally to run Tempest
295     # :param option: tempest option (smoke, ..)
296     # :return: void
297     #
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"
302
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")))
309
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+')
313     f_env.write(header)
314
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,
319         stderr=f_stderr,
320         bufsize=1)
321
322     with p.stdout:
323         for line in iter(p.stdout.readline, b''):
324             if re.search("\} tempest\.", line):
325                 logger.info(line.replace('\n', ''))
326             f_stdout.write(line)
327     p.wait()
328
329     f_stdout.close()
330     f_stderr.close()
331     f_env.close()
332
333     cmd_line = "rally verify show"
334     output = ""
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):
339             break
340         output += line
341     logger.info(output)
342
343     cmd_line = "rally verify list"
344     cmd = os.popen(cmd_line)
345     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
346     # Format:
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]
352     duration = output[7]
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
360     if args.report:
361         logger.debug("Pushing tempest results into DB...")
362         # Note criteria hardcoded...TODO move to testcase.yaml
363         status = "FAIL"
364         try:
365             diff = (int(num_tests) - int(num_failures))
366             success_rate = 100 * diff / int(num_tests)
367         except:
368             success_rate = 0
369
370         # For Tempest we assume that the success rate is above 90%
371         if success_rate >= 90:
372             status = "PASS"
373
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()
378         error_logs = ""
379
380         for match in re.findall('(.*?)[. ]*FAILED', output):
381             error_logs += match
382
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"
391         else:
392             case_name = "tempest_full_parallel"
393
394         try:
395             ft_utils.push_results_to_db("functest",
396                                         case_name,
397                                         None,
398                                         start_time,
399                                         stop_time,
400                                         status,
401                                         json_results)
402         except:
403             logger.error("Error pushing results into Database '%s'"
404                          % sys.exc_info()[0])
405
406
407 def main():
408     global MODE
409
410     if not (args.mode in modes):
411         logger.error("Tempest mode not valid. "
412                      "Possible values are:\n" + str(modes))
413         exit(-1)
414
415     if not os.path.exists(TEMPEST_RESULTS_DIR):
416         os.makedirs(TEMPEST_RESULTS_DIR)
417
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()
424
425     MODE = "--tests-file " + TEMPEST_LIST
426     if args.serial:
427         MODE += " --concur 1"
428
429     run_tempest(MODE)
430
431
432 if __name__ == '__main__':
433     main()