Adapt functest testcase to APi refactoring
[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 argparse
17 import os
18 import re
19 import shutil
20 import subprocess
21 import sys
22 import time
23 import yaml
24 import ConfigParser
25
26 import keystoneclient.v2_0.client as ksclient
27 from neutronclient.v2_0 import client as neutronclient
28
29 import functest.utils.functest_logger as ft_logger
30 import functest.utils.functest_utils as ft_utils
31 import functest.utils.openstack_utils as os_utils
32
33 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
34          'identity', 'image', 'network', 'object_storage', 'orchestration',
35          'telemetry', 'volume', 'custom', 'defcore']
36
37 """ tests configuration """
38 parser = argparse.ArgumentParser()
39 parser.add_argument("-d", "--debug",
40                     help="Debug mode",
41                     action="store_true")
42 parser.add_argument("-s", "--serial",
43                     help="Run tests in one thread",
44                     action="store_true")
45 parser.add_argument("-m", "--mode",
46                     help="Tempest test mode [smoke, all]",
47                     default="smoke")
48 parser.add_argument("-r", "--report",
49                     help="Create json result file",
50                     action="store_true")
51 parser.add_argument("-n", "--noclean",
52                     help="Don't clean the created resources for this test.",
53                     action="store_true")
54
55 args = parser.parse_args()
56
57 """ logging configuration """
58 logger = ft_logger.Logger("run_tempest").getLogger()
59
60 REPO_PATH = os.environ['repos_dir'] + '/functest/'
61
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 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
70 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
71 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
72 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
73 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
74 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
75     "tenant_description")
76 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
77 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
78     "user_password")
79 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
80 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
81     "dir_rally_inst")
82 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
83     "dir_results")
84 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
85 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
86     "dir_tempest_cases")
87 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
88 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
89 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
90 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
91 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
92
93
94 def get_info(file_result):
95     test_run = ""
96     duration = ""
97     test_failed = ""
98
99     p = subprocess.Popen('cat tempest.log',
100                          shell=True, stdout=subprocess.PIPE,
101                          stderr=subprocess.STDOUT)
102     for line in p.stdout.readlines():
103         # print line,
104         if (len(test_run) < 1):
105             test_run = re.findall("[0-9]*\.[0-9]*s", line)
106         if (len(duration) < 1):
107             duration = re.findall("[0-9]*\ tests", line)
108         regexp = r"(failures=[0-9]+)"
109         if (len(test_failed) < 1):
110             test_failed = re.findall(regexp, line)
111
112     logger.debug("test_run:" + test_run)
113     logger.debug("duration:" + duration)
114
115
116 def create_tempest_resources():
117     ks_creds = os_utils.get_credentials("keystone")
118     logger.debug("Creating tenant and user for Tempest suite")
119     keystone = ksclient.Client(**ks_creds)
120     tenant_id = os_utils.create_tenant(keystone,
121                                        TENANT_NAME,
122                                        TENANT_DESCRIPTION)
123     if tenant_id == '':
124         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
125
126     user_id = os_utils.create_user(keystone, USER_NAME, USER_PASSWORD,
127                                    None, tenant_id)
128     if user_id == '':
129         logger.error("Error : Failed to create %s user" % USER_NAME)
130
131     logger.debug("Creating private network for Tempest suite")
132     creds_neutron = os_utils.get_credentials("neutron")
133     neutron_client = neutronclient.Client(**creds_neutron)
134     network_dic = os_utils.create_network_full(logger,
135                                                neutron_client,
136                                                PRIVATE_NET_NAME,
137                                                PRIVATE_SUBNET_NAME,
138                                                ROUTER_NAME,
139                                                PRIVATE_SUBNET_CIDR)
140     if network_dic:
141         if not os_utils.update_neutron_net(neutron_client,
142                                            network_dic['net_id'],
143                                            shared=True):
144             logger.error("Failed to update private network...")
145             exit(-1)
146         else:
147             logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
148     else:
149         logger.error("Private network creation failed")
150         exit(-1)
151
152
153 def configure_tempest(deployment_dir):
154     """
155     Add/update needed parameters into tempest.conf file generated by Rally
156     """
157
158     logger.debug("Generating tempest.conf file...")
159     cmd = "rally verify genconfig"
160     ft_utils.execute_command(cmd, logger)
161
162     logger.debug("Finding tempest.conf file...")
163     tempest_conf_file = deployment_dir + "/tempest.conf"
164     if not os.path.isfile(tempest_conf_file):
165         logger.error("Tempest configuration file %s NOT found."
166                      % tempest_conf_file)
167         exit(-1)
168
169     logger.debug("Updating selected tempest.conf parameters...")
170     config = ConfigParser.RawConfigParser()
171     config.read(tempest_conf_file)
172     config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
173     config.set('identity', 'tenant_name', TENANT_NAME)
174     config.set('identity', 'username', USER_NAME)
175     config.set('identity', 'password', USER_PASSWORD)
176     with open(tempest_conf_file, 'wb') as config_file:
177         config.write(config_file)
178
179     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
180     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
181     return True
182
183
184 def read_file(filename):
185     with open(filename) as src:
186         return [line.strip() for line in src.readlines()]
187
188
189 def generate_test_list(deployment_dir, mode):
190     logger.debug("Generating test case list...")
191     if mode == 'defcore':
192         shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
193     elif mode == 'custom':
194         if os.path.isfile(TEMPEST_CUSTOM):
195             shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
196         else:
197             logger.error("Tempest test list file %s NOT found."
198                          % TEMPEST_CUSTOM)
199             exit(-1)
200     else:
201         if mode == 'smoke':
202             testr_mode = "smoke"
203         elif mode == 'full':
204             testr_mode = ""
205         else:
206             testr_mode = 'tempest.api.' + mode
207         cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
208                testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
209         ft_utils.execute_command(cmd, logger)
210
211
212 def apply_tempest_blacklist():
213     logger.debug("Applying tempest blacklist...")
214     cases_file = read_file(TEMPEST_RAW_LIST)
215     result_file = open(TEMPEST_LIST, 'w')
216     try:
217         black_file = read_file(TEMPEST_BLACKLIST)
218     except:
219         black_file = ''
220         logger.debug("Tempest blacklist file does not exist.")
221     for line in cases_file:
222         if line not in black_file:
223             result_file.write(str(line) + '\n')
224     result_file.close()
225
226
227 def run_tempest(OPTION):
228     #
229     # the "main" function of the script which launches Rally to run Tempest
230     # :param option: tempest option (smoke, ..)
231     # :return: void
232     #
233     logger.info("Starting Tempest test suite: '%s'." % OPTION)
234     start_time = time.time()
235     stop_time = start_time
236     cmd_line = "rally verify start " + OPTION + " --system-wide"
237
238     header = ("Tempest environment:\n"
239               "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
240               (os.getenv('INSTALLER_TYPE', 'Unknown'),
241                os.getenv('DEPLOY_SCENARIO', 'Unknown'),
242                os.getenv('NODE_NAME', 'Unknown'),
243                time.strftime("%a %b %d %H:%M:%S %Z %Y")))
244
245     f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
246     f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
247     f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
248     f_env.write(header)
249
250     subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
251
252     f_stdout.close()
253     f_stderr.close()
254     f_env.close()
255
256     cmd_line = "rally verify show"
257     ft_utils.execute_command(cmd_line, logger,
258                              exit_on_error=True, info=True)
259
260     cmd_line = "rally verify list"
261     logger.debug('Executing command : {}'.format(cmd_line))
262     cmd = os.popen(cmd_line)
263     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
264     # Format:
265     # | UUID | Deployment UUID | smoke | tests | failures | Created at |
266     # Duration | Status  |
267     num_tests = output[4]
268     num_failures = output[5]
269     time_start = output[6]
270     duration = output[7]
271     # Compute duration (lets assume it does not take more than 60 min)
272     dur_min = int(duration.split(':')[1])
273     dur_sec_float = float(duration.split(':')[2])
274     dur_sec_int = int(round(dur_sec_float, 0))
275     dur_sec_int = dur_sec_int + 60 * dur_min
276     stop_time = time.time()
277     # Push results in payload of testcase
278     if args.report:
279         logger.debug("Pushing tempest results into DB...")
280         # Note criteria hardcoded...TODO move to testcase.yaml
281         status = "FAIL"
282         try:
283             diff = (int(num_tests) - int(num_failures))
284             success_rate = 100 * diff / int(num_tests)
285         except:
286             success_rate = 0
287
288         # For Tempest we assume that the success rate is above 90%
289         if success_rate >= 90:
290             status = "PASS"
291
292         # add the test in error in the details sections
293         # should be possible to do it during the test
294         with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
295             output = myfile.read()
296         error_logs = ""
297
298         for match in re.findall('(.*?)[. ]*FAILED', output):
299                 error_logs += match
300
301         # Generate json results for DB
302         json_results = {"timestart": time_start, "duration": dur_sec_int,
303                         "tests": int(num_tests), "failures": int(num_failures),
304                         "errors": error_logs}
305         logger.info("Results: " + str(json_results))
306         # TODO split Tempest smoke and full
307         try:
308             ft_utils.push_results_to_db("functest",
309                                         "Tempest",
310                                         logger,
311                                         start_time,
312                                         stop_time,
313                                         status,
314                                         json_results)
315         except:
316             logger.error("Error pushing results into Database '%s'"
317                          % sys.exc_info()[0])
318
319
320 def main():
321     global MODE
322
323     if not (args.mode in modes):
324         logger.error("Tempest mode not valid. "
325                      "Possible values are:\n" + str(modes))
326         exit(-1)
327
328     if not os.path.exists(TEMPEST_RESULTS_DIR):
329         os.makedirs(TEMPEST_RESULTS_DIR)
330
331     deployment_dir = ft_utils.get_deployment_dir(logger)
332     configure_tempest(deployment_dir)
333     create_tempest_resources()
334     generate_test_list(deployment_dir, args.mode)
335     apply_tempest_blacklist()
336
337     MODE = "--tests-file " + TEMPEST_LIST
338     if args.serial:
339         MODE += " --concur 1"
340
341     run_tempest(MODE)
342
343
344 if __name__ == '__main__':
345     main()