LOG = oslo_logging.getLogger(__name__)
class TestCase(base.BaseTestCase):
    def setUp(self):
    def _common_cleanup(self):
    def log_level(self, level):
    def mock_object(self, obj, attr_name, new_attr=None, **kwargs):
    def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
        def raise_assertion(msg): class Paths(object):
    @staticmethod
    def _find_paths_to_remove(paths, parent_connections):
        """
        :type paths: dict
        :type parent_connections: list
        """
        paths_to_remove = []
        for key in paths.keys():
            found = False
            for connection in parent_connections:
                if key == Path.connection_to_str(connection):
                    found = True
                    break
            if not found:
                paths_to_remove.append(key)
        return paths_to_remove

    @staticmethod
    def _add_new_connection(paths, parent_connections):
        for connection in parent_connections:
            if not isinstance(connection, dict):
                raise (Exception("Unknown %s type of %s " %
                                 (type(connection), connection)))
            key = Path.connection_to_str(connection)
            if key not in paths:
                paths[key] = Path(connection)

    @staticmethod
    def rebuild_multipath(paths, parent_connections, multipath_name,
                          multipath_path):
        """
        :type paths: dict
        :type parent_connections: list
        :type multipath_name: str
        :type multipath_path: str
        """
        LOG.debug("Virtman: begin to rebuild multipath...")

        # Get keys of paths to remove, and add new paths
        paths_to_remove = Paths._find_paths_to_remove(paths, parent_connections)
        Paths._add_new_connection(paths, parent_connections)

        # Connect new paths
        for key in paths.keys():
            if key not in paths_to_remove and not paths[key].connected:
                Path.connect(paths[key])

        # Rebuild multipath device
        disks = [paths[key].device_path for key in paths.keys()
                 if key not in paths_to_remove and paths[key].connected]

        if len(disks) > 0:
            if not multipath_path:
                multipath_path = Paths.create_multipath(multipath_name, disks)
            else:
                multipath_path = multipath_path
                Paths.reload_multipath(multipath_name, disks)
            # TODO:fix here, wait for multipath device ready
            time.sleep(2)

        # Disconnect paths to remove
        for key in paths_to_remove:
            if paths[key].connected:
                Path.disconnect(paths[key])
            del paths[key]
        LOG.debug("Virtman: now multipath is %s" % multipath_path)
        return multipath_path

    @staticmethod
    def create_multipath(multipath_name, disks):
        """
        :type multipath_name: str
        :type disks: list
        :rtype : str
        """
        LOG.debug("Virtman: create multipath according connection %s:" %
                  disks)
        multipath_path = dmsetup.multipath(multipath_name, disks)
        return multipath_path

    @staticmethod
    def reload_multipath(multipath_name, disks):
        """
        :type multipath_name: str
        :type disks: list
        """
        LOG.debug("Virtman: reload multipath according connection %s:" %
                  disks)
        dmsetup.reload_multipath(multipath_name, disks)

    @staticmethod
    def delete_multipath(multipath_name):
        LOG.debug("Virtman: delete multipath %s start!" %
                  multipath_name)
        dmsetup.remove_table(multipath_name)
        LOG.debug("Virtman: delete multipath %s completed  !" %
                  multipath_name)
        return True CONF = cfg.CONF
LOG = logging.getLogger(__name__)
MAX_COUNT = 120
WAIT_TIME = 5
class BaseImage(object):
class BlockDeviceBaseImage(BaseImage):
class Cache(object):
class Origin(object):
class Target(object):
class Volt(object):
class CreateCacheTask(task.Task):
class CreateOriginTask(task.Task):
class CreateTargetTask(task.Task):
class LoginMasterTask(task.Task):
class Qcow2BaseImage(BaseImage):
class FakeBaseImage(BaseImage):
    def __init__(self):
    def deploy_base_image(self):
    def destroy_base_image(self):
    def __init__(self, image_name, image_connections):
    def adjust_for_heartbeat(self, parents):
    def deploy_base_image(self):
    def check_local_image(self):
    def modify_parent_connection(self):
    def deploy(self):
    def destroy_base_image(self):
    def rebuild_multipath(self, parent_connections):
    def delete_multipath(self):
    def get_parent(self):
    def create_cache(base_image):
    def delete_cache(base_image):
    def create_origin(base_image):
    def delete_origin(base_image):
    def create_target(base_image):
    def delete_target(base_image):
    def login_master(base_image):
    def logout_master(base_image):
    def execute(self, base_image, **kwargs):
    def revert(self, base_image, result, **kwargs):
    def execute(self, base_image, **kwargs):
    def revert(self, base_image, result, **kwargs):
    def execute(self, base_image,  **kwargs):
    def revert(self, base_image, result, **kwargs):
    def execute(self, base_image, **kwargs):
    def revert(self, base_image, result, **kwargs):
    def __init__(self, image_name, image_connections):
    def deploy_base_image(self):
    def destroy_base_image(self): class Path(object):

    def __init__(self, connection):
        self.connection = connection
        self.connected = False
        self.device_info = None
        self.device_path = ''

    def __str__(self):
        return self.connection_to_str(self.connection)

    @staticmethod
    def connection_to_str(connection):
        """
        :type connection: dict
        """
        return iscsi_disk_format % (connection['target_portal'],
                                    connection['target_iqn'],
                                    connection['target_lun'])

    @staticmethod
    def connect(path):
        """
        :type path: Path
        """
        LOG.debug("Virtman: connect to path: %s", str(path))
        path.device_info = connector.connect_volume(path.connection)
        path.device_path = path.device_info['path']
        path.connected = True
        return path.device_path

    @staticmethod
    def disconnect(path):
        """
        :type path: Path
        """
        connector.disconnect_volume(path.connection, path.device_info)
        path.connected = False
        LOG.debug("Virtman: disconnect to path: %s", str(path)) class ISCSIExecutor(ISCSIConnector):
    def __init__(self):
def connect_volume(connection):
def disconnect_volume(connection, device_info): CONF = cfg.CONF
class FcgExecutor(FCG):
    def __init__(self):
def is_valid():
def create_group():
def add_disk(disk):
def rm_disk(disk): class DmExecutor(dmsetup.Dmsetup):
    def __init__(self):
def remove_table(name):
def reload_table(name, table):
def multipath(name, disks):
def reload_multipath(name, disks):
def origin(origin_name, origin_dev):
def snapshot(origin_path, snapshot_name, snapshot_dev): class TgtExecutor(TgtAdm):
    def __init__(self, root_helper='', volumes_dir='/etc/tgt/stack.d'):
def create_iscsi_target(iqn, path):
def remove_iscsi_target(vol_id, vol_name):
def exists(iqn):
def is_connected(target_id): CONF = cfg.CONF
def singleton(cls):
    def _singleton(*args, **kwargs):
    def __init__(self):
def login(session_name, peer_id, host, port, iqn, lun):
def logout(session_name, peer_id):
def get(session_name, host):
def heartbeat():
class VoltClient(client.Client): class TestException(VirtmanException):
    message = _("test exception")
import mock
import os
import string
import logging
from oslo.config import cfg
from tests import base
from testtools import ExpectedException
from virtman.path import Paths
from virtman import baseimage_new
from virtman.path import Path
from virtman.drivers import connector
from virtman.drivers import fcg
from virtman.drivers import dmsetup
from virtman.drivers import iscsi
from virtman.drivers import volt
from virtman.utils.exception import TestException
        self.device_info = None
        self.device_path = ''

    def __str__(self):
        return Path.connection_to_str(self.connection)

    def connect(self):
        self.device_info = fake_connect(self.connection)
        self.device_path = self.device_info['path']
        self.connected = True
        return self.device_path

    def disconnect(self):
        self.connected = False


class TestParent():
    def __init__(self, host, port, iqn, lun):
        self.host = host
        self.port = port
        self.iqn = iqn
        self.lun = lun
        self.peer_id = 'test_peer_id'

new_parent = TestParent('10.0.0.2', '3260',
                        'iqn.2010-10.org.openstack:volume-image', '1')

parent_connection = {
    'target_portal': '10.0.0.2:3260',
    'target_iqn': 'iqn.2010-10.org.openstack:volume-00000001',
    'target_lun': '1'
}

def exception_for_test(*args):
    raise TestException

class TestBaseImage(base.TestCase):
    def setUp(self):
        super(TestBaseImage, self).setUp()
        self.base_image = baseimage_new.BaseImage()

    def test_deploy_base_image(self):
        self.assertRaises(NotImplementedError,
                          self.base_image.deploy_base_image)

    def test_destroy_base_image(self):
        self.assertRaises(NotImplementedError,
                          self.base_image.destroy_base_image)




class TestBlockDeviceBaseImage(base.TestCase):
    def setUp(self):
        super(TestBlockDeviceBaseImage, self).setUp()
        self.cmds = []
        baseimage_new.LOG.logger.setLevel(logging.DEBUG)
        self.baseimage = \
            baseimage_new.BlockDeviceBaseImage('test_baseimage',
                                               test_image_connections)

    def fake_deploy(self):
        self.baseimage.target_id = '1'
        self.baseimage.has_target = True
        self.baseimage.origin_path = '/dev/mapper/test_origin'
        self.baseimage.origin_name = 'origin_test_baseimage'
        self.baseimage.cached_path = '/dev/mapper/test_cached'
        self.baseimage.multipath_path = '/dev/mapper/test_multipath'
        self.baseimage.multipath_name = 'multipath_test_baseimage'
        self.baseimage.paths['test_path'] = FakePath('test_path')
        self.baseimage.peer_id = 'test_peer_id'
        self.baseimage.is_login = True
        # self.paths = {'test_path': }

    def test_check_local_image(self):
        CONF.host_ip = '10.0.0.1'
        self.baseimage.check_local_image()
        self.assertEqual(True, self.baseimage.is_local_has_image)
        CONF.host_ip = '10.0.0.2'
        self.baseimage.check_local_image()
        self.assertEqual(False, self.baseimage.is_local_has_image)

    def test_adjust_for_heartbeat(self):
        self.mock_object(Paths, 'rebuild_multipath',
                         mock.Mock(return_value='/dev/mapper/test_multipath'))
        self.baseimage.adjust_for_heartbeat([parent_connection])
        self.assertEqual('/dev/mapper/test_multipath',
                         self.baseimage.multipath_path)

    def test_get_parent(self):
        CONF.host_ip = '10.0.0.2'
        self.mock_object(volt, 'get',
                         mock.Mock(return_value=('test_peer_id', [new_parent])))
        result = self.baseimage.get_parent()
        self.assertEqual([new_parent], result)

    def test_modify_parent_connection(self):
        CONF.host_ip = '10.0.0.2'
        self.mock_object(volt, 'get',
                         mock.Mock(return_value=('test_peer_id', [new_parent])))
        self.baseimage.is_local_has_image = True
        expected_result = [{'target_lun': '1',
                            'target_iqn': 'iqn.2010-10.org.openstack:'
                                          'volume-image',
                            'target_portal': '10.0.0.1:3260'}]
        result = self.baseimage.modify_parent_connection()
        self.assertEqual(expected_result, result)
        expected_result = [{'target_lun': '1',
                            'target_iqn': 'iqn.2010-10.org.openstack:'
                                          'volume-image',
                            'target_portal': '10.0.0.2:3260'}]
        self.baseimage.is_local_has_image = False
        result = self.baseimage.modify_parent_connection()
        self.assertEqual(expected_result, result)

    def test_deploy_base_image(self):
        CONF.master_ip = '10.0.0.1'
        CONF.host_ip = '10.0.0.2'
        self.mock_object(volt, 'get',
                         mock.Mock(return_value=('test_peer_id', [new_parent])))

        self.mock_object(connector, 'connect_volume',