Temporarily disable shelve
[functest.git] / functest / opnfv_tests / openstack / tempest / tempest.py
index c204d52..216709f 100644 (file)
@@ -8,6 +8,8 @@
 # http://www.apache.org/licenses/LICENSE-2.0
 #
 
+"""Tempest testcases implementation."""
+
 from __future__ import division
 
 import logging
@@ -17,83 +19,157 @@ import shutil
 import subprocess
 import time
 
+from six.moves import configparser
+from xtesting.core import testcase
 import yaml
 
-from functest.core import testcase
-from functest.opnfv_tests.openstack.snaps import snaps_utils
+from functest.core import singlevm
 from functest.opnfv_tests.openstack.tempest import conf_utils
-from functest.utils.constants import CONST
-import functest.utils.functest_utils as ft_utils
-import functest.utils.openstack_utils as os_utils
-
-from snaps.openstack import create_flavor
-from snaps.openstack.create_flavor import FlavorSettings, OpenStackFlavor
-from snaps.openstack.create_project import ProjectSettings
-from snaps.openstack.create_network import NetworkSettings, SubnetSettings
-from snaps.openstack.create_user import UserSettings
-from snaps.openstack.tests import openstack_tests
-from snaps.openstack.utils import deploy_utils
+from functest.utils import config
+from functest.utils import env
 
+LOGGER = logging.getLogger(__name__)
 
-""" logging configuration """
-logger = logging.getLogger(__name__)
 
+class TempestCommon(singlevm.VmReady1):
+    # pylint: disable=too-many-instance-attributes
+    """TempestCommon testcases implementation class."""
 
-class TempestCommon(testcase.TestCase):
+    visibility = 'public'
+    shared_network = True
+    filename_alt = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
 
     def __init__(self, **kwargs):
+        if "case_name" not in kwargs:
+            kwargs["case_name"] = 'tempest'
         super(TempestCommon, self).__init__(**kwargs)
-        self.resources = TempestResourcesManager(**kwargs)
-        self.MODE = ""
-        self.OPTION = ""
-        self.VERIFIER_ID = conf_utils.get_verifier_id()
-        self.VERIFIER_REPO_DIR = conf_utils.get_verifier_repo_dir(
-            self.VERIFIER_ID)
-        self.DEPLOYMENT_ID = conf_utils.get_verifier_deployment_id()
-        self.DEPLOYMENT_DIR = conf_utils.get_verifier_deployment_dir(
-            self.VERIFIER_ID, self.DEPLOYMENT_ID)
-        self.VERIFICATION_ID = None
+        self.verifier_id = conf_utils.get_verifier_id()
+        self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
+            self.verifier_id)
+        self.deployment_id = conf_utils.get_verifier_deployment_id()
+        self.deployment_dir = conf_utils.get_verifier_deployment_dir(
+            self.verifier_id, self.deployment_id)
+        self.verification_id = None
+        self.res_dir = os.path.join(
+            getattr(config.CONF, 'dir_results'), self.case_name)
+        self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
+        self.list = os.path.join(self.res_dir, 'test_list.txt')
+        self.conf_file = None
+        self.image_alt = None
+        self.flavor_alt = None
+        self.services = []
+        try:
+            self.services = kwargs['run']['args']['services']
+        except Exception:  # pylint: disable=broad-except
+            pass
+        self.neutron_extensions = []
+        try:
+            self.neutron_extensions = kwargs['run']['args'][
+                'neutron_extensions']
+        except Exception:  # pylint: disable=broad-except
+            pass
+
+    def check_services(self):
+        """Check the mandatory services."""
+        for service in self.services:
+            try:
+                self.cloud.search_services(service)[0]
+            except Exception:  # pylint: disable=broad-except
+                self.is_skipped = True
+                break
+
+    def check_extensions(self):
+        """Check the mandatory network extensions."""
+        extensions = self.cloud.get_network_extensions()
+        for network_extension in self.neutron_extensions:
+            if network_extension not in extensions:
+                LOGGER.warning(
+                    "Cannot find Neutron extension: %s", network_extension)
+                self.is_skipped = True
+                break
+
+    def check_requirements(self):
+        self.check_services()
+        self.check_extensions()
 
     @staticmethod
     def read_file(filename):
+        """Read file and return content as a stripped list."""
         with open(filename) as src:
             return [line.strip() for line in src.readlines()]
 
-    def generate_test_list(self, verifier_repo_dir):
-        logger.debug("Generating test case list...")
-        if self.MODE == 'defcore':
-            shutil.copyfile(
-                conf_utils.TEMPEST_DEFCORE, conf_utils.TEMPEST_RAW_LIST)
-        elif self.MODE == 'custom':
+    @staticmethod
+    def get_verifier_result(verif_id):
+        """Retrieve verification results."""
+        result = {
+            'num_tests': 0,
+            'num_success': 0,
+            'num_failures': 0,
+            'num_skipped': 0
+        }
+        cmd = ["rally", "verify", "show", "--uuid", verif_id]
+        LOGGER.info("Showing result for a verification: '%s'.", cmd)
+        proc = subprocess.Popen(cmd,
+                                stdout=subprocess.PIPE,
+                                stderr=subprocess.STDOUT)
+        for line in proc.stdout:
+            LOGGER.info(line.rstrip())
+            new_line = line.replace(' ', '').split('|')
+            if 'Tests' in new_line:
+                break
+            if 'Testscount' in new_line:
+                result['num_tests'] = int(new_line[2])
+            elif 'Success' in new_line:
+                result['num_success'] = int(new_line[2])
+            elif 'Skipped' in new_line:
+                result['num_skipped'] = int(new_line[2])
+            elif 'Failures' in new_line:
+                result['num_failures'] = int(new_line[2])
+        return result
+
+    @staticmethod
+    def backup_tempest_config(conf_file, res_dir):
+        """
+        Copy config file to tempest results directory
+        """
+        if not os.path.exists(res_dir):
+            os.makedirs(res_dir)
+        shutil.copyfile(conf_file,
+                        os.path.join(res_dir, 'tempest.conf'))
+
+    def generate_test_list(self, **kwargs):
+        """Generate test list based on the test mode."""
+        LOGGER.debug("Generating test case list...")
+        self.backup_tempest_config(self.conf_file, '/etc')
+        if kwargs.get('mode') == 'custom':
             if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
                 shutil.copyfile(
-                    conf_utils.TEMPEST_CUSTOM, conf_utils.TEMPEST_RAW_LIST)
+                    conf_utils.TEMPEST_CUSTOM, self.list)
             else:
                 raise Exception("Tempest test list file %s NOT found."
                                 % conf_utils.TEMPEST_CUSTOM)
         else:
-            if self.MODE == 'smoke':
-                testr_mode = "smoke"
-            elif self.MODE == 'full':
-                testr_mode = ""
-            else:
-                testr_mode = 'tempest.api.' + self.MODE
-            cmd = ("cd {0};"
-                   "testr list-tests {1} > {2};"
-                   "cd -;".format(verifier_repo_dir,
-                                  testr_mode,
-                                  conf_utils.TEMPEST_RAW_LIST))
-            ft_utils.execute_command(cmd)
+            testr_mode = kwargs.get(
+                'mode', r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$')
+            cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
+                self.verifier_repo_dir, testr_mode, self.list)
+            output = subprocess.check_output(cmd, shell=True)
+            LOGGER.info("%s\n%s", cmd, output)
+        os.remove('/etc/tempest.conf')
 
     def apply_tempest_blacklist(self):
-        logger.debug("Applying tempest blacklist...")
-        cases_file = self.read_file(conf_utils.TEMPEST_RAW_LIST)
-        result_file = open(conf_utils.TEMPEST_LIST, 'w')
+        """Exclude blacklisted test cases."""
+        LOGGER.debug("Applying tempest blacklist...")
+        if os.path.exists(self.raw_list):
+            os.remove(self.raw_list)
+        os.rename(self.list, self.raw_list)
+        cases_file = self.read_file(self.raw_list)
+        result_file = open(self.list, 'w')
         black_tests = []
         try:
-            installer_type = CONST.__getattribute__('INSTALLER_TYPE')
-            deploy_scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
-            if (bool(installer_type) * bool(deploy_scenario)):
+            installer_type = env.get('INSTALLER_TYPE')
+            deploy_scenario = env.get('DEPLOY_SCENARIO')
+            if bool(installer_type) * bool(deploy_scenario):
                 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
                 # file
                 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
@@ -108,9 +184,9 @@ class TempestCommon(testcase.TestCase):
                         for test in tests:
                             black_tests.append(test)
                         break
-        except Exception:
+        except Exception:  # pylint: disable=broad-except
             black_tests = []
-            logger.debug("Tempest blacklist file does not exist.")
+            LOGGER.debug("Tempest blacklist file does not exist.")
 
         for cases_line in cases_file:
             for black_tests_line in black_tests:
@@ -120,394 +196,199 @@ class TempestCommon(testcase.TestCase):
                 result_file.write(str(cases_line) + '\n')
         result_file.close()
 
-    def run_verifier_tests(self):
-        self.OPTION += (" --load-list {} --detailed"
-                        .format(conf_utils.TEMPEST_LIST))
-
-        cmd_line = "rally verify start " + self.OPTION
-        logger.info("Starting Tempest test suite: '%s'." % cmd_line)
-
-        header = ("Tempest environment:\n"
-                  "  SUT: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
-                  (CONST.__getattribute__('INSTALLER_TYPE'),
-                   CONST.__getattribute__('DEPLOY_SCENARIO'),
-                   CONST.__getattribute__('NODE_NAME'),
-                   time.strftime("%a %b %d %H:%M:%S %Z %Y")))
+    def run_verifier_tests(self, **kwargs):
+        """Execute tempest test cases."""
+        cmd = ["rally", "verify", "start", "--load-list",
+               self.list]
+        cmd.extend(kwargs.get('option', []))
+        LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
 
         f_stdout = open(
-            os.path.join(conf_utils.TEMPEST_RESULTS_DIR, "tempest.log"), 'w+')
-        f_stderr = open(
-            os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
-                         "tempest-error.log"), 'w+')
-        f_env = open(os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
-                                  "environment.log"), 'w+')
-        f_env.write(header)
-
-        p = subprocess.Popen(
-            cmd_line, shell=True,
+            os.path.join(self.res_dir, "tempest.log"), 'w+')
+
+        proc = subprocess.Popen(
+            cmd,
             stdout=subprocess.PIPE,
-            stderr=f_stderr,
+            stderr=subprocess.STDOUT,
             bufsize=1)
 
-        with p.stdout:
-            for line in iter(p.stdout.readline, b''):
-                if re.search("\} tempest\.", line):
-                    logger.info(line.replace('\n', ''))
-                elif re.search('Starting verification', line):
-                    logger.info(line.replace('\n', ''))
-                    first_pos = line.index("UUID=") + len("UUID=")
-                    last_pos = line.index(") for deployment")
-                    self.VERIFICATION_ID = line[first_pos:last_pos]
-                    logger.debug('Verification UUID: %s', self.VERIFICATION_ID)
+        with proc.stdout:
+            for line in iter(proc.stdout.readline, b''):
+                if re.search(r"\} tempest\.", line):
+                    LOGGER.info(line.rstrip())
+                elif re.search(r'(?=\(UUID=(.*)\))', line):
+                    self.verification_id = re.search(
+                        r'(?=\(UUID=(.*)\))', line).group(1)
                 f_stdout.write(line)
-        p.wait()
-
+        proc.wait()
         f_stdout.close()
-        f_stderr.close()
-        f_env.close()
 
-    def parse_verifier_result(self):
-        if self.VERIFICATION_ID is None:
+        if self.verification_id is None:
             raise Exception('Verification UUID not found')
+        LOGGER.info('Verification UUID: %s', self.verification_id)
 
-        cmd_line = "rally verify show --uuid {}".format(self.VERIFICATION_ID)
-        logger.info("Showing result for a verification: '%s'." % cmd_line)
-        p = subprocess.Popen(cmd_line,
-                             shell=True,
-                             stdout=subprocess.PIPE,
-                             stderr=subprocess.STDOUT)
-        for line in p.stdout:
-            new_line = line.replace(' ', '').split('|')
-            if 'Tests' in new_line:
-                break
-
-            logger.info(line)
-            if 'Testscount' in new_line:
-                num_tests = new_line[2]
-            elif 'Success' in new_line:
-                num_success = new_line[2]
-            elif 'Skipped' in new_line:
-                num_skipped = new_line[2]
-            elif 'Failures' in new_line:
-                num_failures = new_line[2]
+        shutil.copy(
+            "{}/tempest.log".format(self.deployment_dir),
+            "{}/tempest.debug.log".format(self.res_dir))
 
+    def parse_verifier_result(self):
+        """Parse and save test results."""
+        stat = self.get_verifier_result(self.verification_id)
         try:
-            num_executed = int(num_tests) - int(num_skipped)
+            num_executed = stat['num_tests'] - stat['num_skipped']
             try:
-                self.result = 100 * int(num_success) / int(num_executed)
+                self.result = 100 * stat['num_success'] / num_executed
             except ZeroDivisionError:
                 self.result = 0
-                if int(num_tests) > 0:
-                    logger.info("All tests have been skipped")
+                if stat['num_tests'] > 0:
+                    LOGGER.info("All tests have been skipped")
                 else:
-                    logger.error("No test has been executed")
+                    LOGGER.error("No test has been executed")
                     return
 
-            with open(os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
+            with open(os.path.join(self.res_dir,
                                    "tempest.log"), 'r') as logfile:
                 output = logfile.read()
 
             success_testcases = []
-            for match in re.findall('.*\{0\} (.*?)[. ]*success ', output):
+            for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} success ',
+                                    output):
                 success_testcases.append(match)
             failed_testcases = []
-            for match in re.findall('.*\{0\} (.*?)[. ]*fail ', output):
+            for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} fail',
+                                    output):
                 failed_testcases.append(match)
             skipped_testcases = []
-            for match in re.findall('.*\{0\} (.*?)[. ]*skip:', output):
+            for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} skip:',
+                                    output):
                 skipped_testcases.append(match)
 
-            self.details = {"tests": int(num_tests),
-                            "failures": int(num_failures),
+            self.details = {"tests_number": stat['num_tests'],
+                            "success_number": stat['num_success'],
+                            "skipped_number": stat['num_skipped'],
+                            "failures_number": stat['num_failures'],
                             "success": success_testcases,
-                            "errors": failed_testcases,
-                            "skipped": skipped_testcases}
-        except Exception:
+                            "skipped": skipped_testcases,
+                            "failures": failed_testcases}
+        except Exception:  # pylint: disable=broad-except
             self.result = 0
 
-        logger.info("Tempest %s success_rate is %s%%"
-                    % (self.case_name, self.result))
-
-    def run(self):
+        LOGGER.info("Tempest %s success_rate is %s%%",
+                    self.case_name, self.result)
+
+    def generate_report(self):
+        """Generate verification report."""
+        html_file = os.path.join(self.res_dir,
+                                 "tempest-report.html")
+        cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
+               self.verification_id, "--to", html_file]
+        subprocess.Popen(cmd, stdout=subprocess.PIPE,
+                         stderr=subprocess.STDOUT)
+
+    def update_rally_regex(self, rally_conf='/etc/rally/rally.conf'):
+        """Set image name as tempest img_name_regex"""
+        rconfig = configparser.RawConfigParser()
+        rconfig.read(rally_conf)
+        if not rconfig.has_section('tempest'):
+            rconfig.add_section('tempest')
+        rconfig.set('tempest', 'img_name_regex', '^{}$'.format(
+            self.image.name))
+        with open(rally_conf, 'wb') as config_file:
+            rconfig.write(config_file)
+
+    def update_default_role(self, rally_conf='/etc/rally/rally.conf'):
+        """Detect and update the default role if required"""
+        role = self.get_default_role(self.cloud)
+        if not role:
+            return
+        rconfig = configparser.RawConfigParser()
+        rconfig.read(rally_conf)
+        if not rconfig.has_section('tempest'):
+            rconfig.add_section('tempest')
+        rconfig.set('tempest', 'swift_operator_role', role.name)
+        with open(rally_conf, 'wb') as config_file:
+            rconfig.write(config_file)
+
+    def update_rally_logs(self, rally_conf='/etc/rally/rally.conf'):
+        """Print rally logs in res dir"""
+        if not os.path.exists(self.res_dir):
+            os.makedirs(self.res_dir)
+        rconfig = configparser.RawConfigParser()
+        rconfig.read(rally_conf)
+        rconfig.set('DEFAULT', 'log-file', 'rally.log')
+        rconfig.set('DEFAULT', 'log_dir', self.res_dir)
+        with open(rally_conf, 'wb') as config_file:
+            rconfig.write(config_file)
 
+    @staticmethod
+    def clean_rally_conf(rally_conf='/etc/rally/rally.conf'):
+        """Clean Rally config"""
+        rconfig = configparser.RawConfigParser()
+        rconfig.read(rally_conf)
+        if rconfig.has_option('tempest', 'img_name_regex'):
+            rconfig.remove_option('tempest', 'img_name_regex')
+        if rconfig.has_option('tempest', 'swift_operator_role'):
+            rconfig.remove_option('tempest', 'swift_operator_role')
+        if rconfig.has_option('DEFAULT', 'log-file'):
+            rconfig.remove_option('DEFAULT', 'log-file')
+        if rconfig.has_option('DEFAULT', 'log_dir'):
+            rconfig.remove_option('DEFAULT', 'log_dir')
+        with open(rally_conf, 'wb') as config_file:
+            rconfig.write(config_file)
+
+    def configure(self, **kwargs):  # pylint: disable=unused-argument
+        """
+        Create all openstack resources for tempest-based testcases and write
+        tempest.conf.
+        """
+        if not os.path.exists(self.res_dir):
+            os.makedirs(self.res_dir)
+        compute_cnt = len(self.cloud.list_hypervisors())
+
+        self.image_alt = self.publish_image_alt()
+        self.flavor_alt = self.create_flavor_alt()
+        LOGGER.debug("flavor: %s", self.flavor_alt)
+
+        self.conf_file = conf_utils.configure_verifier(self.deployment_dir)
+        conf_utils.configure_tempest_update_params(
+            self.conf_file, network_name=self.network.name,
+            image_id=self.image.id,
+            flavor_id=self.flavor.id,
+            compute_cnt=compute_cnt,
+            image_alt_id=self.image_alt.id,
+            flavor_alt_id=self.flavor_alt.id)
+        self.backup_tempest_config(self.conf_file, self.res_dir)
+
+    def run(self, **kwargs):
         self.start_time = time.time()
         try:
-            if not os.path.exists(conf_utils.TEMPEST_RESULTS_DIR):
-                os.makedirs(conf_utils.TEMPEST_RESULTS_DIR)
-            resources = self.resources.create()
-            compute_cnt = snaps_utils.get_active_compute_cnt(
-                self.resources.os_creds)
-            conf_utils.configure_tempest(
-                self.DEPLOYMENT_DIR,
-                image_id=resources.get("image_id"),
-                flavor_id=resources.get("flavor_id"),
-                compute_cnt=compute_cnt)
-            self.generate_test_list(self.VERIFIER_REPO_DIR)
+            assert super(TempestCommon, self).run(
+                **kwargs) == testcase.TestCase.EX_OK
+            self.update_rally_regex()
+            self.update_default_role()
+            self.update_rally_logs()
+            shutil.copy("/etc/rally/rally.conf", self.res_dir)
+            self.configure(**kwargs)
+            self.generate_test_list(**kwargs)
             self.apply_tempest_blacklist()
-            self.run_verifier_tests()
+            self.run_verifier_tests(**kwargs)
             self.parse_verifier_result()
+            self.generate_report()
             res = testcase.TestCase.EX_OK
-        except Exception as e:
-            logger.error('Error with run: %s' % e)
+        except Exception:  # pylint: disable=broad-except
+            LOGGER.exception('Error with run')
+            self.result = 0
             res = testcase.TestCase.EX_RUN_ERROR
-        finally:
-            self.resources.cleanup()
-
         self.stop_time = time.time()
         return res
 
-    def create_snapshot(self):
-        """
-        Run the Tempest cleanup utility to initialize OS state.
-
-        :return: TestCase.EX_OK
-        """
-        logger.info("Initializing the saved state of the OpenStack deployment")
-
-        if not os.path.exists(conf_utils.TEMPEST_RESULTS_DIR):
-            os.makedirs(conf_utils.TEMPEST_RESULTS_DIR)
-
-        # Make sure that the verifier is configured
-        conf_utils.configure_verifier(self.DEPLOYMENT_DIR)
-
-        try:
-            os_utils.init_tempest_cleanup(
-                self.DEPLOYMENT_DIR, 'tempest.conf',
-                os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
-                             "tempest-cleanup-init.log"))
-        except Exception as err:
-            logger.error(str(err))
-            return testcase.TestCase.EX_RUN_ERROR
-
-        return super(TempestCommon, self).create_snapshot()
-
     def clean(self):
-        """
-        Run the Tempest cleanup utility to delete and destroy OS resources
-        created by Tempest.
-        """
-        logger.info("Destroying the resources created for refstack")
-
-        os_utils.perform_tempest_cleanup(
-            self.DEPLOYMENT_DIR, 'tempest.conf',
-            os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
-                         "tempest-cleanup.log")
-        )
-
-        return super(TempestCommon, self).clean()
-
-
-class TempestSmokeSerial(TempestCommon):
-
-    def __init__(self, **kwargs):
-        if "case_name" not in kwargs:
-            kwargs["case_name"] = 'tempest_smoke_serial'
-        TempestCommon.__init__(self, **kwargs)
-        self.MODE = "smoke"
-        self.OPTION = "--concurrency 1"
-
-
-class TempestSmokeParallel(TempestCommon):
-
-    def __init__(self, **kwargs):
-        if "case_name" not in kwargs:
-            kwargs["case_name"] = 'tempest_smoke_parallel'
-        TempestCommon.__init__(self, **kwargs)
-        self.MODE = "smoke"
-        self.OPTION = ""
-
-
-class TempestFullParallel(TempestCommon):
-
-    def __init__(self, **kwargs):
-        if "case_name" not in kwargs:
-            kwargs["case_name"] = 'tempest_full_parallel'
-        TempestCommon.__init__(self, **kwargs)
-        self.MODE = "full"
-
-
-class TempestCustom(TempestCommon):
-
-    def __init__(self, **kwargs):
-        if "case_name" not in kwargs:
-            kwargs["case_name"] = 'tempest_custom'
-        TempestCommon.__init__(self, **kwargs)
-        self.MODE = "custom"
-        self.OPTION = "--concurrency 1"
-
-
-class TempestDefcore(TempestCommon):
-
-    def __init__(self, **kwargs):
-        if "case_name" not in kwargs:
-            kwargs["case_name"] = 'tempest_defcore'
-        TempestCommon.__init__(self, **kwargs)
-        self.MODE = "defcore"
-        self.OPTION = "--concurrency 1"
-
-
-class TempestResourcesManager(object):
-
-    def __init__(self, **kwargs):
-        self.os_creds = None
-        if 'os_creds' in kwargs:
-            self.os_creds = kwargs['os_creds']
-        else:
-            self.os_creds = openstack_tests.get_credentials(
-                os_env_file=CONST.__getattribute__('openstack_creds'))
-
-        self.creators = list()
-
-        if hasattr(CONST, 'snaps_images_cirros'):
-            self.cirros_image_config = CONST.__getattribute__(
-                'snaps_images_cirros')
-        else:
-            self.cirros_image_config = None
-
-    def create(self, use_custom_images=False, use_custom_flavors=False,
-               create_project=False):
-        if create_project:
-            logger.debug("Creating project (tenant) for Tempest suite")
-            project_name = CONST.__getattribute__(
-                'tempest_identity_tenant_name')
-            project_creator = deploy_utils.create_project(
-                self.os_creds, ProjectSettings(
-                    name=project_name,
-                    description=CONST.__getattribute__(
-                        'tempest_identity_tenant_description')))
-            if (project_creator is None or
-                    project_creator.get_project() is None):
-                raise Exception("Failed to create tenant")
-            project_id = project_creator.get_project().id
-            self.creators.append(project_creator)
-
-            logger.debug("Creating user for Tempest suite")
-            user_creator = deploy_utils.create_user(
-                self.os_creds, UserSettings(
-                    name=CONST.__getattribute__('tempest_identity_user_name'),
-                    password=CONST.__getattribute__(
-                        'tempest_identity_user_password'),
-                    project_name=project_name))
-            if user_creator is None or user_creator.get_user() is None:
-                raise Exception("Failed to create user")
-            user_id = user_creator.get_user().id
-            self.creators.append(user_creator)
-        else:
-            project_name = None
-            project_id = None
-            user_id = None
-
-        logger.debug("Creating private network for Tempest suite")
-        network_creator = deploy_utils.create_network(
-            self.os_creds, NetworkSettings(
-                name=CONST.__getattribute__('tempest_private_net_name'),
-                project_name=project_name,
-                subnet_settings=[SubnetSettings(
-                    name=CONST.__getattribute__('tempest_private_subnet_name'),
-                    cidr=CONST.__getattribute__('tempest_private_subnet_cidr'))
-                ]))
-        if network_creator is None or network_creator.get_network() is None:
-            raise Exception("Failed to create private network")
-        self.creators.append(network_creator)
-
-        image_id = None
-        image_id_alt = None
-        flavor_id = None
-        flavor_id_alt = None
-
-        if (CONST.__getattribute__('tempest_use_custom_images') or
-           use_custom_images):
-            logger.debug("Creating image for Tempest suite")
-            image_base_name = CONST.__getattribute__('openstack_image_name')
-            os_image_settings = openstack_tests.cirros_image_settings(
-                image_base_name, public=True,
-                image_metadata=self.cirros_image_config)
-            logger.debug("Creating image for Tempest suite")
-            image_creator = deploy_utils.create_image(
-                self.os_creds, os_image_settings)
-            if image_creator is None:
-                raise Exception('Failed to create image')
-            self.creators.append(image_creator)
-            image_id = image_creator.get_image().id
-
-        if use_custom_images:
-            logger.debug("Creating 2nd image for Tempest suite")
-            image_base_name_alt = CONST.__getattribute__(
-                'openstack_image_name_alt')
-            os_image_settings_alt = openstack_tests.cirros_image_settings(
-                image_base_name_alt, public=True,
-                image_metadata=self.cirros_image_config)
-            logger.debug("Creating 2nd image for Tempest suite")
-            image_creator_alt = deploy_utils.create_image(
-                self.os_creds, os_image_settings_alt)
-            if image_creator_alt is None:
-                raise Exception('Failed to create image')
-            self.creators.append(image_creator_alt)
-            image_id_alt = image_creator_alt.get_image().id
-
-        if (CONST.__getattribute__('tempest_use_custom_flavors') or
-           use_custom_flavors):
-            logger.info("Creating flavor for Tempest suite")
-            scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
-            flavor_metadata = None
-            if 'ovs' in scenario or 'fdio' in scenario:
-                flavor_metadata = create_flavor.MEM_PAGE_SIZE_LARGE
-            flavor_creator = OpenStackFlavor(
-                self.os_creds, FlavorSettings(
-                    name=CONST.__getattribute__('openstack_flavor_name'),
-                    ram=CONST.__getattribute__('openstack_flavor_ram'),
-                    disk=CONST.__getattribute__('openstack_flavor_disk'),
-                    vcpus=CONST.__getattribute__('openstack_flavor_vcpus'),
-                    metadata=flavor_metadata))
-            flavor = flavor_creator.create()
-            if flavor is None:
-                raise Exception('Failed to create flavor')
-            self.creators.append(flavor_creator)
-            flavor_id = flavor.id
-
-        if use_custom_flavors:
-            logger.info("Creating 2nd flavor for Tempest suite")
-            scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
-            flavor_metadata_alt = None
-            if 'ovs' in scenario or 'fdio' in scenario:
-                flavor_metadata_alt = create_flavor.MEM_PAGE_SIZE_LARGE
-            flavor_creator_alt = OpenStackFlavor(
-                self.os_creds, FlavorSettings(
-                    name=CONST.__getattribute__('openstack_flavor_name_alt'),
-                    ram=CONST.__getattribute__('openstack_flavor_ram'),
-                    disk=CONST.__getattribute__('openstack_flavor_disk'),
-                    vcpus=CONST.__getattribute__('openstack_flavor_vcpus'),
-                    metadata=flavor_metadata_alt))
-            flavor_alt = flavor_creator_alt.create()
-            if flavor_alt is None:
-                raise Exception('Failed to create flavor')
-            self.creators.append(flavor_creator_alt)
-            flavor_id_alt = flavor_alt.id
-
-        print("RESOURCES CREATE: image_id: %s, image_id_alt: %s, "
-              "flavor_id: %s, flavor_id_alt: %s" % (
-                  image_id, image_id_alt, flavor_id, flavor_id_alt,))
-
-        result = {
-            'image_id': image_id,
-            'image_id_alt': image_id_alt,
-            'flavor_id': flavor_id,
-            'flavor_id_alt': flavor_id_alt
-        }
-
-        if create_project:
-            result['project_id'] = project_id
-            result['tenant_id'] = project_id  # for compatibility
-            result['user_id'] = user_id
-
-        return result
-
-    def cleanup(self):
         """
         Cleanup all OpenStack objects. Should be called on completion.
         """
-        for creator in reversed(self.creators):
-            try:
-                creator.clean()
-            except Exception as e:
-                logger.error('Unexpected error cleaning - %s', e)
+        self.clean_rally_conf()
+        if self.image_alt:
+            self.cloud.delete_image(self.image_alt)
+        if self.flavor_alt:
+            self.orig_cloud.delete_flavor(self.flavor_alt.id)
+        super(TempestCommon, self).clean()