Пример #1
0
    def _create_client(self, **kwargs):
        """Instantiate a client for NetApp server.

        This method creates NetApp server client for api communication.
        """
        host_filer = kwargs['hostname']
        LOG.debug(_('Using NetApp filer: %s') % host_filer)
        self.client = NaServer(host=host_filer,
                               server_type=NaServer.SERVER_TYPE_FILER,
                               transport_type=kwargs['transport_type'],
                               style=NaServer.STYLE_LOGIN_PASSWORD,
                               username=kwargs['login'],
                               password=kwargs['password'])
Пример #2
0
 def _get_client(self):
     """Creates NetApp api client."""
     client = NaServer(
         host=self.configuration.netapp_server_hostname,
         server_type=NaServer.SERVER_TYPE_FILER,
         transport_type=self.configuration.netapp_transport_type,
         style=NaServer.STYLE_LOGIN_PASSWORD,
         username=self.configuration.netapp_login,
         password=self.configuration.netapp_password)
     return client
Пример #3
0
    def _create_client(self, **kwargs):
        """Instantiate a client for NetApp server.

        This method creates NetApp server client for api communication.
        """
        host_filer = kwargs['hostname']
        LOG.debug(_('Using NetApp filer: %s') % host_filer)
        self.client = NaServer(host=host_filer,
                               server_type=NaServer.SERVER_TYPE_FILER,
                               transport_type=kwargs['transport_type'],
                               style=NaServer.STYLE_LOGIN_PASSWORD,
                               username=kwargs['login'],
                               password=kwargs['password'])
Пример #4
0
class NetAppDirectISCSIDriver(driver.ISCSIDriver):
    """NetApp Direct iSCSI volume driver."""

    VERSION = "1.0.0"

    IGROUP_PREFIX = "openstack-"
    required_flags = [
        "netapp_transport_type",
        "netapp_login",
        "netapp_password",
        "netapp_server_hostname",
        "netapp_server_port",
    ]

    def __init__(self, *args, **kwargs):
        super(NetAppDirectISCSIDriver, self).__init__(*args, **kwargs)
        validate_instantiation(**kwargs)
        self.configuration.append_config_values(netapp_connection_opts)
        self.configuration.append_config_values(netapp_basicauth_opts)
        self.configuration.append_config_values(netapp_transport_opts)
        self.configuration.append_config_values(netapp_provisioning_opts)
        self.lun_table = {}

    def _create_client(self, **kwargs):
        """Instantiate a client for NetApp server.

        This method creates NetApp server client for api communication.
        """

        host_filer = kwargs["hostname"]
        LOG.debug(_("Using NetApp filer: %s") % host_filer)
        self.client = NaServer(
            host=host_filer,
            server_type=NaServer.SERVER_TYPE_FILER,
            transport_type=kwargs["transport_type"],
            style=NaServer.STYLE_LOGIN_PASSWORD,
            username=kwargs["login"],
            password=kwargs["password"],
        )

    def _do_custom_setup(self):
        """Does custom setup depending on the type of filer."""
        raise NotImplementedError()

    def _check_flags(self):
        """Ensure that the flags we care about are set."""
        required_flags = self.required_flags
        for flag in required_flags:
            if not getattr(self.configuration, flag, None):
                msg = _("%s is not set") % flag
                raise exception.InvalidInput(data=msg)

    def do_setup(self, context):
        """Setup the NetApp Volume driver.

        Called one time by the manager after the driver is loaded.
        Validate the flags we care about and setup NetApp
        client.
        """

        self._check_flags()
        self._create_client(
            transport_type=self.configuration.netapp_transport_type,
            login=self.configuration.netapp_login,
            password=self.configuration.netapp_password,
            hostname=self.configuration.netapp_server_hostname,
            port=self.configuration.netapp_server_port,
        )
        self._do_custom_setup()

    def check_for_setup_error(self):
        """Check that the driver is working and can communicate.

        Discovers the LUNs on the NetApp server.
        """

        self.lun_table = {}
        self._get_lun_list()
        LOG.debug(_("Success getting LUN list from server"))

    def create_volume(self, volume):
        """Driver entry point for creating a new volume."""
        default_size = "104857600"  # 100 MB
        gigabytes = 1073741824L  # 2^30
        name = volume["name"]
        if int(volume["size"]) == 0:
            size = default_size
        else:
            size = str(int(volume["size"]) * gigabytes)
        metadata = {}
        metadata["OsType"] = "linux"
        metadata["SpaceReserved"] = "true"
        extra_specs = get_volume_extra_specs(volume)
        self._create_lun_on_eligible_vol(name, size, metadata, extra_specs)
        LOG.debug(_("Created LUN with name %s") % name)
        handle = self._create_lun_handle(metadata)
        self._add_lun_to_table(NetAppLun(handle, name, size, metadata))

    def delete_volume(self, volume):
        """Driver entry point for destroying existing volumes."""
        name = volume["name"]
        metadata = self._get_lun_attr(name, "metadata")
        if not metadata:
            msg = _("No entry in LUN table for volume/snapshot %(name)s.")
            msg_fmt = {"name": name}
            LOG.warn(msg % msg_fmt)
            return
        lun_destroy = NaElement.create_node_with_children("lun-destroy", **{"path": metadata["Path"], "force": "true"})
        self.client.invoke_successfully(lun_destroy, True)
        LOG.debug(_("Destroyed LUN %s") % name)
        self.lun_table.pop(name)

    def ensure_export(self, context, volume):
        """Driver entry point to get the export info for an existing volume."""
        handle = self._get_lun_attr(volume["name"], "handle")
        return {"provider_location": handle}

    def create_export(self, context, volume):
        """Driver entry point to get the export info for a new volume."""
        handle = self._get_lun_attr(volume["name"], "handle")
        return {"provider_location": handle}

    def remove_export(self, context, volume):
        """Driver exntry point to remove an export for a volume.

        Since exporting is idempotent in this driver, we have nothing
        to do for unexporting.
        """

        pass

    def initialize_connection(self, volume, connector):
        """Driver entry point to attach a volume to an instance.

        Do the LUN masking on the storage system so the initiator can access
        the LUN on the target. Also return the iSCSI properties so the
        initiator can find the LUN. This implementation does not call
        _get_iscsi_properties() to get the properties because cannot store the
        LUN number in the database. We only find out what the LUN number will
        be during this method call so we construct the properties dictionary
        ourselves.
        """

        initiator_name = connector["initiator"]
        name = volume["name"]
        lun_id = self._map_lun(name, initiator_name, "iscsi", None)
        msg = _("Mapped LUN %(name)s to the initiator %(initiator_name)s")
        msg_fmt = {"name": name, "initiator_name": initiator_name}
        LOG.debug(msg % msg_fmt)
        iqn = self._get_iscsi_service_details()
        target_details_list = self._get_target_details()
        msg = _("Succesfully fetched target details for LUN %(name)s and " "initiator %(initiator_name)s")
        msg_fmt = {"name": name, "initiator_name": initiator_name}
        LOG.debug(msg % msg_fmt)

        if not target_details_list:
            msg = _("Failed to get LUN target details for the LUN %s")
            raise exception.VolumeBackendAPIException(data=msg % name)
        target_details = None
        for tgt_detail in target_details_list:
            if tgt_detail.get("interface-enabled", "true") == "true":
                target_details = tgt_detail
                break
        if not target_details:
            target_details = target_details_list[0]

        if not target_details["address"] and target_details["port"]:
            msg = _("Failed to get target portal for the LUN %s")
            raise exception.VolumeBackendAPIException(data=msg % name)
        if not iqn:
            msg = _("Failed to get target IQN for the LUN %s")
            raise exception.VolumeBackendAPIException(data=msg % name)

        properties = {}
        properties["target_discovered"] = False
        (address, port) = (target_details["address"], target_details["port"])
        properties["target_portal"] = "%s:%s" % (address, port)
        properties["target_iqn"] = iqn
        properties["target_lun"] = lun_id
        properties["volume_id"] = volume["id"]

        auth = volume["provider_auth"]
        if auth:
            (auth_method, auth_username, auth_secret) = auth.split()
            properties["auth_method"] = auth_method
            properties["auth_username"] = auth_username
            properties["auth_password"] = auth_secret

        return {"driver_volume_type": "iscsi", "data": properties}

    def create_snapshot(self, snapshot):
        """Driver entry point for creating a snapshot.

        This driver implements snapshots by using efficient single-file
        (LUN) cloning.
        """

        vol_name = snapshot["volume_name"]
        snapshot_name = snapshot["name"]
        lun = self.lun_table[vol_name]
        self._clone_lun(lun.name, snapshot_name, "false")

    def delete_snapshot(self, snapshot):
        """Driver entry point for deleting a snapshot."""
        self.delete_volume(snapshot)
        LOG.debug(_("Snapshot %s deletion successful") % snapshot["name"])

    def create_volume_from_snapshot(self, volume, snapshot):
        """Driver entry point for creating a new volume from a snapshot.

        Many would call this "cloning" and in fact we use cloning to implement
        this feature.
        """

        vol_size = volume["size"]
        snap_size = snapshot["volume_size"]
        if vol_size != snap_size:
            msg = _("Cannot create volume of size %(vol_size)s from " "snapshot of size %(snap_size)s")
            msg_fmt = {"vol_size": vol_size, "snap_size": snap_size}
            raise exception.VolumeBackendAPIException(data=msg % msg_fmt)
        snapshot_name = snapshot["name"]
        new_name = volume["name"]
        self._clone_lun(snapshot_name, new_name, "true")

    def terminate_connection(self, volume, connector, **kwargs):
        """Driver entry point to unattach a volume from an instance.

        Unmask the LUN on the storage system so the given intiator can no
        longer access it.
        """

        initiator_name = connector["initiator"]
        name = volume["name"]
        metadata = self._get_lun_attr(name, "metadata")
        path = metadata["Path"]
        self._unmap_lun(path, initiator_name)
        msg = _("Unmapped LUN %(name)s from the initiator " "%(initiator_name)s")
        msg_fmt = {"name": name, "initiator_name": initiator_name}
        LOG.debug(msg % msg_fmt)

    def _get_ontapi_version(self):
        """Gets the supported ontapi version."""
        ontapi_version = NaElement("system-get-ontapi-version")
        res = self.client.invoke_successfully(ontapi_version, False)
        major = res.get_child_content("major-version")
        minor = res.get_child_content("minor-version")
        return (major, minor)

    def _create_lun_on_eligible_vol(self, name, size, metadata, extra_specs=None):
        """Creates an actual lun on filer."""
        raise NotImplementedError()

    def _get_iscsi_service_details(self):
        """Returns iscsi iqn."""
        raise NotImplementedError()

    def _get_target_details(self):
        """Gets the target portal details."""
        raise NotImplementedError()

    def _create_lun_handle(self, metadata):
        """Returns lun handle based on filer type."""
        raise NotImplementedError()

    def _get_lun_list(self):
        """Gets the list of luns on filer."""
        raise NotImplementedError()

    def _extract_and_populate_luns(self, api_luns):
        """Extracts the luns from api.

        Populates in the lun table.
        """

        for lun in api_luns:
            meta_dict = self._create_lun_meta(lun)
            path = lun.get_child_content("path")
            (rest, splitter, name) = path.rpartition("/")
            handle = self._create_lun_handle(meta_dict)
            size = lun.get_child_content("size")
            discovered_lun = NetAppLun(handle, name, size, meta_dict)
            self._add_lun_to_table(discovered_lun)

    def _is_naelement(self, elem):
        """Checks if element is NetApp element."""
        if not isinstance(elem, NaElement):
            raise ValueError("Expects NaElement")

    def _map_lun(self, name, initiator, initiator_type="iscsi", lun_id=None):
        """Maps lun to the initiator and returns lun id assigned."""
        metadata = self._get_lun_attr(name, "metadata")
        os = metadata["OsType"]
        path = metadata["Path"]
        if self._check_allowed_os(os):
            os = os
        else:
            os = "default"
        igroup_name = self._get_or_create_igroup(initiator, initiator_type, os)
        lun_map = NaElement.create_node_with_children("lun-map", **{"path": path, "initiator-group": igroup_name})
        if lun_id:
            lun_map.add_new_child("lun-id", lun_id)
        try:
            result = self.client.invoke_successfully(lun_map, True)
            return result.get_child_content("lun-id-assigned")
        except NaApiError as e:
            code = e.code
            message = e.message
            msg = _("Error mapping lun. Code :%(code)s, Message:%(message)s")
            msg_fmt = {"code": code, "message": message}
            exc_info = sys.exc_info()
            LOG.warn(msg % msg_fmt)
            (igroup, lun_id) = self._find_mapped_lun_igroup(path, initiator)
            if lun_id is not None:
                return lun_id
            else:
                raise exc_info[0], exc_info[1], exc_info[2]

    def _unmap_lun(self, path, initiator):
        """Unmaps a lun from given initiator."""
        (igroup_name, lun_id) = self._find_mapped_lun_igroup(path, initiator)
        lun_unmap = NaElement.create_node_with_children("lun-unmap", **{"path": path, "initiator-group": igroup_name})
        try:
            self.client.invoke_successfully(lun_unmap, True)
        except NaApiError as e:
            msg = _("Error unmapping lun. Code :%(code)s," " Message:%(message)s")
            msg_fmt = {"code": e.code, "message": e.message}
            exc_info = sys.exc_info()
            LOG.warn(msg % msg_fmt)
            # if the lun is already unmapped
            if e.code == "13115" or e.code == "9016":
                pass
            else:
                raise exc_info[0], exc_info[1], exc_info[2]

    def _find_mapped_lun_igroup(self, path, initiator, os=None):
        """Find the igroup for mapped lun with initiator."""
        raise NotImplementedError()

    def _get_or_create_igroup(self, initiator, initiator_type="iscsi", os="default"):
        """Checks for an igroup for an initiator.

        Creates igroup if not found.
        """

        igroups = self._get_igroup_by_initiator(initiator=initiator)
        igroup_name = None
        for igroup in igroups:
            if igroup["initiator-group-os-type"] == os:
                if igroup["initiator-group-type"] == initiator_type or igroup["initiator-group-type"] == "mixed":
                    if igroup["initiator-group-name"].startswith(self.IGROUP_PREFIX):
                        igroup_name = igroup["initiator-group-name"]
                        break
        if not igroup_name:
            igroup_name = self.IGROUP_PREFIX + str(uuid.uuid4())
            self._create_igroup(igroup_name, initiator_type, os)
            self._add_igroup_initiator(igroup_name, initiator)
        return igroup_name

    def _get_igroup_by_initiator(self, initiator):
        """Get igroups by initiator."""
        raise NotImplementedError()

    def _check_allowed_os(self, os):
        """Checks if the os type supplied is NetApp supported."""
        if os in ["linux", "aix", "hpux", "windows", "solaris", "netware", "vmware", "openvms", "xen", "hyper_v"]:
            return True
        else:
            return False

    def _create_igroup(self, igroup, igroup_type="iscsi", os_type="default"):
        """Creates igoup with specified args."""
        igroup_create = NaElement.create_node_with_children(
            "igroup-create", **{"initiator-group-name": igroup, "initiator-group-type": igroup_type, "os-type": os_type}
        )
        self.client.invoke_successfully(igroup_create, True)

    def _add_igroup_initiator(self, igroup, initiator):
        """Adds initiators to the specified igroup."""
        igroup_add = NaElement.create_node_with_children(
            "igroup-add", **{"initiator-group-name": igroup, "initiator": initiator}
        )
        self.client.invoke_successfully(igroup_add, True)

    def _get_qos_type(self, volume):
        """Get the storage service type for a volume."""
        type_id = volume["volume_type_id"]
        if not type_id:
            return None
        volume_type = volume_types.get_volume_type(None, type_id)
        if not volume_type:
            return None
        return volume_type["name"]

    def _add_lun_to_table(self, lun):
        """Adds LUN to cache table."""
        if not isinstance(lun, NetAppLun):
            msg = _("Object is not a NetApp LUN.")
            raise exception.VolumeBackendAPIException(data=msg)
        self.lun_table[lun.name] = lun

    def _clone_lun(self, name, new_name, space_reserved):
        """Clone LUN with the given name to the new name."""
        raise NotImplementedError()

    def _get_lun_by_args(self, **args):
        """Retrives lun with specified args."""
        raise NotImplementedError()

    def _get_lun_attr(self, name, attr):
        """Get the attributes for a LUN from our cache table."""
        if not name in self.lun_table or not hasattr(self.lun_table[name], attr):
            LOG.warn(_("Could not find attribute for LUN named %s") % name)
            return None
        return getattr(self.lun_table[name], attr)

    def _create_lun_meta(self, lun):
        raise NotImplementedError()

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        vol_size = volume["size"]
        src_vol = self.lun_table[src_vref["name"]]
        src_vol_size = src_vref["size"]
        if vol_size != src_vol_size:
            msg = _("Cannot clone volume of size %(vol_size)s from " "src volume of size %(src_vol_size)s")
            msg_fmt = {"vol_size": vol_size, "src_vol_size": src_vol_size}
            raise exception.VolumeBackendAPIException(data=msg % msg_fmt)
        new_name = volume["name"]
        self._clone_lun(src_vol.name, new_name, "true")

    def get_volume_stats(self, refresh=False):
        """Get volume stats.

        If 'refresh' is True, run update the stats first.
        """

        if refresh:
            self._update_volume_stats()

        return self._stats

    def _update_volume_stats(self):
        """Retrieve stats info from volume group."""
        raise NotImplementedError()
Пример #5
0
class NetAppDirectISCSIDriver(driver.ISCSIDriver):
    """NetApp Direct iSCSI volume driver."""

    IGROUP_PREFIX = 'openstack-'
    required_flags = ['netapp_transport_type', 'netapp_login',
                      'netapp_password', 'netapp_server_hostname',
                      'netapp_server_port']

    def __init__(self, *args, **kwargs):
        super(NetAppDirectISCSIDriver, self).__init__(*args, **kwargs)
        validate_instantiation(**kwargs)
        self.configuration.append_config_values(netapp_connection_opts)
        self.configuration.append_config_values(netapp_basicauth_opts)
        self.configuration.append_config_values(netapp_transport_opts)
        self.configuration.append_config_values(netapp_provisioning_opts)
        self.lun_table = {}

    def _create_client(self, **kwargs):
        """Instantiate a client for NetApp server.

        This method creates NetApp server client for api communication.
        """
        host_filer = kwargs['hostname']
        LOG.debug(_('Using NetApp filer: %s') % host_filer)
        self.client = NaServer(host=host_filer,
                               server_type=NaServer.SERVER_TYPE_FILER,
                               transport_type=kwargs['transport_type'],
                               style=NaServer.STYLE_LOGIN_PASSWORD,
                               username=kwargs['login'],
                               password=kwargs['password'])

    def _do_custom_setup(self):
        """Does custom setup depending on the type of filer."""
        raise NotImplementedError()

    def _check_flags(self):
        """Ensure that the flags we care about are set."""
        required_flags = self.required_flags
        for flag in required_flags:
            if not getattr(self.configuration, flag, None):
                msg = _('%s is not set') % flag
                raise exception.InvalidInput(data=msg)

    def do_setup(self, context):
        """Setup the NetApp Volume driver.

        Called one time by the manager after the driver is loaded.
        Validate the flags we care about and setup NetApp
        client.
        """
        self._check_flags()
        self._create_client(
            transport_type=self.configuration.netapp_transport_type,
            login=self.configuration.netapp_login,
            password=self.configuration.netapp_password,
            hostname=self.configuration.netapp_server_hostname,
            port=self.configuration.netapp_server_port)
        self._do_custom_setup()

    def check_for_setup_error(self):
        """Check that the driver is working and can communicate.

        Discovers the LUNs on the NetApp server.
        """
        self.lun_table = {}
        self._get_lun_list()
        LOG.debug(_("Success getting LUN list from server"))

    def create_volume(self, volume):
        """Driver entry point for creating a new volume."""
        default_size = '104857600'  # 100 MB
        gigabytes = 1073741824L  # 2^30
        name = volume['name']
        if int(volume['size']) == 0:
            size = default_size
        else:
            size = str(int(volume['size']) * gigabytes)
        metadata = {}
        metadata['OsType'] = 'linux'
        metadata['SpaceReserved'] = 'true'
        self._create_lun_on_eligible_vol(name, size, metadata)
        LOG.debug(_("Created LUN with name %s") % name)
        handle = self._create_lun_handle(metadata)
        self._add_lun_to_table(NetAppLun(handle, name, size, metadata))

    def delete_volume(self, volume):
        """Driver entry point for destroying existing volumes."""
        name = volume['name']
        metadata = self._get_lun_attr(name, 'metadata')
        if not metadata:
            msg = _("No entry in LUN table for volume/snapshot %(name)s.")
            msg_fmt = {'name': name}
            LOG.warn(msg % msg_fmt)
            return
        lun_destroy = NaElement.create_node_with_children(
            'lun-destroy',
            **{'path': metadata['Path'],
            'force': 'true'})
        self.client.invoke_successfully(lun_destroy, True)
        LOG.debug(_("Destroyed LUN %s") % name)
        self.lun_table.pop(name)

    def ensure_export(self, context, volume):
        """Driver entry point to get the export info for an existing volume."""
        handle = self._get_lun_attr(volume['name'], 'handle')
        return {'provider_location': handle}

    def create_export(self, context, volume):
        """Driver entry point to get the export info for a new volume."""
        handle = self._get_lun_attr(volume['name'], 'handle')
        return {'provider_location': handle}

    def remove_export(self, context, volume):
        """Driver exntry point to remove an export for a volume.

        Since exporting is idempotent in this driver, we have nothing
        to do for unexporting.
        """
        pass

    def initialize_connection(self, volume, connector):
        """Driver entry point to attach a volume to an instance.

        Do the LUN masking on the storage system so the initiator can access
        the LUN on the target. Also return the iSCSI properties so the
        initiator can find the LUN. This implementation does not call
        _get_iscsi_properties() to get the properties because cannot store the
        LUN number in the database. We only find out what the LUN number will
        be during this method call so we construct the properties dictionary
        ourselves.
        """
        initiator_name = connector['initiator']
        name = volume['name']
        lun_id = self._map_lun(name, initiator_name, 'iscsi', None)
        msg = _("Mapped LUN %(name)s to the initiator %(initiator_name)s")
        msg_fmt = {'name': name, 'initiator_name': initiator_name}
        LOG.debug(msg % msg_fmt)
        iqn = self._get_iscsi_service_details()
        target_details_list = self._get_target_details()
        msg = _("Succesfully fetched target details for LUN %(name)s and "
                "initiator %(initiator_name)s")
        msg_fmt = {'name': name, 'initiator_name': initiator_name}
        LOG.debug(msg % msg_fmt)

        if not target_details_list:
            msg = _('Failed to get LUN target details for the LUN %s')
            raise exception.VolumeBackendAPIException(data=msg % name)
        target_details = None
        for tgt_detail in target_details_list:
            if tgt_detail.get('interface-enabled', 'true') == 'true':
                target_details = tgt_detail
                break
        if not target_details:
            target_details = target_details_list[0]

        if not target_details['address'] and target_details['port']:
            msg = _('Failed to get target portal for the LUN %s')
            raise exception.VolumeBackendAPIException(data=msg % name)
        if not iqn:
            msg = _('Failed to get target IQN for the LUN %s')
            raise exception.VolumeBackendAPIException(data=msg % name)

        properties = {}
        properties['target_discovered'] = False
        (address, port) = (target_details['address'], target_details['port'])
        properties['target_portal'] = '%s:%s' % (address, port)
        properties['target_iqn'] = iqn
        properties['target_lun'] = lun_id
        properties['volume_id'] = volume['id']

        auth = volume['provider_auth']
        if auth:
            (auth_method, auth_username, auth_secret) = auth.split()
            properties['auth_method'] = auth_method
            properties['auth_username'] = auth_username
            properties['auth_password'] = auth_secret

        return {
            'driver_volume_type': 'iscsi',
            'data': properties,
        }

    def create_snapshot(self, snapshot):
        """Driver entry point for creating a snapshot.

        This driver implements snapshots by using efficient single-file
        (LUN) cloning.
        """
        vol_name = snapshot['volume_name']
        snapshot_name = snapshot['name']
        lun = self.lun_table[vol_name]
        self._clone_lun(lun.name, snapshot_name, 'false')

    def delete_snapshot(self, snapshot):
        """Driver entry point for deleting a snapshot."""
        self.delete_volume(snapshot)
        LOG.debug(_("Snapshot %s deletion successful") % snapshot['name'])

    def create_volume_from_snapshot(self, volume, snapshot):
        """Driver entry point for creating a new volume from a snapshot.

        Many would call this "cloning" and in fact we use cloning to implement
        this feature.
        """
        vol_size = volume['size']
        snap_size = snapshot['volume_size']
        if vol_size != snap_size:
            msg = _('Cannot create volume of size %(vol_size)s from '
                    'snapshot of size %(snap_size)s')
            msg_fmt = {'vol_size': vol_size, 'snap_size': snap_size}
            raise exception.VolumeBackendAPIException(data=msg % msg_fmt)
        snapshot_name = snapshot['name']
        new_name = volume['name']
        self._clone_lun(snapshot_name, new_name, 'true')

    def terminate_connection(self, volume, connector, **kwargs):
        """Driver entry point to unattach a volume from an instance.

        Unmask the LUN on the storage system so the given intiator can no
        longer access it.
        """
        initiator_name = connector['initiator']
        name = volume['name']
        metadata = self._get_lun_attr(name, 'metadata')
        path = metadata['Path']
        self._unmap_lun(path, initiator_name)
        msg = _("Unmapped LUN %(name)s from the initiator "
                "%(initiator_name)s")
        msg_fmt = {'name': name, 'initiator_name': initiator_name}
        LOG.debug(msg % msg_fmt)

    def _get_ontapi_version(self):
        """Gets the supported ontapi version."""
        ontapi_version = NaElement('system-get-ontapi-version')
        res = self.client.invoke_successfully(ontapi_version, False)
        major = res.get_child_content('major-version')
        minor = res.get_child_content('minor-version')
        return (major, minor)

    def _create_lun_on_eligible_vol(self, name, size, metadata):
        """Creates an actual lun on filer."""
        req_size = float(size) *\
            float(self.configuration.netapp_size_multiplier)
        volume = self._get_avl_volume_by_size(req_size)
        if not volume:
            msg = _('Failed to get vol with required size for volume: %s')
            raise exception.VolumeBackendAPIException(data=msg % name)
        path = '/vol/%s/%s' % (volume['name'], name)
        lun_create = NaElement.create_node_with_children(
            'lun-create-by-size',
            **{'path': path, 'size': size,
            'ostype': metadata['OsType'],
            'space-reservation-enabled':
            metadata['SpaceReserved']})
        self.client.invoke_successfully(lun_create, True)
        metadata['Path'] = '/vol/%s/%s' % (volume['name'], name)
        metadata['Volume'] = volume['name']
        metadata['Qtree'] = None

    def _get_avl_volume_by_size(self, size):
        """Get the available volume by size."""
        raise NotImplementedError()

    def _get_iscsi_service_details(self):
        """Returns iscsi iqn."""
        raise NotImplementedError()

    def _get_target_details(self):
        """Gets the target portal details."""
        raise NotImplementedError()

    def _create_lun_handle(self, metadata):
        """Returns lun handle based on filer type."""
        raise NotImplementedError()

    def _get_lun_list(self):
        """Gets the list of luns on filer."""
        raise NotImplementedError()

    def _extract_and_populate_luns(self, api_luns):
        """Extracts the luns from api.

        Populates in the lun table.
        """
        for lun in api_luns:
            meta_dict = self._create_lun_meta(lun)
            path = lun.get_child_content('path')
            (rest, splitter, name) = path.rpartition('/')
            handle = self._create_lun_handle(meta_dict)
            size = lun.get_child_content('size')
            discovered_lun = NetAppLun(handle, name,
                                       size, meta_dict)
            self._add_lun_to_table(discovered_lun)

    def _is_naelement(self, elem):
        """Checks if element is NetApp element."""
        if not isinstance(elem, NaElement):
            raise ValueError('Expects NaElement')

    def _map_lun(self, name, initiator, initiator_type='iscsi', lun_id=None):
        """Maps lun to the initiator and returns lun id assigned."""
        metadata = self._get_lun_attr(name, 'metadata')
        os = metadata['OsType']
        path = metadata['Path']
        if self._check_allowed_os(os):
            os = os
        else:
            os = 'default'
        igroup_name = self._get_or_create_igroup(initiator,
                                                 initiator_type, os)
        lun_map = NaElement.create_node_with_children(
            'lun-map', **{'path': path,
            'initiator-group': igroup_name})
        if lun_id:
            lun_map.add_new_child('lun-id', lun_id)
        try:
            result = self.client.invoke_successfully(lun_map, True)
            return result.get_child_content('lun-id-assigned')
        except NaApiError as e:
            code = e.code
            message = e.message
            msg = _('Error mapping lun. Code :%(code)s, Message:%(message)s')
            msg_fmt = {'code': code, 'message': message}
            exc_info = sys.exc_info()
            LOG.warn(msg % msg_fmt)
            (igroup, lun_id) = self._find_mapped_lun_igroup(path, initiator)
            if lun_id is not None:
                return lun_id
            else:
                raise exc_info[0], exc_info[1], exc_info[2]

    def _unmap_lun(self, path, initiator):
        """Unmaps a lun from given initiator."""
        (igroup_name, lun_id) = self._find_mapped_lun_igroup(path, initiator)
        lun_unmap = NaElement.create_node_with_children(
            'lun-unmap',
            **{'path': path,
            'initiator-group': igroup_name})
        try:
            self.client.invoke_successfully(lun_unmap, True)
        except NaApiError as e:
            msg = _("Error unmapping lun. Code :%(code)s,"
                    " Message:%(message)s")
            msg_fmt = {'code': e.code, 'message': e.message}
            exc_info = sys.exc_info()
            LOG.warn(msg % msg_fmt)
            # if the lun is already unmapped
            if e.code == '13115' or e.code == '9016':
                pass
            else:
                raise exc_info[0], exc_info[1], exc_info[2]

    def _find_mapped_lun_igroup(self, path, initiator, os=None):
        """Find the igroup for mapped lun with initiator."""
        raise NotImplementedError()

    def _get_or_create_igroup(self, initiator, initiator_type='iscsi',
                              os='default'):
        """Checks for an igroup for an initiator.

        Creates igroup if not found.
        """
        igroups = self._get_igroup_by_initiator(initiator=initiator)
        igroup_name = None
        for igroup in igroups:
            if igroup['initiator-group-os-type'] == os:
                if igroup['initiator-group-type'] == initiator_type or \
                        igroup['initiator-group-type'] == 'mixed':
                    if igroup['initiator-group-name'].startswith(
                            self.IGROUP_PREFIX):
                        igroup_name = igroup['initiator-group-name']
                        break
        if not igroup_name:
            igroup_name = self.IGROUP_PREFIX + str(uuid.uuid4())
            self._create_igroup(igroup_name, initiator_type, os)
            self._add_igroup_initiator(igroup_name, initiator)
        return igroup_name

    def _get_igroup_by_initiator(self, initiator):
        """Get igroups by initiator."""
        raise NotImplementedError()

    def _check_allowed_os(self, os):
        """Checks if the os type supplied is NetApp supported."""
        if os in ['linux', 'aix', 'hpux', 'windows', 'solaris',
                  'netware', 'vmware', 'openvms', 'xen', 'hyper_v']:
            return True
        else:
            return False

    def _create_igroup(self, igroup, igroup_type='iscsi', os_type='default'):
        """Creates igoup with specified args."""
        igroup_create = NaElement.create_node_with_children(
            'igroup-create',
            **{'initiator-group-name': igroup,
            'initiator-group-type': igroup_type,
            'os-type': os_type})
        self.client.invoke_successfully(igroup_create, True)

    def _add_igroup_initiator(self, igroup, initiator):
        """Adds initiators to the specified igroup."""
        igroup_add = NaElement.create_node_with_children(
            'igroup-add',
            **{'initiator-group-name': igroup,
            'initiator': initiator})
        self.client.invoke_successfully(igroup_add, True)

    def _get_qos_type(self, volume):
        """Get the storage service type for a volume."""
        type_id = volume['volume_type_id']
        if not type_id:
            return None
        volume_type = volume_types.get_volume_type(None, type_id)
        if not volume_type:
            return None
        return volume_type['name']

    def _add_lun_to_table(self, lun):
        """Adds LUN to cache table."""
        if not isinstance(lun, NetAppLun):
            msg = _("Object is not a NetApp LUN.")
            raise exception.VolumeBackendAPIException(data=msg)
        self.lun_table[lun.name] = lun

    def _clone_lun(self, name, new_name, space_reserved):
        """Clone LUN with the given name to the new name."""
        raise NotImplementedError()

    def _get_lun_by_args(self, **args):
        """Retrives lun with specified args."""
        raise NotImplementedError()

    def _get_lun_attr(self, name, attr):
        """Get the attributes for a LUN from our cache table."""
        if not name in self.lun_table or not hasattr(
                self.lun_table[name], attr):
            LOG.warn(_("Could not find attribute for LUN named %s") % name)
            return None
        return getattr(self.lun_table[name], attr)

    def _create_lun_meta(self, lun):
        raise NotImplementedError()

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        vol_size = volume['size']
        src_vol = self.lun_table[src_vref['name']]
        src_vol_size = src_vref['size']
        if vol_size != src_vol_size:
            msg = _('Cannot clone volume of size %(vol_size)s from '
                    'src volume of size %(src_vol_size)s')
            msg_fmt = {'vol_size': vol_size, 'src_vol_size': src_vol_size}
            raise exception.VolumeBackendAPIException(data=msg % msg_fmt)
        new_name = volume['name']
        self._clone_lun(src_vol.name, new_name, 'true')

    def get_volume_stats(self, refresh=False):
        """Get volume stats.

        If 'refresh' is True, run update the stats first.
        """
        if refresh:
            self._update_volume_stats()

        return self._stats

    def _update_volume_stats(self):
        """Retrieve stats info from volume group."""
        raise NotImplementedError()