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