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