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