Merge "Use functest repo variable"
[functest.git] / functest / opnfv_tests / openstack / tempest / tempest.py
1 #!/usr/bin/env 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 """Tempest testcases implementation."""
12
13 from __future__ import division
14
15 import logging
16 import os
17 import re
18 import shutil
19 import subprocess
20 import time
21 import uuid
22
23 import yaml
24
25 from functest.core import testcase
26 from functest.opnfv_tests.openstack.snaps import snaps_utils
27 from functest.opnfv_tests.openstack.tempest import conf_utils
28 from functest.utils import config
29 from functest.utils import env
30 import functest.utils.functest_utils as ft_utils
31
32 from snaps.config.flavor import FlavorConfig
33 from snaps.config.network import NetworkConfig, SubnetConfig
34 from snaps.config.project import ProjectConfig
35 from snaps.config.user import UserConfig
36
37 from snaps.openstack import create_flavor
38 from snaps.openstack.create_flavor import OpenStackFlavor
39 from snaps.openstack.tests import openstack_tests
40 from snaps.openstack.utils import deploy_utils
41
42
43 LOGGER = logging.getLogger(__name__)
44
45
46 class TempestCommon(testcase.TestCase):
47     # pylint: disable=too-many-instance-attributes
48     """TempestCommon testcases implementation class."""
49
50     def __init__(self, **kwargs):
51         super(TempestCommon, self).__init__(**kwargs)
52         self.resources = TempestResourcesManager(**kwargs)
53         self.mode = ""
54         self.option = []
55         self.verifier_id = conf_utils.get_verifier_id()
56         self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
57             self.verifier_id)
58         self.deployment_id = conf_utils.get_verifier_deployment_id()
59         self.deployment_dir = conf_utils.get_verifier_deployment_dir(
60             self.verifier_id, self.deployment_id)
61         self.verification_id = None
62
63     @staticmethod
64     def read_file(filename):
65         """Read file and return content as a stripped list."""
66         with open(filename) as src:
67             return [line.strip() for line in src.readlines()]
68
69     @staticmethod
70     def get_verifier_result(verif_id):
71         """Retrieve verification results."""
72         result = {
73             'num_tests': 0,
74             'num_success': 0,
75             'num_failures': 0,
76             'num_skipped': 0
77         }
78         cmd = ["rally", "verify", "show", "--uuid", verif_id]
79         LOGGER.info("Showing result for a verification: '%s'.", cmd)
80         proc = subprocess.Popen(cmd,
81                                 stdout=subprocess.PIPE,
82                                 stderr=subprocess.STDOUT)
83         for line in proc.stdout:
84             new_line = line.replace(' ', '').split('|')
85             if 'Tests' in new_line:
86                 break
87             LOGGER.info(line)
88             if 'Testscount' in new_line:
89                 result['num_tests'] = int(new_line[2])
90             elif 'Success' in new_line:
91                 result['num_success'] = int(new_line[2])
92             elif 'Skipped' in new_line:
93                 result['num_skipped'] = int(new_line[2])
94             elif 'Failures' in new_line:
95                 result['num_failures'] = int(new_line[2])
96         return result
97
98     def generate_test_list(self, verifier_repo_dir):
99         """Generate test list based on the test mode."""
100         LOGGER.debug("Generating test case list...")
101         if self.mode == 'defcore':
102             shutil.copyfile(
103                 conf_utils.TEMPEST_DEFCORE, conf_utils.TEMPEST_RAW_LIST)
104         elif self.mode == 'custom':
105             if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
106                 shutil.copyfile(
107                     conf_utils.TEMPEST_CUSTOM, conf_utils.TEMPEST_RAW_LIST)
108             else:
109                 raise Exception("Tempest test list file %s NOT found."
110                                 % conf_utils.TEMPEST_CUSTOM)
111         else:
112             if self.mode == 'smoke':
113                 testr_mode = r"'tempest\.(api|scenario).*\[.*\bsmoke\b.*\]'"
114             elif self.mode == 'full':
115                 testr_mode = r"'^tempest\.'"
116             else:
117                 testr_mode = self.mode
118             cmd = ("cd {0};"
119                    "testr list-tests {1} > {2};"
120                    "cd -;".format(verifier_repo_dir,
121                                   testr_mode,
122                                   conf_utils.TEMPEST_RAW_LIST))
123             ft_utils.execute_command(cmd)
124
125     def apply_tempest_blacklist(self):
126         """Exclude blacklisted test cases."""
127         LOGGER.debug("Applying tempest blacklist...")
128         cases_file = self.read_file(conf_utils.TEMPEST_RAW_LIST)
129         result_file = open(conf_utils.TEMPEST_LIST, 'w')
130         black_tests = []
131         try:
132             installer_type = env.get('INSTALLER_TYPE')
133             deploy_scenario = env.get('DEPLOY_SCENARIO')
134             if bool(installer_type) * bool(deploy_scenario):
135                 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
136                 # file
137                 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
138                 black_list_yaml = yaml.safe_load(black_list_file)
139                 black_list_file.close()
140                 for item in black_list_yaml:
141                     scenarios = item['scenarios']
142                     installers = item['installers']
143                     if (deploy_scenario in scenarios and
144                             installer_type in installers):
145                         tests = item['tests']
146                         for test in tests:
147                             black_tests.append(test)
148                         break
149         except Exception:  # pylint: disable=broad-except
150             black_tests = []
151             LOGGER.debug("Tempest blacklist file does not exist.")
152
153         for cases_line in cases_file:
154             for black_tests_line in black_tests:
155                 if black_tests_line in cases_line:
156                     break
157             else:
158                 result_file.write(str(cases_line) + '\n')
159         result_file.close()
160
161     def run_verifier_tests(self):
162         """Execute tempest test cases."""
163         cmd = ["rally", "verify", "start", "--load-list",
164                conf_utils.TEMPEST_LIST]
165         cmd.extend(self.option)
166         LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
167
168         f_stdout = open(
169             os.path.join(conf_utils.TEMPEST_RESULTS_DIR, "tempest.log"), 'w+')
170         f_stderr = open(
171             os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
172                          "tempest-error.log"), 'w+')
173
174         proc = subprocess.Popen(
175             cmd,
176             stdout=subprocess.PIPE,
177             stderr=f_stderr,
178             bufsize=1)
179
180         with proc.stdout:
181             for line in iter(proc.stdout.readline, b''):
182                 if re.search(r"\} tempest\.", line):
183                     LOGGER.info(line.replace('\n', ''))
184                 elif re.search('Starting verification', line):
185                     LOGGER.info(line.replace('\n', ''))
186                     first_pos = line.index("UUID=") + len("UUID=")
187                     last_pos = line.index(") for deployment")
188                     self.verification_id = line[first_pos:last_pos]
189                     LOGGER.debug('Verification UUID: %s', self.verification_id)
190                 f_stdout.write(line)
191         proc.wait()
192
193         f_stdout.close()
194         f_stderr.close()
195
196         if self.verification_id is None:
197             raise Exception('Verification UUID not found')
198
199     def parse_verifier_result(self):
200         """Parse and save test results."""
201         stat = self.get_verifier_result(self.verification_id)
202         try:
203             num_executed = stat['num_tests'] - stat['num_skipped']
204             try:
205                 self.result = 100 * stat['num_success'] / num_executed
206             except ZeroDivisionError:
207                 self.result = 0
208                 if stat['num_tests'] > 0:
209                     LOGGER.info("All tests have been skipped")
210                 else:
211                     LOGGER.error("No test has been executed")
212                     return
213
214             with open(os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
215                                    "tempest.log"), 'r') as logfile:
216                 output = logfile.read()
217
218             success_testcases = []
219             for match in re.findall(r'.*\{0\} (.*?)[. ]*success ', output):
220                 success_testcases.append(match)
221             failed_testcases = []
222             for match in re.findall(r'.*\{0\} (.*?)[. ]*fail ', output):
223                 failed_testcases.append(match)
224             skipped_testcases = []
225             for match in re.findall(r'.*\{0\} (.*?)[. ]*skip:', output):
226                 skipped_testcases.append(match)
227
228             self.details = {"tests": stat['num_tests'],
229                             "failures": stat['num_failures'],
230                             "success": success_testcases,
231                             "skipped": skipped_testcases,
232                             "errors": failed_testcases}
233         except Exception:  # pylint: disable=broad-except
234             self.result = 0
235
236         LOGGER.info("Tempest %s success_rate is %s%%",
237                     self.case_name, self.result)
238
239     def generate_report(self):
240         """Generate verification report."""
241         html_file = os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
242                                  "tempest-report.html")
243         cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
244                self.verification_id, "--to", html_file]
245         subprocess.Popen(cmd, stdout=subprocess.PIPE,
246                          stderr=subprocess.STDOUT)
247
248     def run(self, **kwargs):
249
250         self.start_time = time.time()
251         try:
252             if not os.path.exists(conf_utils.TEMPEST_RESULTS_DIR):
253                 os.makedirs(conf_utils.TEMPEST_RESULTS_DIR)
254             resources = self.resources.create()
255             compute_cnt = snaps_utils.get_active_compute_cnt(
256                 self.resources.os_creds)
257             conf_utils.configure_tempest(
258                 self.deployment_dir,
259                 network_name=resources.get("network_name"),
260                 image_id=resources.get("image_id"),
261                 flavor_id=resources.get("flavor_id"),
262                 compute_cnt=compute_cnt)
263             self.generate_test_list(self.verifier_repo_dir)
264             self.apply_tempest_blacklist()
265             self.run_verifier_tests()
266             self.parse_verifier_result()
267             self.generate_report()
268             res = testcase.TestCase.EX_OK
269         except Exception as err:  # pylint: disable=broad-except
270             LOGGER.error('Error with run: %s', err)
271             res = testcase.TestCase.EX_RUN_ERROR
272         finally:
273             self.resources.cleanup()
274
275         self.stop_time = time.time()
276         return res
277
278
279 class TempestSmokeSerial(TempestCommon):
280     """Tempest smoke serial testcase implementation."""
281     def __init__(self, **kwargs):
282         if "case_name" not in kwargs:
283             kwargs["case_name"] = 'tempest_smoke_serial'
284         TempestCommon.__init__(self, **kwargs)
285         self.mode = "smoke"
286         self.option = ["--concurrency", "1"]
287
288
289 class TempestSmokeParallel(TempestCommon):
290     """Tempest smoke parallel testcase implementation."""
291     def __init__(self, **kwargs):
292         if "case_name" not in kwargs:
293             kwargs["case_name"] = 'tempest_smoke_parallel'
294         TempestCommon.__init__(self, **kwargs)
295         self.mode = "smoke"
296
297
298 class TempestFullParallel(TempestCommon):
299     """Tempest full parallel testcase implementation."""
300     def __init__(self, **kwargs):
301         if "case_name" not in kwargs:
302             kwargs["case_name"] = 'tempest_full_parallel'
303         TempestCommon.__init__(self, **kwargs)
304         self.mode = "full"
305
306
307 class TempestCustom(TempestCommon):
308     """Tempest custom testcase implementation."""
309     def __init__(self, **kwargs):
310         if "case_name" not in kwargs:
311             kwargs["case_name"] = 'tempest_custom'
312         TempestCommon.__init__(self, **kwargs)
313         self.mode = "custom"
314         self.option = ["--concurrency", "1"]
315
316
317 class TempestDefcore(TempestCommon):
318     """Tempest Defcore testcase implementation."""
319     def __init__(self, **kwargs):
320         if "case_name" not in kwargs:
321             kwargs["case_name"] = 'tempest_defcore'
322         TempestCommon.__init__(self, **kwargs)
323         self.mode = "defcore"
324         self.option = ["--concurrency", "1"]
325
326
327 class TempestResourcesManager(object):
328     """Tempest resource manager."""
329     def __init__(self, **kwargs):
330         self.os_creds = kwargs.get('os_creds') or snaps_utils.get_credentials()
331         self.guid = '-' + str(uuid.uuid4())
332         self.creators = list()
333         self.cirros_image_config = getattr(
334             config.CONF, 'snaps_images_cirros', None)
335
336     def _create_project(self):
337         """Create project for tests."""
338         project_creator = deploy_utils.create_project(
339             self.os_creds, ProjectConfig(
340                 name=getattr(
341                     config.CONF, 'tempest_identity_tenant_name') + self.guid,
342                 description=getattr(
343                     config.CONF, 'tempest_identity_tenant_description')))
344         if project_creator is None or project_creator.get_project() is None:
345             raise Exception("Failed to create tenant")
346         self.creators.append(project_creator)
347         return project_creator.get_project().id
348
349     def _create_user(self):
350         """Create user for tests."""
351         user_creator = deploy_utils.create_user(
352             self.os_creds, UserConfig(
353                 name=getattr(
354                     config.CONF, 'tempest_identity_user_name') + self.guid,
355                 password=getattr(
356                     config.CONF, 'tempest_identity_user_password'),
357                 project_name=getattr(
358                     config.CONF, 'tempest_identity_tenant_name') + self.guid))
359         if user_creator is None or user_creator.get_user() is None:
360             raise Exception("Failed to create user")
361         self.creators.append(user_creator)
362         return user_creator.get_user().id
363
364     def _create_network(self, project_name):
365         """Create network for tests."""
366         tempest_network_type = None
367         tempest_physical_network = None
368         tempest_segmentation_id = None
369
370         tempest_network_type = getattr(
371             config.CONF, 'tempest_network_type', None)
372         tempest_physical_network = getattr(
373             config.CONF, 'tempest_physical_network', None)
374         tempest_segmentation_id = getattr(
375             config.CONF, 'tempest_segmentation_id', None)
376         tempest_net_name = getattr(
377             config.CONF, 'tempest_private_net_name') + self.guid
378
379         network_creator = deploy_utils.create_network(
380             self.os_creds, NetworkConfig(
381                 name=tempest_net_name,
382                 project_name=project_name,
383                 network_type=tempest_network_type,
384                 physical_network=tempest_physical_network,
385                 segmentation_id=tempest_segmentation_id,
386                 subnet_settings=[SubnetConfig(
387                     name=getattr(
388                         config.CONF,
389                         'tempest_private_subnet_name') + self.guid,
390                     project_name=project_name,
391                     cidr=getattr(
392                         config.CONF, 'tempest_private_subnet_cidr'))]))
393         if network_creator is None or network_creator.get_network() is None:
394             raise Exception("Failed to create private network")
395         self.creators.append(network_creator)
396         return tempest_net_name
397
398     def _create_image(self, name):
399         """Create image for tests"""
400         os_image_settings = openstack_tests.cirros_image_settings(
401             name, public=True,
402             image_metadata=self.cirros_image_config)
403         image_creator = deploy_utils.create_image(
404             self.os_creds, os_image_settings)
405         if image_creator is None:
406             raise Exception('Failed to create image')
407         self.creators.append(image_creator)
408         return image_creator.get_image().id
409
410     def _create_flavor(self, name):
411         """Create flavor for tests."""
412         scenario = env.get('DEPLOY_SCENARIO')
413         flavor_metadata = None
414         if 'ovs' in scenario or 'fdio' in scenario:
415             flavor_metadata = create_flavor.MEM_PAGE_SIZE_LARGE
416         flavor_creator = OpenStackFlavor(
417             self.os_creds, FlavorConfig(
418                 name=name,
419                 ram=getattr(config.CONF, 'openstack_flavor_ram'),
420                 disk=getattr(config.CONF, 'openstack_flavor_disk'),
421                 vcpus=getattr(config.CONF, 'openstack_flavor_vcpus'),
422                 metadata=flavor_metadata))
423         flavor = flavor_creator.create()
424         if flavor is None:
425             raise Exception('Failed to create flavor')
426         self.creators.append(flavor_creator)
427         return flavor.id
428
429     def create(self, use_custom_images=False, use_custom_flavors=False,
430                create_project=False):
431         """Create resources for Tempest test suite."""
432         result = {
433             'tempest_net_name': None,
434             'image_id': None,
435             'image_id_alt': None,
436             'flavor_id': None,
437             'flavor_id_alt': None
438         }
439         project_name = None
440
441         if create_project:
442             LOGGER.debug("Creating project and user for Tempest suite")
443             project_name = getattr(
444                 config.CONF, 'tempest_identity_tenant_name') + self.guid
445             result['project_id'] = self._create_project()
446             result['user_id'] = self._create_user()
447             result['tenant_id'] = result['project_id']  # for compatibility
448
449         LOGGER.debug("Creating private network for Tempest suite")
450         result['tempest_net_name'] = self._create_network(project_name)
451
452         LOGGER.debug("Creating image for Tempest suite")
453         image_name = getattr(config.CONF, 'openstack_image_name') + self.guid
454         result['image_id'] = self._create_image(image_name)
455
456         if use_custom_images:
457             LOGGER.debug("Creating 2nd image for Tempest suite")
458             image_name = getattr(
459                 config.CONF, 'openstack_image_name_alt') + self.guid
460             result['image_id_alt'] = self._create_image(image_name)
461
462         if (getattr(config.CONF, 'tempest_use_custom_flavors') == 'True' or
463                 use_custom_flavors):
464             LOGGER.info("Creating flavor for Tempest suite")
465             name = getattr(config.CONF, 'openstack_flavor_name') + self.guid
466             result['flavor_id'] = self._create_flavor(name)
467
468         if use_custom_flavors:
469             LOGGER.info("Creating 2nd flavor for Tempest suite")
470             scenario = env.get('DEPLOY_SCENARIO')
471             if 'ovs' in scenario or 'fdio' in scenario:
472                 setattr(config.CONF, 'openstack_flavor_ram', 1024)
473             name = getattr(
474                 config.CONF, 'openstack_flavor_name_alt') + self.guid
475             result['flavor_id_alt'] = self._create_flavor(name)
476
477         return result
478
479     def cleanup(self):
480         """
481         Cleanup all OpenStack objects. Should be called on completion.
482         """
483         for creator in reversed(self.creators):
484             try:
485                 creator.clean()
486             except Exception as err:  # pylint: disable=broad-except
487                 LOGGER.error('Unexpected error cleaning - %s', err)