Doesn't redirect stderr when getting verifier id
[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 json
16 import logging
17 import os
18 import re
19 import shutil
20 import subprocess
21 import time
22
23 import pkg_resources
24 from six.moves import configparser
25 from xtesting.core import testcase
26 import yaml
27
28 from functest.core import singlevm
29 from functest.opnfv_tests.openstack.rally import rally
30 from functest.utils import config
31 from functest.utils import env
32 from functest.utils import functest_utils
33
34 LOGGER = logging.getLogger(__name__)
35
36
37 class TempestCommon(singlevm.VmReady2):
38     # pylint: disable=too-many-instance-attributes,too-many-public-methods
39     """TempestCommon testcases implementation class."""
40
41     visibility = 'public'
42     filename_alt = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
43     shared_network = True
44     tempest_conf_yaml = pkg_resources.resource_filename(
45         'functest',
46         'opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml')
47     tempest_custom = pkg_resources.resource_filename(
48         'functest',
49         'opnfv_tests/openstack/tempest/custom_tests/test_list.txt')
50     tempest_blacklist = pkg_resources.resource_filename(
51         'functest',
52         'opnfv_tests/openstack/tempest/custom_tests/blacklist.yaml')
53     tempest_public_blacklist = pkg_resources.resource_filename(
54         'functest',
55         'opnfv_tests/openstack/tempest/custom_tests/public_blacklist.yaml')
56
57     def __init__(self, **kwargs):
58         if "case_name" not in kwargs:
59             kwargs["case_name"] = 'tempest'
60         super(TempestCommon, self).__init__(**kwargs)
61         assert self.orig_cloud
62         assert self.cloud
63         assert self.project
64         if self.orig_cloud.get_role("admin"):
65             self.role_name = "admin"
66         elif self.orig_cloud.get_role("Admin"):
67             self.role_name = "Admin"
68         else:
69             raise Exception("Cannot detect neither admin nor Admin")
70         self.orig_cloud.grant_role(
71             self.role_name, user=self.project.user.id,
72             project=self.project.project.id,
73             domain=self.project.domain.id)
74         self.orig_cloud.grant_role(
75             self.role_name, user=self.project.user.id,
76             domain=self.project.domain.id)
77         self.deployment_id = None
78         self.verifier_id = None
79         self.verifier_repo_dir = None
80         self.deployment_dir = None
81         self.verification_id = None
82         self.res_dir = os.path.join(
83             getattr(config.CONF, 'dir_results'), self.case_name)
84         self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
85         self.list = os.path.join(self.res_dir, 'test_list.txt')
86         self.conf_file = None
87         self.image_alt = None
88         self.flavor_alt = None
89         self.services = []
90         try:
91             self.services = kwargs['run']['args']['services']
92         except Exception:  # pylint: disable=broad-except
93             pass
94         self.neutron_extensions = []
95         try:
96             self.neutron_extensions = kwargs['run']['args'][
97                 'neutron_extensions']
98         except Exception:  # pylint: disable=broad-except
99             pass
100         self.deny_skipping = kwargs.get("deny_skipping", False)
101         self.tests_count = kwargs.get("tests_count", 0)
102
103     def check_services(self):
104         """Check the mandatory services."""
105         for service in self.services:
106             try:
107                 self.cloud.search_services(service)[0]
108             except Exception:  # pylint: disable=broad-except
109                 self.is_skipped = True
110                 break
111
112     def check_extensions(self):
113         """Check the mandatory network extensions."""
114         extensions = self.cloud.get_network_extensions()
115         for network_extension in self.neutron_extensions:
116             if network_extension not in extensions:
117                 LOGGER.warning(
118                     "Cannot find Neutron extension: %s", network_extension)
119                 self.is_skipped = True
120                 break
121
122     def check_requirements(self):
123         self.check_services()
124         self.check_extensions()
125         if self.is_skipped:
126             self.project.clean()
127
128     @staticmethod
129     def read_file(filename):
130         """Read file and return content as a stripped list."""
131         with open(filename) as src:
132             return [line.strip() for line in src.readlines()]
133
134     @staticmethod
135     def get_verifier_result(verif_id):
136         """Retrieve verification results."""
137         result = {
138             'num_tests': 0,
139             'num_success': 0,
140             'num_failures': 0,
141             'num_skipped': 0
142         }
143         cmd = ["rally", "verify", "show", "--uuid", verif_id]
144         LOGGER.info("Showing result for a verification: '%s'.", cmd)
145         proc = subprocess.Popen(cmd,
146                                 stdout=subprocess.PIPE,
147                                 stderr=subprocess.STDOUT)
148         for line in proc.stdout:
149             LOGGER.info(line.decode("utf-8").rstrip())
150             new_line = line.decode("utf-8").replace(' ', '').split('|')
151             if 'Tests' in new_line:
152                 break
153             if 'Testscount' in new_line:
154                 result['num_tests'] = int(new_line[2])
155             elif 'Success' in new_line:
156                 result['num_success'] = int(new_line[2])
157             elif 'Skipped' in new_line:
158                 result['num_skipped'] = int(new_line[2])
159             elif 'Failures' in new_line:
160                 result['num_failures'] = int(new_line[2])
161         return result
162
163     @staticmethod
164     def backup_tempest_config(conf_file, res_dir):
165         """
166         Copy config file to tempest results directory
167         """
168         if not os.path.exists(res_dir):
169             os.makedirs(res_dir)
170         shutil.copyfile(conf_file,
171                         os.path.join(res_dir, 'tempest.conf'))
172
173     @staticmethod
174     def create_verifier():
175         """Create new verifier"""
176         LOGGER.info("Create verifier from existing repo...")
177         cmd = ['rally', 'verify', 'delete-verifier',
178                '--id', str(getattr(config.CONF, 'tempest_verifier_name')),
179                '--force']
180         try:
181             output = subprocess.check_output(cmd)
182             LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
183         except subprocess.CalledProcessError:
184             pass
185
186         cmd = ['rally', 'verify', 'create-verifier',
187                '--source', str(getattr(config.CONF, 'dir_repo_tempest')),
188                '--name', str(getattr(config.CONF, 'tempest_verifier_name')),
189                '--type', 'tempest', '--system-wide']
190         output = subprocess.check_output(cmd)
191         LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
192         return TempestCommon.get_verifier_id()
193
194     @staticmethod
195     def get_verifier_id():
196         """
197         Returns verifier id for current Tempest
198         """
199         cmd = ("rally verify list-verifiers | awk '/" +
200                getattr(config.CONF, 'tempest_verifier_name') +
201                "/ {print $2}'")
202         proc = subprocess.Popen(cmd, shell=True,
203                                 stdout=subprocess.PIPE,
204                                 stderr=subprocess.DEVNULL)
205         verifier_uuid = proc.stdout.readline().rstrip()
206         return verifier_uuid.decode("utf-8")
207
208     @staticmethod
209     def get_verifier_repo_dir(verifier_id):
210         """
211         Returns installed verifier repo directory for Tempest
212         """
213         return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
214                             'verification',
215                             'verifier-{}'.format(verifier_id),
216                             'repo')
217
218     @staticmethod
219     def get_verifier_deployment_dir(verifier_id, deployment_id):
220         """
221         Returns Rally deployment directory for current verifier
222         """
223         return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
224                             'verification',
225                             'verifier-{}'.format(verifier_id),
226                             'for-deployment-{}'.format(deployment_id))
227
228     @staticmethod
229     def update_tempest_conf_file(conf_file, rconfig):
230         """Update defined paramters into tempest config file"""
231         with open(TempestCommon.tempest_conf_yaml) as yfile:
232             conf_yaml = yaml.safe_load(yfile)
233         if conf_yaml:
234             sections = rconfig.sections()
235             for section in conf_yaml:
236                 if section not in sections:
237                     rconfig.add_section(section)
238                 sub_conf = conf_yaml.get(section)
239                 for key, value in sub_conf.items():
240                     rconfig.set(section, key, value)
241
242         with open(conf_file, 'w') as config_file:
243             rconfig.write(config_file)
244
245     @staticmethod
246     def configure_tempest_update_params(
247             tempest_conf_file, image_id=None, flavor_id=None,
248             compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
249             admin_role_name='admin', cidr='192.168.120.0/24',
250             domain_id='default'):
251         # pylint: disable=too-many-branches,too-many-arguments
252         # pylint: disable=too-many-statements,too-many-locals
253         """
254         Add/update needed parameters into tempest.conf file
255         """
256         LOGGER.debug("Updating selected tempest.conf parameters...")
257         rconfig = configparser.RawConfigParser()
258         rconfig.read(tempest_conf_file)
259         rconfig.set(
260             'compute', 'volume_device_name', env.get('VOLUME_DEVICE_NAME'))
261         if image_id is not None:
262             rconfig.set('compute', 'image_ref', image_id)
263         if image_alt_id is not None:
264             rconfig.set('compute', 'image_ref_alt', image_alt_id)
265         if flavor_id is not None:
266             rconfig.set('compute', 'flavor_ref', flavor_id)
267         if flavor_alt_id is not None:
268             rconfig.set('compute', 'flavor_ref_alt', flavor_alt_id)
269         if compute_cnt > 1:
270             # enable multinode tests
271             rconfig.set('compute', 'min_compute_nodes', compute_cnt)
272             rconfig.set('compute-feature-enabled', 'live_migration', True)
273         if os.environ.get('OS_REGION_NAME'):
274             rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
275         if env.get("NEW_USER_ROLE").lower() != "member":
276             rconfig.set(
277                 'auth', 'tempest_roles',
278                 functest_utils.convert_list_to_ini([env.get("NEW_USER_ROLE")]))
279         if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
280             rconfig.set('auth', 'use_dynamic_credentials', False)
281             account_file = os.path.join(
282                 getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
283             assert os.path.exists(
284                 account_file), "{} doesn't exist".format(account_file)
285             rconfig.set('auth', 'test_accounts_file', account_file)
286         rconfig.set('identity', 'auth_version', 'v3')
287         rconfig.set('identity', 'admin_role', admin_role_name)
288         rconfig.set('identity', 'default_domain_id', domain_id)
289         if not rconfig.has_section('network'):
290             rconfig.add_section('network')
291         rconfig.set('network', 'default_network', cidr)
292         rconfig.set('network', 'project_network_cidr', cidr)
293         rconfig.set('network', 'project_networks_reachable', False)
294         rconfig.set(
295             'identity', 'v3_endpoint_type',
296             os.environ.get('OS_INTERFACE', 'public'))
297
298         sections = rconfig.sections()
299         services_list = [
300             'compute', 'volume', 'image', 'network', 'data-processing',
301             'object-storage', 'orchestration']
302         for service in services_list:
303             if service not in sections:
304                 rconfig.add_section(service)
305             rconfig.set(service, 'endpoint_type',
306                         os.environ.get('OS_INTERFACE', 'public'))
307
308         LOGGER.debug('Add/Update required params defined in tempest_conf.yaml '
309                      'into tempest.conf file')
310         TempestCommon.update_tempest_conf_file(tempest_conf_file, rconfig)
311
312     @staticmethod
313     def configure_verifier(deployment_dir):
314         """
315         Execute rally verify configure-verifier, which generates tempest.conf
316         """
317         cmd = ['rally', 'verify', 'configure-verifier', '--reconfigure',
318                '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]
319         output = subprocess.check_output(cmd)
320         LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
321
322         LOGGER.debug("Looking for tempest.conf file...")
323         tempest_conf_file = os.path.join(deployment_dir, "tempest.conf")
324         if not os.path.isfile(tempest_conf_file):
325             LOGGER.error("Tempest configuration file %s NOT found.",
326                          tempest_conf_file)
327             return None
328         return tempest_conf_file
329
330     def generate_test_list(self, **kwargs):
331         """Generate test list based on the test mode."""
332         LOGGER.debug("Generating test case list...")
333         self.backup_tempest_config(self.conf_file, '/etc')
334         if kwargs.get('mode') == 'custom':
335             if os.path.isfile(self.tempest_custom):
336                 shutil.copyfile(
337                     self.tempest_custom, self.list)
338             else:
339                 raise Exception("Tempest test list file %s NOT found."
340                                 % self.tempest_custom)
341         else:
342             testr_mode = kwargs.get(
343                 'mode', r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$')
344             cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
345                 self.verifier_repo_dir, testr_mode, self.list)
346             output = subprocess.check_output(cmd, shell=True)
347             LOGGER.info("%s\n%s", cmd, output.decode("utf-8"))
348         os.remove('/etc/tempest.conf')
349
350     def apply_tempest_blacklist(self, black_list):
351         """Exclude blacklisted test cases."""
352         LOGGER.debug("Applying tempest blacklist...")
353         if os.path.exists(self.raw_list):
354             os.remove(self.raw_list)
355         os.rename(self.list, self.raw_list)
356         cases_file = self.read_file(self.raw_list)
357         result_file = open(self.list, 'w')
358         black_tests = []
359         try:
360             deploy_scenario = env.get('DEPLOY_SCENARIO')
361             if bool(deploy_scenario):
362                 # if DEPLOY_SCENARIO is set we read the file
363                 black_list_file = open(black_list)
364                 black_list_yaml = yaml.safe_load(black_list_file)
365                 black_list_file.close()
366                 for item in black_list_yaml:
367                     scenarios = item['scenarios']
368                     in_it = rally.RallyBase.in_iterable_re
369                     if in_it(deploy_scenario, scenarios):
370                         tests = item['tests']
371                         black_tests.extend(tests)
372         except Exception:  # pylint: disable=broad-except
373             black_tests = []
374             LOGGER.debug("Tempest blacklist file does not exist.")
375
376         for cases_line in cases_file:
377             for black_tests_line in black_tests:
378                 if re.search(black_tests_line, cases_line):
379                     break
380             else:
381                 result_file.write(str(cases_line) + '\n')
382         result_file.close()
383
384     def run_verifier_tests(self, **kwargs):
385         """Execute tempest test cases."""
386         cmd = ["rally", "verify", "start", "--load-list",
387                self.list]
388         cmd.extend(kwargs.get('option', []))
389         LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
390
391         f_stdout = open(
392             os.path.join(self.res_dir, "tempest.log"), 'w+')
393
394         proc = subprocess.Popen(
395             cmd,
396             stdout=subprocess.PIPE,
397             stderr=subprocess.STDOUT,
398             bufsize=1)
399
400         with proc.stdout:
401             for line in iter(proc.stdout.readline, b''):
402                 if re.search(r"\} tempest\.", line.decode("utf-8")):
403                     LOGGER.info(line.rstrip())
404                 elif re.search(r'(?=\(UUID=(.*)\))', line.decode("utf-8")):
405                     self.verification_id = re.search(
406                         r'(?=\(UUID=(.*)\))', line.decode("utf-8")).group(1)
407                 f_stdout.write(line.decode("utf-8"))
408         proc.wait()
409         f_stdout.close()
410
411         if self.verification_id is None:
412             raise Exception('Verification UUID not found')
413         LOGGER.info('Verification UUID: %s', self.verification_id)
414
415         shutil.copy(
416             "{}/tempest.log".format(self.deployment_dir),
417             "{}/tempest.debug.log".format(self.res_dir))
418
419     def parse_verifier_result(self):
420         """Parse and save test results."""
421         stat = self.get_verifier_result(self.verification_id)
422         try:
423             num_executed = stat['num_tests'] - stat['num_skipped']
424             try:
425                 self.result = 100 * stat['num_success'] / num_executed
426             except ZeroDivisionError:
427                 self.result = 0
428                 if stat['num_tests'] > 0:
429                     LOGGER.info("All tests have been skipped")
430                 else:
431                     LOGGER.error("No test has been executed")
432                     return
433
434             with open(os.path.join(self.res_dir,
435                                    "rally.log"), 'r') as logfile:
436                 output = logfile.read()
437
438             success_testcases = []
439             for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} success ',
440                                     output):
441                 success_testcases.append(match)
442             failed_testcases = []
443             for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} fail',
444                                     output):
445                 failed_testcases.append(match)
446             skipped_testcases = []
447             for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} skip(?::| )',
448                                     output):
449                 skipped_testcases.append(match)
450
451             self.details = {"tests_number": stat['num_tests'],
452                             "success_number": stat['num_success'],
453                             "skipped_number": stat['num_skipped'],
454                             "failures_number": stat['num_failures'],
455                             "success": success_testcases,
456                             "skipped": skipped_testcases,
457                             "failures": failed_testcases}
458         except Exception:  # pylint: disable=broad-except
459             self.result = 0
460
461         LOGGER.info("Tempest %s success_rate is %s%%",
462                     self.case_name, self.result)
463
464     def update_rally_regex(self, rally_conf='/etc/rally/rally.conf'):
465         """Set image name as tempest img_name_regex"""
466         rconfig = configparser.RawConfigParser()
467         rconfig.read(rally_conf)
468         if not rconfig.has_section('openstack'):
469             rconfig.add_section('openstack')
470         rconfig.set('openstack', 'img_name_regex', '^{}$'.format(
471             self.image.name))
472         with open(rally_conf, 'w') as config_file:
473             rconfig.write(config_file)
474
475     def update_default_role(self, rally_conf='/etc/rally/rally.conf'):
476         """Detect and update the default role if required"""
477         role = self.get_default_role(self.cloud)
478         if not role:
479             return
480         rconfig = configparser.RawConfigParser()
481         rconfig.read(rally_conf)
482         if not rconfig.has_section('openstack'):
483             rconfig.add_section('openstack')
484         rconfig.set('openstack', 'swift_operator_role', role.name)
485         with open(rally_conf, 'w') as config_file:
486             rconfig.write(config_file)
487
488     @staticmethod
489     def clean_rally_conf(rally_conf='/etc/rally/rally.conf'):
490         """Clean Rally config"""
491         rconfig = configparser.RawConfigParser()
492         rconfig.read(rally_conf)
493         if rconfig.has_option('openstack', 'img_name_regex'):
494             rconfig.remove_option('openstack', 'img_name_regex')
495         if rconfig.has_option('openstack', 'swift_operator_role'):
496             rconfig.remove_option('openstack', 'swift_operator_role')
497         with open(rally_conf, 'w') as config_file:
498             rconfig.write(config_file)
499
500     def update_network_section(self):
501         """Update network section in tempest.conf"""
502         rconfig = configparser.RawConfigParser()
503         rconfig.read(self.conf_file)
504         if not rconfig.has_section('network'):
505             rconfig.add_section('network')
506         rconfig.set('network', 'public_network_id', self.ext_net.id)
507         rconfig.set('network', 'floating_network_name', self.ext_net.name)
508         with open(self.conf_file, 'w') as config_file:
509             rconfig.write(config_file)
510
511     def update_compute_section(self):
512         """Update compute section in tempest.conf"""
513         rconfig = configparser.RawConfigParser()
514         rconfig.read(self.conf_file)
515         if not rconfig.has_section('compute'):
516             rconfig.add_section('compute')
517         rconfig.set('compute', 'fixed_network_name', self.network.name)
518         with open(self.conf_file, 'w') as config_file:
519             rconfig.write(config_file)
520
521     def update_scenario_section(self):
522         """Update scenario section in tempest.conf"""
523         rconfig = configparser.RawConfigParser()
524         rconfig.read(self.conf_file)
525         filename = getattr(
526             config.CONF, '{}_image'.format(self.case_name), self.filename)
527         if not rconfig.has_section('scenario'):
528             rconfig.add_section('scenario')
529         rconfig.set('scenario', 'img_file', os.path.basename(filename))
530         rconfig.set('scenario', 'img_dir', os.path.dirname(filename))
531         rconfig.set('scenario', 'img_disk_format', getattr(
532             config.CONF, '{}_image_format'.format(self.case_name),
533             self.image_format))
534         extra_properties = self.extra_properties.copy()
535         if env.get('IMAGE_PROPERTIES'):
536             extra_properties.update(
537                 functest_utils.convert_ini_to_dict(
538                     env.get('IMAGE_PROPERTIES')))
539         extra_properties.update(
540             getattr(config.CONF, '{}_extra_properties'.format(
541                 self.case_name), {}))
542         rconfig.set(
543             'scenario', 'img_properties',
544             functest_utils.convert_dict_to_ini(extra_properties))
545         with open(self.conf_file, 'w') as config_file:
546             rconfig.write(config_file)
547
548     def configure(self, **kwargs):  # pylint: disable=unused-argument
549         """
550         Create all openstack resources for tempest-based testcases and write
551         tempest.conf.
552         """
553         if not os.path.exists(self.res_dir):
554             os.makedirs(self.res_dir)
555         self.deployment_id = rally.RallyBase.create_rally_deployment(
556             environ=self.project.get_environ())
557         if not self.deployment_id:
558             raise Exception("Deployment create failed")
559         self.verifier_id = self.create_verifier()
560         if not self.verifier_id:
561             raise Exception("Verifier create failed")
562         self.verifier_repo_dir = self.get_verifier_repo_dir(
563             self.verifier_id)
564         self.deployment_dir = self.get_verifier_deployment_dir(
565             self.verifier_id, self.deployment_id)
566
567         compute_cnt = self.count_hypervisors()
568         self.image_alt = self.publish_image_alt()
569         self.flavor_alt = self.create_flavor_alt()
570         LOGGER.debug("flavor: %s", self.flavor_alt)
571
572         self.conf_file = self.configure_verifier(self.deployment_dir)
573         if not self.conf_file:
574             raise Exception("Tempest verifier configuring failed")
575         self.configure_tempest_update_params(
576             self.conf_file,
577             image_id=self.image.id,
578             flavor_id=self.flavor.id,
579             compute_cnt=compute_cnt,
580             image_alt_id=self.image_alt.id,
581             flavor_alt_id=self.flavor_alt.id,
582             admin_role_name=self.role_name, cidr=self.cidr,
583             domain_id=self.project.domain.id)
584         self.update_network_section()
585         self.update_compute_section()
586         self.update_scenario_section()
587         self.backup_tempest_config(self.conf_file, self.res_dir)
588
589     def run(self, **kwargs):
590         self.start_time = time.time()
591         try:
592             assert super(TempestCommon, self).run(
593                 **kwargs) == testcase.TestCase.EX_OK
594             if not os.path.exists(self.res_dir):
595                 os.makedirs(self.res_dir)
596             self.update_rally_regex()
597             self.update_default_role()
598             rally.RallyBase.update_rally_logs(self.res_dir)
599             shutil.copy("/etc/rally/rally.conf", self.res_dir)
600             self.configure(**kwargs)
601             self.generate_test_list(**kwargs)
602             self.apply_tempest_blacklist(TempestCommon.tempest_blacklist)
603             if env.get('PUBLIC_ENDPOINT_ONLY').lower() == 'true':
604                 self.apply_tempest_blacklist(
605                     TempestCommon.tempest_public_blacklist)
606             self.run_verifier_tests(**kwargs)
607             self.parse_verifier_result()
608             rally.RallyBase.verify_report(
609                 os.path.join(self.res_dir, "tempest-report.html"),
610                 self.verification_id)
611             rally.RallyBase.verify_report(
612                 os.path.join(self.res_dir, "tempest-report.xml"),
613                 self.verification_id, "junit-xml")
614             res = testcase.TestCase.EX_OK
615         except Exception:  # pylint: disable=broad-except
616             LOGGER.exception('Error with run')
617             self.result = 0
618             res = testcase.TestCase.EX_RUN_ERROR
619         self.stop_time = time.time()
620         return res
621
622     def clean(self):
623         """
624         Cleanup all OpenStack objects. Should be called on completion.
625         """
626         self.clean_rally_conf()
627         rally.RallyBase.clean_rally_logs()
628         if self.image_alt:
629             self.cloud.delete_image(self.image_alt)
630         if self.flavor_alt:
631             self.orig_cloud.delete_flavor(self.flavor_alt.id)
632         super(TempestCommon, self).clean()
633
634     def is_successful(self):
635         """The overall result of the test."""
636         skips = self.details.get("skipped_number", 0)
637         if skips > 0 and self.deny_skipping:
638             return testcase.TestCase.EX_TESTCASE_FAILED
639         if self.tests_count and (
640                 self.details.get("tests_number", 0) != self.tests_count):
641             return testcase.TestCase.EX_TESTCASE_FAILED
642         return super(TempestCommon, self).is_successful()
643
644
645 class TempestScenario(TempestCommon):
646     """Tempest scenario testcase implementation class."""
647
648     quota_instances = -1
649     quota_cores = -1
650
651     def run(self, **kwargs):
652         self.orig_cloud.set_compute_quotas(
653             self.project.project.name,
654             instances=self.quota_instances,
655             cores=self.quota_cores)
656         return super(TempestScenario, self).run(**kwargs)
657
658
659 class TempestHorizon(TempestCommon):
660     """Tempest Horizon testcase implementation class."""
661
662     def configure(self, **kwargs):
663         super(TempestHorizon, self).configure(**kwargs)
664         rconfig = configparser.RawConfigParser()
665         rconfig.read(self.conf_file)
666         if not rconfig.has_section('dashboard'):
667             rconfig.add_section('dashboard')
668         rconfig.set('dashboard', 'dashboard_url', env.get('DASHBOARD_URL'))
669         with open(self.conf_file, 'w') as config_file:
670             rconfig.write(config_file)
671         self.backup_tempest_config(self.conf_file, self.res_dir)