예제 #1
0
def get_infinisdk_from_arguments(arguments):
    from infinisdk import InfiniBox
    from infinidat_openstack.versioncheck import raise_if_unsupported, get_system_version
    system = InfiniBox(arguments.address, use_ssl=True, auth=(arguments.username, arguments.password))
    system.login()
    raise_if_unsupported(get_system_version(arguments.address, arguments.username, arguments.password, system))
    return system
 def infinisdk_side_effect(address, use_ssl, auth=("admin", "123456")):
     if address == self.infinisdk.get_name():
         instance = InfiniBox(self.simulator, auth=auth)
     else:
         instance = InfiniBox(address, auth=auth)
     instance.login()
     return instance
예제 #3
0
def ibox_login(ibox):
    try:
        pass_file = "." + ibox + ".sec"
        system = InfiniBox(ibox, pass_decode(pass_file))
        system.login()
        return system
    except Exception as E:
        print "failed due to {}".format(E)
예제 #4
0
def ibox_login(ibox):
    try:
        pass_file = "." + ibox + ".sec"
        print "Opening {}".format(pass_file)
        auth = pass_decode(pass_file)
        system = InfiniBox(ibox, auth)
        system.login()
        return system, auth
    except Exception as E:
        print "failed due to {}".format(E)
def get_system(module):
    """Return System Object or Fail"""
    box = module.params['system']
    user = module.params['user']
    password = module.params['password']

    if user and password:
        system = InfiniBox(box, auth=(user, password))
    elif environ.get('INFINIBOX_USER') and environ.get('INFINIBOX_PASSWORD'):
        system = InfiniBox(box,
                           auth=(environ.get('INFINIBOX_USER'),
                                 environ.get('INFINIBOX_PASSWORD')))
    elif path.isfile(path.expanduser('~') + '/.infinidat/infinisdk.ini'):
        system = InfiniBox(box)
    else:
        module.fail_json(
            msg=
            "You must set INFINIBOX_USER and INFINIBOX_PASSWORD environment variables or set username/password module arguments"
        )

    try:
        system.login()
    except Exception:
        module.fail_json(
            msg="Infinibox authentication failed. Check your credentials")
    return system
예제 #6
0
def init(opts):
    '''
    Open the connection to the ibox device, login, and bind to the
    Resource class
    '''
    opts['multiprocessing'] = False
    log.debug('Opening connection to ibox')

    args = {"host": opts['proxy']['host'],"user": opts['proxy']['username'],"password":opts['proxy']['password']}
#    optional_args = ['user',
#                     'username',
#                     'password',
#                     'passwd'
#                     ]
#
#    if 'username' in opts['proxy'].keys():
#        opts['proxy']['user'] = opts['proxy'].pop('username')
#    proxy_keys = opts['proxy'].keys()
#    for arg in optional_args:
#        if arg in proxy_keys:
#            args[arg] = opts['proxy'][arg]

    
    thisproxy['conn'] = InfiniBox(args["host"], auth=(args["user"], str(args["password"])))
    thisproxy['conn'].login()
    thisproxy['initialized'] = True
예제 #7
0
def run(*args, **kwargs):
    user, box, password = args
    simulation = False
    if kwargs["mode"] == 'delete':
        print("delete-snapshots")
    elif kwargs["mode"] == 'status':
        print("status")
        simulation = True
        #t = PrettyTable(['instance name', 'creation timestamp', 'retention days', 'snapshot name', 'lock state', 'expiration date', 'action'])
        #print ("instance name \t | creation timestamp \t | retention days \t | snapshot name \t |  lock state \t | expiration date \t | action")
    else:
        usage()
        exit()
    config = read_config(config_file)
    auth = (args[0], args[2])
    b = InfiniBox(args[1], auth=auth)
    b.login()
    iter_snap(config, b, kwargs["mode"], "filesystems")
    iter_snap(config, b, kwargs["mode"], "volumes")
예제 #8
0
def get_system(module):
    """Return System Object or Fail"""
    box = module.params['system']
    user = module.params.get('user', None)
    password = module.params.get('password', None)

    if user and password:
        system = InfiniBox(box, auth=(user, password))
    elif environ.get('INFINIBOX_USER') and environ.get('INFINIBOX_PASSWORD'):
        system = InfiniBox(box, auth=(environ.get('INFINIBOX_USER'), environ.get('INFINIBOX_PASSWORD')))
    elif path.isfile(path.expanduser('~') + '/.infinidat/infinisdk.ini'):
        system = InfiniBox(box)
    else:
        module.fail_json(msg="You must set INFINIBOX_USER and INFINIBOX_PASSWORD environment variables or set username/password module arguments")

    try:
        system.login()
    except Exception:
        module.fail_json(msg="Infinibox authentication failed. Check your credentials")
    return system
예제 #9
0
def apply(config_parser, address, pool_name, username, password, volume_backend_name=None, thick_provisioning=False, prefer_fc=False, infinidat_allow_pool_not_found=False, infinidat_purge_volume_on_deletion=False):
    import sys
    from infinisdk import InfiniBox
    from infinisdk.core.exceptions import SystemNotFoundException
    from infinidat_openstack.versioncheck import raise_if_unsupported, get_system_version
    try:
        system = InfiniBox(address, use_ssl=True, auth=(username, password))
    except SystemNotFoundException:
        system = None
    if system is None:
        print("Could not connect to system \"{}\"".format(pool_name), file=sys.stderr)
        raise SystemExit(1)
    system.login()
    raise_if_unsupported(get_system_version(address, username, password, system))
    pool = system.pools.safe_get(name=pool_name)
    if pool is None:
        print("Pool \"{}\" not found".format(pool_name), file=sys.stderr)
        raise SystemExit(1)
    pool_id = pool.get_id()
    key = "infinibox-{0}-pool-{1}".format(system.get_serial(), pool.get_id()) if not volume_backend_name else volume_backend_name
    enabled = True
    for backend in get_volume_backends(config_parser):
        if backend['address'] == address and backend['pool_id'] == pool_id:
            key = backend['key']
            enabled = key in get_enabled_backends(config_parser)
    if not config_parser.has_section(key):
        config_parser.add_section(key)
    config_parser.set(key, "volume_driver", VOLUME_DRIVER)
    for setting in SETTINGS:
        config_parser.set(key, setting[1], locals()[setting[0]])
    config_parser.set(key, 'san_password', mask(password))
    config_parser.set(key, "infinidat_provision_type", "thick" if thick_provisioning else "thin")
    config_parser.set(key, "infinidat_prefer_fc", prefer_fc)
    config_parser.set(key, "infinidat_allow_pool_not_found", infinidat_allow_pool_not_found)
    config_parser.set(key, "infinidat_purge_volume_on_deletion", infinidat_purge_volume_on_deletion)
    if enabled:
        enable(config_parser, key)
    return key
예제 #10
0
    def do_setup(self, context):
        from infinisdk.core.exceptions import ObjectNotFound
        from infinidat_openstack.config import is_masked, unmask
        for key in ('infinidat_provision_type', 'infinidat_pool_id', 'san_login', 'san_password'):
            if not self.configuration.safe_get(key):
                raise exception.InvalidInput(reason=translate("{0} must be set".format(key)))

        provision_type = self.configuration.infinidat_provision_type
        if provision_type.upper() not in ('THICK', 'THIN'):
            raise exception.InvalidInput(reason=translate("infinidat_provision_type must be THICK or THIN"))

        from infinisdk import InfiniBox
        self.system = InfiniBox(self.configuration.san_ip,
                                auth=(self.configuration.san_login,
                                      unmask(self.configuration.san_password) if \
                                      is_masked(self.configuration.san_password) else \
                                      self.configuration.san_password))
        self.system.login()
        try:
            self._get_pool()  # we want to search for the pool here so we fail if we can't find it.
        except (ObjectNotFound, exception.InvalidInput):
            if not self.configuration.infinidat_allow_pool_not_found:
                raise
            LOG.info("InfiniBox pool not found, but infinidat_allow_pool_not_found is set")
예제 #11
0
# show command line options
if options.verbose:
	# store password temporarily
	password = options.password

	# hide password from output
	options.password = "******"

	# show command line options
	print "command line options:\n%s\n" % (pformat(vars(options)))

	# restore password
	options.password = password

global_vars.system = InfiniBox(options.fqdn, auth=(options.username, options.password))

global_vars.system.login()

state = 0
total = 0
hosts = global_vars.system.hosts
vols = global_vars.system.volumes
pools = global_vars.system.pools
luns = global_vars.system.luns
clusters = global_vars.system.host_clusters
total_space_allocated = 0
total_space_used = 0
i = 0 # For loop iterator

# build proper message
예제 #12
0
def iboxauth(ibox, user, pw):
    ibox = InfiniBox(ibox, auth=(user, pw))
    ibox.login()
    return ibox
예제 #13
0
import requests
import os
import json
from infinisdk import InfiniBox
from capacity import GiB
import argparse
box_a = 'ibox2373'
box_b = 'ibox606'
auth = ('infinidat', '123456')
box_a_object = InfiniBox(box_a, auth)
box_b_object = InfiniBox(box_b, auth)
box_a_object.login()
box_b_object.login()
volume_name = 'ds3'
host = 'iocloudcore-02'
additional = 2 * GiB


def get_args():
    """
    Supports the command-line arguments listed below.
    """
    parser = argparse.ArgumentParser(
        description="Resizing replica for Active/Active")
    parser.add_argument('-v',
                        '--volume',
                        nargs=1,
                        required=True,
                        help='Name of the volume')
    parser.add_argument('-s',
                        '--size',
예제 #14
0
class InfiniboxVolumeDriver(driver.VolumeDriver):
    VERSION = __version__

    def __init__(self, *args, **kwargs):
        super(InfiniboxVolumeDriver, self).__init__(*args, **kwargs)
        self.configuration.append_config_values(volume_opts)
        self.configuration.append_config_values(san_opts)
        self.volume_backend_name = self.configuration.config_group
        self.system = None
        self.pool = None
        self.volume_stats = None

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def do_setup(self, context):
        from infinisdk.core.exceptions import ObjectNotFound
        from infinidat_openstack.config import is_masked, unmask
        for key in ('infinidat_provision_type', 'infinidat_pool_id', 'san_login', 'san_password'):
            if not self.configuration.safe_get(key):
                raise exception.InvalidInput(reason=translate("{0} must be set".format(key)))

        provision_type = self.configuration.infinidat_provision_type
        if provision_type.upper() not in ('THICK', 'THIN'):
            raise exception.InvalidInput(reason=translate("infinidat_provision_type must be THICK or THIN"))

        from infinisdk import InfiniBox
        self.system = InfiniBox(self.configuration.san_ip,
                                auth=(self.configuration.san_login,
                                      unmask(self.configuration.san_password) if \
                                      is_masked(self.configuration.san_password) else \
                                      self.configuration.san_password))
        self.system.login()
        try:
            self._get_pool()  # we want to search for the pool here so we fail if we can't find it.
        except (ObjectNotFound, exception.InvalidInput):
            if not self.configuration.infinidat_allow_pool_not_found:
                raise
            LOG.info("InfiniBox pool not found, but infinidat_allow_pool_not_found is set")

    # Since we no longer inherit from SanDriver, we have to implement the four following methods:

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def ensure_export(self, context, volume):
        """Synchronously recreates an export for a logical volume."""
        pass

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_export(self, context, volume, connector=None):
        """Exports the volume."""
        pass

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def remove_export(self, context, volume):
        """Removes an export for a logical volume."""
        pass

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def check_for_setup_error(self):
        """Returns an error if prerequisites aren't met."""
        if not self.configuration.san_password:
            raise exception.InvalidInput(reason=translate('Specify san_password'))

        # The san_ip must always be set, because we use it for the target
        if not self.configuration.san_ip:
            raise exception.InvalidInput(reason=translate("san_ip must be set"))

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_volume(self, cinder_volume):
        infinidat_volume = self.system.volumes.create(name=self._create_volume_name(cinder_volume),
                                                      size=cinder_volume.size * GiB,
                                                      pool=self._get_pool(),
                                                      provisioning=self._get_provisioning())
        if hasattr(cinder_volume, 'consistencygroup') and cinder_volume.consistencygroup:
            cinder_cg = cinder_volume.consistencygroup
            self._add_volume_to_cg(infinidat_volume, cinder_cg)
        else:
            cinder_cg = None
        self._set_volume_or_snapshot_metadata(
            infinidat_volume,
            cinder_volume,
            cinder_cg=cinder_cg)

    def _purge_infinidat_volume(self, infinidat_volume):
        if infinidat_volume.is_mapped():
            infinidat_volume.unmap()

        for child in list(infinidat_volume.get_children()):
            self._purge_infinidat_volume(child)

        infinidat_volume.delete()

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def delete_volume(self, cinder_volume):
        from infinisdk.core.exceptions import ObjectNotFound
        try:
            infinidat_volume = self._find_volume(cinder_volume)
        except ObjectNotFound:
            LOG.info("delete_volume: volume {0!r} not found in InfiniBox, returning None".format(cinder_volume))
            return
        metadata = infinidat_volume.get_all_metadata()

        if infinidat_volume.has_children():
            raise exception.VolumeIsBusy(volume_name=translate(infinidat_volume.get_name()))

        delete_parent = metadata.get("delete_parent", "false").lower() == "true"
        object_to_delete = infinidat_volume.get_parent() if delete_parent else infinidat_volume

        if self.configuration.infinidat_purge_volume_on_deletion:
            self._purge_infinidat_volume(object_to_delete)
        else:
            object_to_delete.delete()

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def initialize_connection(self, cinder_volume, connector, initiator_data=None):
        # connector is a dict containing information about the connection. For example:
        # connector={u'ip': u'172.16.86.169', u'host': u'openstack01', u'wwnns': [u'20000000c99115ea'],
        #            u'initiator': u'iqn.1993-08.org.debian:01:1cef2344a325', u'wwpns': [u'10000000c99115ea']}

        self._assert_connector(connector)
        methods = dict(fc=self._initialize_connection__fc,
                       iscsi=self._initialize_connection__iscsi)
        return self._handle_connection(methods, cinder_volume, connector)

    def _get_or_create_lun(self, host, volume):
        for logical_unit in host.get_luns():
            if logical_unit.get_volume() == volume:
                return logical_unit.get_lun()
        return host.map_volume(volume).get_lun()

    def _get_iscsi_network_space(self):
        from infinisdk.core.exceptions import ObjectNotFound
        preferred_network_space = self.configuration.infinidat_preferred_iscsi_network_space
        try:
            if preferred_network_space:
                return self.system.network_spaces.get(service="ISCSI_SERVICE", name=preferred_network_space)
            return self.system.network_spaces.choose(service="ISCSI_SERVICE")
        except ObjectNotFound:
            if preferred_network_space:
                msg = "Can't find iSCSI network space {}".format(preferred_network_space)
            else:
                msg = "Can't find any iSCSI network space"
            raise ISCSINetworkSpaceNotFoundException(msg)


    def _get_iscsi_portal(self, iscsi_network_space):
        preferred_portal = self.configuration.infinidat_preferred_iscsi_portal
        port = iscsi_network_space.get_properties().iscsi_tcp_port
        available_portals = ["{}:{}".format(interface.ip_address, port) for interface in iscsi_network_space.get_ips()]
        for portal in available_portals:
            if not preferred_portal or preferred_portal == portal:
                return portal
        msg = "Preferred portal {} was not found. available portals:{!r}".format(preferred_portal, available_portals)
        raise ISCSIPortalNotFoundException(msg)


    def _initialize_connection__fc(self, cinder_volume, connector):
        infinidat_volume = self._find_volume(cinder_volume)
        for wwpn in connector[u'wwpns']:
            host = self._find_or_create_host_by_port(wwpn)
            self._set_host_metadata(host)
            lun = self._get_or_create_lun(host, infinidat_volume)
        access_mode = 'ro' if infinidat_volume.is_write_protected() else 'rw'
        target_wwn = [str(wwn) for wwn in self.system.components.fc_ports.get_online_target_addresses()]

        # See comments in cinder/volume/driver.py:FibreChannelDriver about the structure we need to return.
        return dict(driver_volume_type='fibre_channel',
                    data=dict(target_discovered=False, target_wwn=target_wwn, target_lun=lun, access_mode=access_mode))

    def _initialize_connection__iscsi(self, cinder_volume, connector):
        from infi.dtypes.iqn import IQN
        infinidat_volume = self._find_volume(cinder_volume)
        host = self._find_or_create_host_by_port(IQN(connector[u'initiator']))
        self._set_host_metadata(host)
        lun = self._get_or_create_lun(host, infinidat_volume)
        access_mode = 'ro' if infinidat_volume.is_write_protected() else 'rw'


        iscsi_network_space = self._get_iscsi_network_space()
        target_portal = self._get_iscsi_portal(iscsi_network_space)
        target_iqn = iscsi_network_space.get_properties().iscsi_iqn

        return dict(driver_volume_type='iscsi',
                    data=dict(
                              target_discovered=True,
                              volume_id=cinder_volume.id,
                              access_mode=access_mode,
                              target_portal=target_portal,
                              target_iqn=target_iqn,
                              target_lun=lun,
                              ))

    def _handle_connection(self, protocol_methods, cinder_volume, connector, *args, **kwargs):
        preferred_fc = self.configuration.infinidat_prefer_fc
        fc, iscsi = connector.get('wwpns'), connector.get('initiator')
        if not fc and not iscsi:
            raise exception.Invalid(translate(("no wwpns or iscsi initiator in connector {0}".format(connector))))
        elif fc and (not iscsi or preferred_fc):
            return protocol_methods['fc'](cinder_volume, connector, *args, **kwargs)
        else:
            return protocol_methods['iscsi'](cinder_volume, connector, *args, **kwargs)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def terminate_connection(self, cinder_volume, connector, force=False, **kwargs):
        self._assert_connector(connector)
        methods = dict(fc=self._terminate_connection__fc,
                       iscsi=self._terminate_connection__iscsi)
        return self._handle_connection(methods, cinder_volume, connector, force=force)

    def _terminate_connection__fc(self, cinder_volume, connector, force=False):
        from infinisdk.core.exceptions import ObjectNotFound
        infinidat_volume = self._find_volume(cinder_volume)
        for wwpn in connector[u'wwpns']:
            try:
                host = self._find_host_by_port(wwpn)
            except ObjectNotFound:
                continue
            self._set_host_metadata(host)
            host.unmap_volume(infinidat_volume)
            LOG.info("Volume(name={0!r}, id={1}) unmapped from Host (name={2!r}, id={3}) successfully".format(
                    infinidat_volume.get_name(), infinidat_volume.get_id(), host.get_name(), host.get_id()))
            self._delete_host_if_unused(host)

    def _terminate_connection__iscsi(self, cinder_volume, connector, force=False):
        infinidat_volume = self._find_volume(cinder_volume)
        try:
            host = self._find_host_by_port(connector[u'initiator'])
        except ObjectNotFound:
            return
        self._set_host_metadata(host)
        metadata_before_unmap = host.get_all_metadata()
        host.unmap_volume(infinidat_volume)
        LOG.info("Volume(name={0!r}, id={1}) unmapped from Host (name={2!r}, id={3}) successfully".format(
                    infinidat_volume.get_name(), infinidat_volume.get_id(), host.get_name(), host.get_id()))
        self._delete_host_if_unused(host)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_volume_from_snapshot(self, cinder_volume, cinder_snapshot):
        infinidat_snapshot = self._find_snapshot(cinder_snapshot)
        if cinder_volume.size * GiB < infinidat_snapshot.get_size():
            msg = "cannot shrink snapshot. original size={}, target size={}".format(infinidat_snapshot.get_size(), cinder_volume.size * GiB)
            raise exception.InvalidInput(reason=translate(msg))
        infinidat_volume = infinidat_snapshot.create_child(name=self._create_volume_name(cinder_volume))
        infinidat_volume.disable_write_protection()
        infinidat_volume.update_size(cinder_volume.size * GiB)
        if hasattr(cinder_volume, 'consistencygroup') and cinder_volume.consistencygroup:
            cinder_cg = cinder_volume.consistencygroup
            self._add_volume_to_cg(infinidat_volume, cinder_cg)
        else:
            cinder_cg = None
        self._set_volume_or_snapshot_metadata(
            infinidat_volume,
            cinder_volume,
            cinder_cg=cinder_cg)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_cloned_volume(self, tgt_cinder_volume, src_cinder_volume):
        if tgt_cinder_volume.size < src_cinder_volume.size:
            msg = "cannot shrink clone. original size={}, target size={}".format(src_cinder_volume.size, tgt_cinder_volume.size)
            raise exception.InvalidInput(reason=translate(msg))
        src_infinidat_volume = self._find_volume(src_cinder_volume)
        # We first create a snapshot and then a clone from that snapshot.
        snapshot = src_infinidat_volume.create_snapshot(name=self._create_snapshot_name(src_cinder_volume) + "-internal")
        self._set_obj_metadata(snapshot, {
            "cinder_id": "",
            "internal": "true"
            })
        # We now create a clone from the snapshot
        tgt_infinidat_volume = snapshot.create_child(name=self._create_volume_name(tgt_cinder_volume))
        tgt_infinidat_volume.disable_write_protection()
        tgt_infinidat_volume.update_size(tgt_cinder_volume.size * GiB)
        if hasattr(tgt_cinder_volume, "consistencygroup") and tgt_cinder_volume.consistencygroup:
            cinder_cg = tgt_cinder_volume.consistencygroup
            self._add_volume_to_cg(tgt_infinidat_volume, cinder_cg)
        else:
            cinder_cg = None
        self._set_volume_or_snapshot_metadata(
            tgt_infinidat_volume,
            tgt_cinder_volume,
            delete_parent=True,
            cinder_cg=cinder_cg)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def extend_volume(self, cinder_volume, new_size):
        LOG.info("InfiniboxVolumeDriver.extend_volume")
        infinidat_volume = self._find_volume(cinder_volume)
        new_size_in_bytes = new_size * GiB
        if infinidat_volume.get_size() != new_size_in_bytes:
            if infinidat_volume.get_size() > new_size_in_bytes:
                msg = "cannot shrink volume: new size must be greater or equal to current size. original size={}, new size={}"
                raise exception.InvalidInput(reason=translate(msg.format(infinidat_volume.get_size(), new_size_in_bytes)))
            infinidat_volume.update_size(new_size_in_bytes)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def migrate_volume(self, context, volume, host):
        return False, None  # not supported: we can't migrate a volume between pools or between Infinibox machines

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_snapshot(self, cinder_snapshot):
        infinidat_volume = self._find_volume(cinder_snapshot.volume)
        infinidat_snapshot = infinidat_volume.create_snapshot(name=translate(self._create_snapshot_name(cinder_snapshot)))
        self._set_volume_or_snapshot_metadata(infinidat_snapshot, cinder_snapshot)

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def delete_snapshot(self, cinder_snapshot):
        infinidat_snapshot = self._find_snapshot(cinder_snapshot)
        if infinidat_snapshot.has_children():
            raise exception.SnapshotIsBusy(snapshot_name=translate(infinidat_snapshot.get_name()))
        infinidat_snapshot.delete()

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def get_volume_stats(self, refresh=False):
        if refresh or not self.volume_stats:
            self._update_volume_stats()
        return self.volume_stats

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_consistencygroup(self, context, cinder_cg):
        infinidat_cg = self.system.cons_groups.create(name=self._create_cg_name(cinder_cg), pool=self._get_pool())
        self._set_cg_metadata(infinidat_cg, cinder_cg)
        return {'status': 'available'}

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def delete_consistencygroup(self, context, cinder_cg, members=None):
        from infinisdk.core.exceptions import ObjectNotFound
        try:
            infinidat_cg = self._find_cg(cinder_cg)
        except ObjectNotFound:
            LOG.info("delete_consistencygroup: consistency group {0!r} not found in InfiniBox, returning None".format(cinder_cg))
            return
        infinidat_cg.delete()

        # 'members' (volumes) is passed as a parameter in liberty and above but not on kilo
        if members is None:
            memebers = self.db.volume_get_all_by_group(context, cinder_cg.id)
        for cinder_volume in memebers:
            self.delete_volume(cinder_volume)
            cinder_volume.status = 'deleted'

        return {'status': cinder_cg['status']}, memebers

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def update_consistencygroup(self, context, cinder_cg, add_volumes=None, remove_volumes=None):
        infinidat_cg = self._find_cg(cinder_cg)
        for vol in add_volumes:
            infinidat_volume = self._find_volume(vol)
            infinidat_cg.add_member(infinidat_volume)
        for vol in remove_volumes:
            infinidat_volume = self._find_volume(vol)
            infinidat_cg.remove_member(infinidat_volume)

        return None, None, None

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def create_cgsnapshot(self, context, cgsnapshot):
        # For some reason the cinder consistencygroup object is not passed here correctly
        cinder_cg_id = cgsnapshot.consistencygroup_id
        infinidat_cg = self._find_cg_by_id(cinder_cg_id)
        infinidat_cgsnap = infinidat_cg.create_snapshot(name=self._create_cgsnapshot_name(cgsnapshot))
        members = self.db.snapshot_get_all_for_cgsnapshot(context, cgsnapshot.id)
        for snapshot in members:
            for infinidat_snapshot in infinidat_cgsnap.get_members():
                if snapshot.volume_id in infinidat_snapshot.get_parent().get_name():
                    infinidat_snapshot.update_name(self._create_snapshot_name(snapshot))
            snapshot.status = 'available'
        self._set_cg_metadata(infinidat_cgsnap, cgsnapshot)
        return {'status': 'available'}, members

    @logbook_compat
    @infinisdk_to_cinder_exceptions
    def delete_cgsnapshot(self, context, cgsnapshot, members=None):
        # 'members' (snapshots) is passed as a parameter in liberty and above but not on kilo
        if members is None:
            members = self.db.snapshot_get_all_for_cgsnapshot(context, cgsnapshot.id)
        from infinisdk.core.exceptions import ObjectNotFound
        try:
            # This cgsanpshot is actualy a consistency group object in the system
            infinidat_cgsnapshot = self._find_cgsnap(cgsnapshot)
        except ObjectNotFound:
            LOG.info("delete_cgsnapshot: cgsnapshot {0!r} not found in InfiniBox, returning None".format(cgsnapshot))
        else:
            infinidat_cgsnapshot.delete()

        for cinder_snapshot in members:
            self.delete_snapshot(cinder_snapshot)
            cinder_snapshot.status = 'deleted'

        return {'status': cgsnapshot.status}, members

    def _update_volume_stats(self):
        from infinisdk.core.exceptions import ObjectNotFound
        """Retrieve stats info from volume group."""

        data = {}
        data["volume_backend_name"] = self.volume_backend_name
        data["vendor_name"] = STATS_VENDOR
        data["driver_version"] = self.VERSION
        data["storage_protocol"] = 'FC' if self.configuration.infinidat_prefer_fc else 'iSCSI'
        data["consistencygroup_support"] = 'True'

        try:
            data['total_capacity_gb'] = self._get_pool().get_physical_capacity() / GiB
            data['free_capacity_gb'] = self._get_pool().get_free_physical_capacity() / GiB
        except (ObjectNotFound, exception.InvalidInput):
            data['total_capaceity_gb'] = 0
            data['free_capacity_gb'] = 0

        data['reserved_percentage'] = 0
        data['QoS_support'] = False
        self.volume_stats = data

    def _get_pool(self):
        if not self.pool:
            pools = self.system.pools.find(id=int(self.configuration.infinidat_pool_id))
            if not pools:
                raise exception.InvalidInput(translate("pool {0} not found".format(int(self.configuration.infinidat_pool_id))))
            self.pool = pools[0]
        return self.pool

    def _find_volume(self, cinder_volume):
        return self.system.volumes.get(name=self._create_volume_name(cinder_volume))

    def _find_snapshot(self, cinder_snapshot):
        return self.system.volumes.get(name=self._create_snapshot_name(cinder_snapshot))

    def _find_cg(self, cinder_cg):
        return self.system.cons_groups.get(name=self._create_cg_name(cinder_cg))

    def _find_cg_by_id(self, cinder_cg_id):
        return self.system.cons_groups.get(name=self._create_cg_name_by_id(cinder_cg_id))

    def _find_cgsnap(self, cinder_cgsnap):
        cgsnap = self.system.cons_groups.get(name=self._create_cgsnapshot_name(cinder_cgsnap))
        assert cgsnap.is_snapgroup()  # Just making sure since these are actualy cg objects
        return cgsnap

    def _add_volume_to_cg(self, infinidat_volume, cinder_cg):
        from infinisdk.core.exceptions import ObjectNotFound
        try:
            infinidat_cg = self._find_cg(cinder_cg)
        except ObjectNotFound:
            LOG.info("create_volume: consistency group {0!r} not found in InfiniBox, not adding volume {0!r} to the group.".format(cinder_cg, infinidat_volume))
        else:
            infinidat_cg.add_member(infinidat_volume)

    def _find_host_by_port(self, port):
        return self.system.hosts.get(name=self._create_host_name_by_port(port))

    def _find_or_create_host_by_port(self, port):
        name = self._create_host_name_by_port(str(port))
        host = self.system.hosts.safe_get(name=name)
        if not host:
            host = self.system.hosts.create(name=name)
            host.add_port(port)
        return host

    def _delete_host_if_unused(self, host):
        from infinisdk.core.exceptions import APICommandFailed
        try:
            host.delete()
        except APICommandFailed, e:
            if 'HOST_NOT_EMPTY' in e.response.response.content:
                pass  # host still contains mappings
            else:
                raise  # some other bad thing happened
예제 #15
0
                        help='Ibox Name')
    parser.add_argument('-u',
                        '--user',
                        nargs=1,
                        required=True,
                        help='Ibox user')
    parser.add_argument('-p',
                        '--password',
                        nargs=1,
                        required=True,
                        help='Ibox password')
    args = parser.parse_args()
    return args


args = get_args()
auth = (args.user[0], args.password[0])
system = InfiniBox(args.ibox[0], auth)
try:
    system.login()
    volume = system.volumes.find(name=args.volume[0])
    if (volume.to_list()):
        volume = volume.to_list()[0]
    print(volume.get_name())
    for snap in volume.get_snapshots().to_list():
        sp = "^" + args.rename[0]
        if re.search(sp, snap.get_name()):
            new_name = (re.sub(sp, volume.get_name(), snap.get_name()))
            snap.update_name(new_name)
except Exception as E:
    print("Cannot run", E)
예제 #16
0
                        required=True,
                        help='Sync interval in minutes')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = get_args()
    if args.configfile:
        if os.path.isfile('{}'.format(args.configfile[0])):
            cfgargs = args_from_cfgfile(args.configfile[0])
            ibox1 = cfgargs['src_ibox']
            user1 = cfgargs['src_user']
            enc_pw1 = cfgargs['dst_password']
            ibox2 = cfgargs['dst_ibox']
            user2 = cfgargs['dst_user']
            enc_pw2 = cfgargs['src_password']
            v1_name = args.v1_name[0]
            v2_name = args.v2_name[0]
            rpo = args.rpo[0]
            interval = args.interval[0]
            pw1 = base64.b64decode(enc_pw1).decode("utf-8", "ignore")
            pw2 = base64.b64decode(enc_pw2).decode("utf-8", "ignore")
            src = InfiniBox(ibox1, auth=(user1, pw1))
            src.login()
            dst = InfiniBox(ibox2, auth=(user2, pw2))
            dst.login()
            rep = get_objects(v1_name, ibox2, v2_name, rpo, interval)
            if (rep.is_active()):
                print("\033[1;32;40m Replicated Successfuly \033[0m")