Re-generating tempest.conf file before starting tests
[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 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
61     functest_yaml = yaml.safe_load(f)
62 f.close()
63 TEST_DB = functest_yaml.get("results").get("test_db_url")
64
65 MODE = "smoke"
66 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
67     "openstack").get("image_name")
68 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
69     "openstack").get("image_file_name")
70 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
71     "openstack").get("image_disk_format")
72 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
73     "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
74 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
75 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
76 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
77 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
78 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
79 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
80     "tenant_description")
81 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
82 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
83     "user_password")
84 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
85 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
86     "dir_rally_inst")
87 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
88     "dir_results")
89 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
90 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
91     "dir_tempest_cases")
92 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
93 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
94 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
95 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
96 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
97
98
99 def get_info(file_result):
100     test_run = ""
101     duration = ""
102     test_failed = ""
103
104     p = subprocess.Popen('cat tempest.log',
105                          shell=True, stdout=subprocess.PIPE,
106                          stderr=subprocess.STDOUT)
107     for line in p.stdout.readlines():
108         # print line,
109         if (len(test_run) < 1):
110             test_run = re.findall("[0-9]*\.[0-9]*s", line)
111         if (len(duration) < 1):
112             duration = re.findall("[0-9]*\ tests", line)
113         regexp = r"(failures=[0-9]+)"
114         if (len(test_failed) < 1):
115             test_failed = re.findall(regexp, line)
116
117     logger.debug("test_run:" + test_run)
118     logger.debug("duration:" + duration)
119
120
121 def create_tempest_resources():
122     keystone_client = os_utils.get_keystone_client()
123     neutron_client = os_utils.get_neutron_client()
124     glance_client = os_utils.get_glance_client()
125
126     logger.debug("Creating tenant and user for Tempest suite")
127     tenant_id = os_utils.create_tenant(keystone_client,
128                                        TENANT_NAME,
129                                        TENANT_DESCRIPTION)
130     if tenant_id == '':
131         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
132
133     user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
134                                    None, tenant_id)
135     if user_id == '':
136         logger.error("Error : Failed to create %s user" % USER_NAME)
137
138     logger.debug("Creating private network for Tempest suite")
139     network_dic = os_utils.create_network_full(neutron_client,
140                                                PRIVATE_NET_NAME,
141                                                PRIVATE_SUBNET_NAME,
142                                                ROUTER_NAME,
143                                                PRIVATE_SUBNET_CIDR)
144     if network_dic:
145         if not os_utils.update_neutron_net(neutron_client,
146                                            network_dic['net_id'],
147                                            shared=True):
148             logger.error("Failed to update private network...")
149             exit(-1)
150         else:
151             logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
152     else:
153         logger.error("Private network creation failed")
154         exit(-1)
155
156     logger.debug("Creating image for Tempest suite")
157     # Check if the given image exists
158     image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
159     if image_id != '':
160         logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
161     else:
162         logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
163                                                           GLANCE_IMAGE_PATH))
164         image_id = os_utils.create_glance_image(glance_client,
165                                                 GLANCE_IMAGE_NAME,
166                                                 GLANCE_IMAGE_PATH)
167         if not image_id:
168             logger.error("Failed to create a Glance image...")
169             exit(-1)
170         logger.debug("Image '%s' with ID=%s created successfully."
171                      % (GLANCE_IMAGE_NAME, image_id))
172
173
174 def configure_tempest(deployment_dir):
175     """
176     Add/update needed parameters into tempest.conf file generated by Rally
177     """
178
179     tempest_conf_file = deployment_dir + "/tempest.conf"
180     if os.path.isfile(tempest_conf_file):
181         logger.debug("Deleting old tempest.conf file...")
182         os.remove(tempest_conf_file)
183
184     logger.debug("Generating new tempest.conf file...")
185     cmd = "rally verify genconfig"
186     ft_utils.execute_command(cmd, logger)
187
188     logger.debug("Finding tempest.conf file...")
189     if not os.path.isfile(tempest_conf_file):
190         logger.error("Tempest configuration file %s NOT found."
191                      % tempest_conf_file)
192         exit(-1)
193
194     logger.debug("Updating selected tempest.conf parameters...")
195     config = ConfigParser.RawConfigParser()
196     config.read(tempest_conf_file)
197     config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
198     config.set('identity', 'tenant_name', TENANT_NAME)
199     config.set('identity', 'username', USER_NAME)
200     config.set('identity', 'password', USER_PASSWORD)
201
202     if os.getenv('OS_ENDPOINT_TYPE') is not None:
203         services_list = ['compute', 'volume', 'image', 'network',
204                          'data-processing', 'object-storage', 'orchestration']
205         sections = config.sections()
206         for service in services_list:
207             if service not in sections:
208                 config.add_section(service)
209             config.set(service, 'endpoint_type',
210                        os.environ.get("OS_ENDPOINT_TYPE"))
211
212     with open(tempest_conf_file, 'wb') as config_file:
213         config.write(config_file)
214
215     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
216     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
217     return True
218
219
220 def configure_tempest_feature(deployment_dir, mode):
221     """Add/update needed parameters into tempest.conf file generated by Rally
222
223     """
224
225     logger.debug("Finding tempest.conf file...")
226     tempest_conf_file = deployment_dir + "/tempest.conf"
227     if not os.path.isfile(tempest_conf_file):
228         logger.error("Tempest configuration file %s NOT found."
229                      % tempest_conf_file)
230         exit(-1)
231
232     logger.debug("Updating selected tempest.conf parameters...")
233     config = ConfigParser.RawConfigParser()
234     config.read(tempest_conf_file)
235     if mode == 'feature_multisite':
236         config.set('service_available', 'kingbird', 'true')
237         cmd = "openstack endpoint show kingbird | grep publicurl |\
238                awk '{print $4}'"
239         kingbird_endpoint_details = "".join(os.popen(cmd).read().split())
240         kingbird_endpoint_url = kingbird_endpoint_details.rsplit('/', 1)[0] + \
241             '/'
242         kingbird_api_version = kingbird_endpoint_details.rsplit('/', 1)[1]
243         try:
244             config.add_section("kingbird")
245         except Exception:
246             logger.info('kingbird section exist')
247         config.set('kingbird', 'endpoint_type', 'publicURL')
248         config.set('kingbird', 'TIME_TO_SYNC', '20')
249         config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
250         config.set('kingbird', 'api_version', kingbird_api_version)
251     with open(tempest_conf_file, 'wb') as config_file:
252         config.write(config_file)
253
254     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
255     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
256     return True
257
258
259 def read_file(filename):
260     with open(filename) as src:
261         return [line.strip() for line in src.readlines()]
262
263
264 def generate_test_list(deployment_dir, mode):
265     logger.debug("Generating test case list...")
266     if mode == 'defcore':
267         shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
268     elif mode == 'custom':
269         if os.path.isfile(TEMPEST_CUSTOM):
270             shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
271         else:
272             logger.error("Tempest test list file %s NOT found."
273                          % TEMPEST_CUSTOM)
274             exit(-1)
275     else:
276         if mode == 'smoke':
277             testr_mode = "smoke"
278         elif mode == 'feature_multisite':
279             testr_mode = " | grep -i kingbird "
280         elif mode == 'full':
281             testr_mode = ""
282         else:
283             testr_mode = 'tempest.api.' + mode
284         cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
285                testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
286         ft_utils.execute_command(cmd, logger)
287
288
289 def apply_tempest_blacklist():
290     logger.debug("Applying tempest blacklist...")
291     cases_file = read_file(TEMPEST_RAW_LIST)
292     result_file = open(TEMPEST_LIST, 'w')
293     black_tests = []
294     try:
295         installer_type = os.getenv('INSTALLER_TYPE')
296         deploy_scenario = os.getenv('DEPLOY_SCENARIO')
297         if (bool(installer_type) * bool(deploy_scenario)):
298             # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the file
299             black_list_file = open(TEMPEST_BLACKLIST)
300             black_list_yaml = yaml.safe_load(black_list_file)
301             black_list_file.close()
302             for item in black_list_yaml:
303                 scenarios = item['scenarios']
304                 installers = item['installers']
305                 if (deploy_scenario in scenarios and
306                         installer_type in installers):
307                     tests = item['tests']
308                     for test in tests:
309                         black_tests.append(test)
310                     break
311     except:
312         black_tests = []
313         logger.debug("Tempest blacklist file does not exist.")
314
315     for cases_line in cases_file:
316         for black_tests_line in black_tests:
317             if black_tests_line in cases_line:
318                 break
319         else:
320             result_file.write(str(cases_line) + '\n')
321     result_file.close()
322
323
324 def run_tempest(OPTION):
325     #
326     # the "main" function of the script which launches Rally to run Tempest
327     # :param option: tempest option (smoke, ..)
328     # :return: void
329     #
330     logger.info("Starting Tempest test suite: '%s'." % OPTION)
331     start_time = time.time()
332     stop_time = start_time
333     cmd_line = "rally verify start " + OPTION + " --system-wide"
334
335     header = ("Tempest environment:\n"
336               "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
337               (os.getenv('INSTALLER_TYPE', 'Unknown'),
338                os.getenv('DEPLOY_SCENARIO', 'Unknown'),
339                os.getenv('NODE_NAME', 'Unknown'),
340                time.strftime("%a %b %d %H:%M:%S %Z %Y")))
341
342     f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
343     f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
344     f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
345     f_env.write(header)
346
347     # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
348     p = subprocess.Popen(
349         cmd_line, shell=True,
350         stdout=subprocess.PIPE,
351         stderr=f_stderr,
352         bufsize=1)
353
354     with p.stdout:
355         for line in iter(p.stdout.readline, b''):
356             if re.search("\} tempest\.", line):
357                 logger.info(line.replace('\n', ''))
358             f_stdout.write(line)
359     p.wait()
360
361     f_stdout.close()
362     f_stderr.close()
363     f_env.close()
364
365     cmd_line = "rally verify show"
366     output = ""
367     p = subprocess.Popen(
368         cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
369     for line in p.stdout:
370         if re.search("Tests\:", line):
371             break
372         output += line
373     logger.info(output)
374
375     cmd_line = "rally verify list"
376     cmd = os.popen(cmd_line)
377     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
378     # Format:
379     # | UUID | Deployment UUID | smoke | tests | failures | Created at |
380     # Duration | Status  |
381     num_tests = output[4]
382     num_failures = output[5]
383     time_start = output[6]
384     duration = output[7]
385     # Compute duration (lets assume it does not take more than 60 min)
386     dur_min = int(duration.split(':')[1])
387     dur_sec_float = float(duration.split(':')[2])
388     dur_sec_int = int(round(dur_sec_float, 0))
389     dur_sec_int = dur_sec_int + 60 * dur_min
390     stop_time = time.time()
391
392     try:
393         diff = (int(num_tests) - int(num_failures))
394         success_rate = 100 * diff / int(num_tests)
395     except:
396         success_rate = 0
397
398     if 'smoke' in args.mode:
399         case_name = 'tempest_smoke_serial'
400     else:
401         case_name = 'tempest_full_parallel'
402
403     status = ft_utils.check_success_rate(case_name, success_rate)
404     logger.info("Tempest %s success_rate is %s%%, is marked as %s"
405                 % (case_name, success_rate, status))
406
407     # Push results in payload of testcase
408     if args.report:
409         # add the test in error in the details sections
410         # should be possible to do it during the test
411         logger.debug("Pushing tempest results into DB...")
412         with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
413             output = myfile.read()
414         error_logs = ""
415
416         for match in re.findall('(.*?)[. ]*FAILED', output):
417             error_logs += match
418
419         # Generate json results for DB
420         json_results = {"timestart": time_start, "duration": dur_sec_int,
421                         "tests": int(num_tests), "failures": int(num_failures),
422                         "errors": error_logs}
423         logger.info("Results: " + str(json_results))
424         # split Tempest smoke and full
425
426         try:
427             ft_utils.push_results_to_db("functest",
428                                         case_name,
429                                         None,
430                                         start_time,
431                                         stop_time,
432                                         status,
433                                         json_results)
434         except:
435             logger.error("Error pushing results into Database '%s'"
436                          % sys.exc_info()[0])
437
438     if status == "PASS":
439         return 0
440     else:
441         return -1
442
443
444 def main():
445     global MODE
446
447     if not (args.mode in modes):
448         logger.error("Tempest mode not valid. "
449                      "Possible values are:\n" + str(modes))
450         exit(-1)
451
452     if not os.path.exists(TEMPEST_RESULTS_DIR):
453         os.makedirs(TEMPEST_RESULTS_DIR)
454
455     deployment_dir = ft_utils.get_deployment_dir(logger)
456     configure_tempest(deployment_dir)
457     configure_tempest_feature(deployment_dir, args.mode)
458     create_tempest_resources()
459     generate_test_list(deployment_dir, args.mode)
460     apply_tempest_blacklist()
461
462     MODE = "--tests-file " + TEMPEST_LIST
463     if args.serial:
464         MODE += " --concur 1"
465
466     ret_val = run_tempest(MODE)
467     if ret_val != 0:
468         sys.exit(-1)
469
470     sys.exit(0)
471
472
473 if __name__ == '__main__':
474     main()