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