Merge "Add a flag in the CLI to report results to DB"
[functest.git] / functest / opnfv_tests / openstack / tempest / tempest.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10
11 import os
12 import re
13 import shutil
14 import subprocess
15 import time
16
17 import yaml
18
19 import conf_utils
20 import functest.core.testcase_base as testcase_base
21 from functest.utils.constants import CONST
22 import functest.utils.functest_logger as ft_logger
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.openstack_utils as os_utils
25
26 """ logging configuration """
27 logger = ft_logger.Logger("Tempest").getLogger()
28
29
30 class TempestCommon(testcase_base.TestcaseBase):
31
32     def __init__(self):
33         super(TempestCommon, self).__init__()
34         self.MODE = ""
35         self.OPTION = ""
36         self.FLAVOR_ID = None
37         self.IMAGE_ID = None
38         self.DEPLOYMENT_DIR = self.get_deployment_dir()
39
40     @staticmethod
41     def get_deployment_dir():
42         """
43         Returns current Rally deployment directory
44         """
45         cmd = ("rally deployment list | awk '/" +
46                CONST.rally_deployment_name +
47                "/ {print $2}'")
48         p = subprocess.Popen(cmd, shell=True,
49                              stdout=subprocess.PIPE,
50                              stderr=subprocess.STDOUT)
51         deployment_uuid = p.stdout.readline().rstrip()
52         if deployment_uuid == "":
53             logger.error("Rally deployment not found.")
54             exit(-1)
55         return os.path.join(CONST.dir_rally_inst,
56                             "tempest/for-deployment-" + deployment_uuid)
57
58     @staticmethod
59     def read_file(filename):
60         with open(filename) as src:
61             return [line.strip() for line in src.readlines()]
62
63     def create_tempest_resources(self):
64         keystone_client = os_utils.get_keystone_client()
65
66         logger.debug("Creating tenant and user for Tempest suite")
67         tenant_id = os_utils.create_tenant(
68             keystone_client,
69             CONST.tempest_identity_tenant_name,
70             CONST.tempest_identity_tenant_description)
71         if not tenant_id:
72             logger.error("Error : Failed to create %s tenant"
73                          % CONST.tempest_identity_tenant_name)
74
75         user_id = os_utils.create_user(keystone_client,
76                                        CONST.tempest_identity_user_name,
77                                        CONST.tempest_identity_user_password,
78                                        None, tenant_id)
79         if not user_id:
80             logger.error("Error : Failed to create %s user" %
81                          CONST.tempest_identity_user_name)
82
83         logger.debug("Creating private network for Tempest suite")
84         network_dic = \
85             os_utils.create_shared_network_full(
86                 CONST.tempest_private_net_name,
87                 CONST.tempest_private_subnet_name,
88                 CONST.tempest_router_name,
89                 CONST.tempest_private_subnet_cidr)
90         if not network_dic:
91             return testcase_base.TestcaseBase.EX_RUN_ERROR
92
93         if CONST.tempest_use_custom_images:
94             # adding alternative image should be trivial should we need it
95             logger.debug("Creating image for Tempest suite")
96             _, self.IMAGE_ID = os_utils.get_or_create_image(
97                 CONST.openstack_image_name, conf_utils.GLANCE_IMAGE_PATH,
98                 CONST.openstack_image_disk_format)
99             if not self.IMAGE_ID:
100                 return testcase_base.TestcaseBase.EX_RUN_ERROR
101
102         if CONST.tempest_use_custom_flavors:
103             # adding alternative flavor should be trivial should we need it
104             logger.debug("Creating flavor for Tempest suite")
105             _, self.FLAVOR_ID = os_utils.get_or_create_flavor(
106                 CONST.openstack_flavor_name,
107                 CONST.openstack_flavor_ram,
108                 CONST.openstack_flavor_disk,
109                 CONST.openstack_flavor_vcpus)
110             if not self.FLAVOR_ID:
111                 return testcase_base.TestcaseBase.EX_RUN_ERROR
112
113         return testcase_base.TestcaseBase.EX_OK
114
115     def generate_test_list(self, DEPLOYMENT_DIR):
116         logger.debug("Generating test case list...")
117         if self.MODE == 'defcore':
118             shutil.copyfile(
119                 conf_utils.TEMPEST_DEFCORE, conf_utils.TEMPEST_RAW_LIST)
120         elif self.MODE == 'custom':
121             if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
122                 shutil.copyfile(
123                     conf_utils.TEMPEST_CUSTOM, conf_utils.TEMPEST_RAW_LIST)
124             else:
125                 logger.error("Tempest test list file %s NOT found."
126                              % conf_utils.TEMPEST_CUSTOM)
127                 return testcase_base.TestcaseBase.EX_RUN_ERROR
128         else:
129             if self.MODE == 'smoke':
130                 testr_mode = "smoke"
131             elif self.MODE == 'feature_multisite':
132                 testr_mode = " | grep -i kingbird "
133             elif self.MODE == 'full':
134                 testr_mode = ""
135             else:
136                 testr_mode = 'tempest.api.' + self.MODE
137             cmd = ("cd " + DEPLOYMENT_DIR + ";" + "testr list-tests " +
138                    testr_mode + ">" + conf_utils.TEMPEST_RAW_LIST + ";cd")
139             ft_utils.execute_command(cmd)
140
141         return testcase_base.TestcaseBase.EX_OK
142
143     def apply_tempest_blacklist(self):
144         logger.debug("Applying tempest blacklist...")
145         cases_file = self.read_file(conf_utils.TEMPEST_RAW_LIST)
146         result_file = open(conf_utils.TEMPEST_LIST, 'w')
147         black_tests = []
148         try:
149             installer_type = CONST.INSTALLER_TYPE
150             deploy_scenario = CONST.DEPLOY_SCENARIO
151             if (bool(installer_type) * bool(deploy_scenario)):
152                 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
153                 # file
154                 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
155                 black_list_yaml = yaml.safe_load(black_list_file)
156                 black_list_file.close()
157                 for item in black_list_yaml:
158                     scenarios = item['scenarios']
159                     installers = item['installers']
160                     if (deploy_scenario in scenarios and
161                             installer_type in installers):
162                         tests = item['tests']
163                         for test in tests:
164                             black_tests.append(test)
165                         break
166         except:
167             black_tests = []
168             logger.debug("Tempest blacklist file does not exist.")
169
170         for cases_line in cases_file:
171             for black_tests_line in black_tests:
172                 if black_tests_line in cases_line:
173                     break
174             else:
175                 result_file.write(str(cases_line) + '\n')
176         result_file.close()
177         return testcase_base.TestcaseBase.EX_OK
178
179     def run(self):
180
181         self.start_time = time.time()
182
183         if not os.path.exists(conf_utils.TEMPEST_RESULTS_DIR):
184             os.makedirs(conf_utils.TEMPEST_RESULTS_DIR)
185
186         # Pre-configuration
187         res = self.create_tempest_resources()
188         if res != testcase_base.TestcaseBase.EX_OK:
189             return res
190
191         res = conf_utils.configure_tempest(logger,
192                                            self.DEPLOYMENT_DIR,
193                                            self.IMAGE_ID,
194                                            self.FLAVOR_ID)
195         if res != testcase_base.TestcaseBase.EX_OK:
196             return res
197
198         res = self.generate_test_list(self.DEPLOYMENT_DIR)
199         if res != testcase_base.TestcaseBase.EX_OK:
200             return res
201
202         res = self.apply_tempest_blacklist()
203         if res != testcase_base.TestcaseBase.EX_OK:
204             return res
205
206         self.OPTION += (" --tests-file %s " % conf_utils.TEMPEST_LIST)
207
208         cmd_line = "rally verify start " + self.OPTION + " --system-wide"
209         logger.info("Starting Tempest test suite: '%s'." % cmd_line)
210
211         header = ("Tempest environment:\n"
212                   "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
213                   (CONST.INSTALLER_TYPE,
214                    CONST.DEPLOY_SCENARIO,
215                    CONST.NODE_NAME,
216                    time.strftime("%a %b %d %H:%M:%S %Z %Y")))
217
218         f_stdout = open(conf_utils.TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
219         f_stderr = open(
220             conf_utils.TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
221         f_env = open(conf_utils.TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
222         f_env.write(header)
223
224         # subprocess.call(cmd_line, shell=True,
225         # stdout=f_stdout, stderr=f_stderr)
226         p = subprocess.Popen(
227             cmd_line, shell=True,
228             stdout=subprocess.PIPE,
229             stderr=f_stderr,
230             bufsize=1)
231
232         with p.stdout:
233             for line in iter(p.stdout.readline, b''):
234                 if re.search("\} tempest\.", line):
235                     logger.info(line.replace('\n', ''))
236                 f_stdout.write(line)
237         p.wait()
238
239         f_stdout.close()
240         f_stderr.close()
241         f_env.close()
242
243         cmd_line = "rally verify show"
244         output = ""
245         p = subprocess.Popen(cmd_line,
246                              shell=True,
247                              stdout=subprocess.PIPE,
248                              stderr=subprocess.PIPE)
249         for line in p.stdout:
250             if re.search("Tests\:", line):
251                 break
252             output += line
253         logger.info(output)
254
255         cmd_line = "rally verify list"
256         cmd = os.popen(cmd_line)
257         output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
258         # Format:
259         # | UUID | Deployment UUID | smoke | tests | failures | Created at |
260         # Duration | Status  |
261         num_tests = output[4]
262         num_failures = output[5]
263         duration = output[7]
264         # Compute duration (lets assume it does not take more than 60 min)
265         dur_min = int(duration.split(':')[1])
266         dur_sec_float = float(duration.split(':')[2])
267         dur_sec_int = int(round(dur_sec_float, 0))
268         dur_sec_int = dur_sec_int + 60 * dur_min
269
270         try:
271             diff = (int(num_tests) - int(num_failures))
272             success_rate = 100 * diff / int(num_tests)
273         except:
274             success_rate = 0
275
276         self.criteria = ft_utils.check_success_rate(
277             self.case_name, success_rate)
278         logger.info("Tempest %s success_rate is %s%%, is marked as %s"
279                     % (self.case_name, success_rate, self.criteria))
280
281         self.stop_time = time.time()
282
283         if self.criteria == "PASS":
284             return testcase_base.TestcaseBase.EX_OK
285         else:
286             return testcase_base.TestcaseBase.EX_TESTCASE_FAILED
287
288
289 class TempestSmokeSerial(TempestCommon):
290
291     def __init__(self):
292         TempestCommon.__init__(self)
293         self.case_name = "tempest_smoke_serial"
294         self.MODE = "smoke"
295         self.OPTION = "--concur 1"
296
297
298 class TempestSmokeParallel(TempestCommon):
299
300     def __init__(self):
301         TempestCommon.__init__(self)
302         self.case_name = "tempest_smoke_parallel"
303         self.MODE = "smoke"
304         self.OPTION = ""
305
306
307 class TempestFullParallel(TempestCommon):
308
309     def __init__(self):
310         TempestCommon.__init__(self)
311         self.case_name = "tempest_full_parallel"
312         self.MODE = "full"
313
314
315 class TempestMultisite(TempestCommon):
316
317     def __init__(self):
318         TempestCommon.__init__(self)
319         self.case_name = "multisite"
320         self.MODE = "feature_multisite"
321         self.OPTION = "--concur 1"
322         conf_utils.configure_tempest_multisite(logger, self.DEPLOYMENT_DIR)
323
324
325 class TempestCustom(TempestCommon):
326
327     def __init__(self, mode, option):
328         TempestCommon.__init__(self)
329         self.case_name = "tempest_custom"
330         self.MODE = mode
331         self.OPTION = option