def execute(self, args):
        # Access newly created storage domain
        local_sd = self._api.storagedomains.get(args.name)

        # Find datacenter object
        local_dc = self._api.datacenters.get(args.datacenter)

        # Find host object
        local_host = self._api.hosts.get(args.host)

        # Build storage parameter
        stParams = params.Storage(path=args.path,
                                  address=args.server,
                                  type_=args.type)

        # Build storage domain parameter
        sdParams = params.StorageDomain(
            name=args.name,  #'local_export',
            data_center=local_dc,
            host=local_host,
            type_='export',
            storage=stParams,
            storage_format='v1')

        if self._api.storagedomains.add(sdParams):
            print 'Export Domain was created/imported successfully'

        # Access newly created storage domain
        local_sd = self._api.storagedomains.get(args.name)
Exemplo n.º 2
0
def add_iscsi_storage_domain(prefix):
    api = prefix.virt_env.engine_vm().get_api()

    # Find LUN GUIDs
    ret = prefix.virt_env.get_vm(SD_ISCSI_HOST_NAME).ssh(
        ['multipath', '-ll', '-v1', '|sort'])
    nt.assert_equals(ret.code, 0)

    lun_guids = ret.out.splitlines()[:SD_ISCSI_NR_LUNS]

    p = params.StorageDomain(
        name=SD_ISCSI_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format='v3',
        host=params.Host(name=api.hosts.list().pop().name, ),
        storage=params.Storage(
            type_='iscsi',
            volume_group=params.VolumeGroup(logical_unit=[
                params.LogicalUnit(
                    id=lun_id,
                    address=_get_host_ip(
                        prefix,
                        SD_ISCSI_HOST_NAME,
                    ),
                    port=SD_ISCSI_PORT,
                    target=SD_ISCSI_TARGET,
                ) for lun_id in lun_guids
            ]),
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 3
0
def add_iscsi_storage_domain(prefix):
    api = prefix.virt_env.engine_vm().get_api()

    # Find LUN GUIDs
    ret = prefix.virt_env.get_vm('storage-iscsi').ssh(['multipath', '-ll'], )
    nt.assert_equals(ret.code, 0)

    lun_guids = [
        line.split()[0] for line in ret.out.split('\n')
        if line.find('LIO-ORG') != -1
    ]

    lun_guids = lun_guids[:SD_ISCSI_NR_LUNS]

    p = params.StorageDomain(
        name=SD_ISCSI_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format='v3',
        host=params.Host(name=api.hosts.list().pop().name, ),
        storage=params.Storage(
            type_='iscsi',
            volume_group=params.VolumeGroup(logical_unit=[
                params.LogicalUnit(
                    id=lun_id,
                    address=SD_ISCSI_ADDRESS,
                    port=SD_ISCSI_PORT,
                    target=SD_ISCSI_TARGET,
                ) for lun_id in lun_guids
            ]),
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 4
0
def add_iscsi_storage_domain_3(prefix, lun_guids):
    api = prefix.virt_env.engine_vm().get_api()

    ips = _get_host_all_ips(prefix, SD_ISCSI_HOST_NAME)
    luns = []
    for lun_id in lun_guids:
        for ip in ips:
            lun = params.LogicalUnit(
                id=lun_id,
                address=ip,
                port=SD_ISCSI_PORT,
                target=SD_ISCSI_TARGET,
                username='******',
                password='******',
            )
            luns.append(lun)

    p = params.StorageDomain(
        name=SD_ISCSI_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format=SD_FORMAT,
        host=_random_host_from_dc(api, DC_NAME),
        storage=params.Storage(
            type_='iscsi',
            volume_group=params.VolumeGroup(logical_unit=luns),
        ),
    )
    _add_storage_domain_3(api, p)
Exemplo n.º 5
0
def add_directlun(prefix):
    # Find LUN GUIDs
    ret = prefix.virt_env.get_vm(SD_ISCSI_HOST_NAME).ssh(
        ['cat', '/root/multipath.txt'])
    nt.assert_equals(ret.code, 0)

    all_guids = ret.out.splitlines()
    lun_guid = all_guids[
        SD_ISCSI_NR_LUNS]  #Take the first unused LUN. 0-(SD_ISCSI_NR_LUNS) are used by iSCSI SD

    dlun_params = params.Disk(
        name=DLUN_DISK_NAME,
        interface='virtio_scsi',
        format='raw',
        lun_storage=params.Storage(
            type_='iscsi',
            logical_unit=[
                params.LogicalUnit(
                    id=lun_guid,
                    address=prefix.virt_env.get_vm(SD_ISCSI_HOST_NAME).ip(),
                    port=SD_ISCSI_PORT,
                    target=SD_ISCSI_TARGET,
                    username='******',
                    password='******',
                )
            ]),
        sgio='unfiltered',
    )

    api = prefix.virt_env.engine_vm().get_api()
    api.vms.get(VM0_NAME).disks.add(dlun_params)
    nt.assert_not_equal(
        api.vms.get(VM0_NAME).disks.get(DLUN_DISK_NAME), None,
        'Direct LUN disk not attached')
Exemplo n.º 6
0
def addStorageDomain():
    global controller
    logging.debug("Adding local storage domain")

    # strip last '/' from path if it's given. Otherwise, adding storage will
    # fail.
    try:
        logging.info("Creating local storage")
        stParams = params.Storage(
            path=controller.CONF["STORAGE_PATH"].rstrip('/'))
        stParams.set_type('localfs')

        logging.info("Creating local storage domain")
        sdParams = params.StorageDomain(
            name=LOCAL_STORAGE,
            data_center=controller.CONF["API_OBJECT"].datacenters.get(
                LOCAL_DATA_CENTER),
            storage_format='v1',
            host=controller.CONF["API_OBJECT"].hosts.get(LOCAL_HOST),
            storage=stParams)
        sdParams.set_type('data')

        logging.info("Adding local storage domain")
        controller.CONF["API_OBJECT"].storagedomains.add(sdParams)
    except:
        logging.error(traceback.format_exc())
        raise Exception(ERROR_ADD_LOCAL_DOMAIN)
Exemplo n.º 7
0
def add_iscsi_storage_domain(prefix):
    api = prefix.virt_env.engine_vm().get_api()

    # Find LUN GUIDs
    ret = prefix.virt_env.get_vm(SD_ISCSI_HOST_NAME).ssh(
        ['cat', '/root/multipath.txt'])
    nt.assert_equals(ret.code, 0)

    lun_guids = ret.out.splitlines()[:SD_ISCSI_NR_LUNS]

    p = params.StorageDomain(
        name=SD_ISCSI_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format=SD_FORMAT,
        host=_random_host_from_dc(api, DC_NAME),
        storage=params.Storage(
            type_='iscsi',
            volume_group=params.VolumeGroup(logical_unit=[
                params.LogicalUnit(
                    id=lun_id,
                    address=_get_host_ip(
                        prefix,
                        SD_ISCSI_HOST_NAME,
                    ),
                    port=SD_ISCSI_PORT,
                    target=SD_ISCSI_TARGET,
                    username='******',
                    password='******',
                ) for lun_id in lun_guids
            ]),
        ),
    )
    _add_storage_domain(api, p)
def create_lun(api, vm_name, disk_alias, lun_id):
    """
    Create a new direct attach disk from lun_id then attach to vm_name
    """
    try:
        lu = params.LogicalUnit()
        lu.set_id(lun_id)

        lus = list()
        lus.append(lu)

        storage_params = params.Storage()
        storage_params.set_id(lun_id)
        storage_params.set_logical_unit(lus)
        storage_params.set_type('fcp')
        disk_params = params.Disk()
        disk_params.set_format('raw')
        disk_params.set_interface('virtio')
        disk_params.set_alias(disk_alias)
        disk_params.set_active(True)
        disk_params.set_lun_storage(storage_params)

        if vm_name:
            if not MODULE_CHECK_MODE:
                vm = api.vms.get(name=vm_name)
                disk = vm.disks.add(disk_params)
        else:
            if not MODULE_CHECK_MODE:
                disk = api.disks.add(disk_params)
        return 1
    except Exception as e:
        raise Exception("Error while adding new lun: " + str(e))
Exemplo n.º 9
0
def add_iso_storage_domain(api):
    p = params.StorageDomain(
        name=SD_ISO_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='iso',
        host=params.Host(name=api.hosts.list().pop().name, ),
        storage=params.Storage(
            type_='nfs',
            address=SD_ISO_ADDRESS,
            path=SD_ISO_PATH,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 10
0
    def attach_iso_export_domain_into_datacenter(self,
                                                 address,
                                                 path,
                                                 dc_name,
                                                 host_name,
                                                 domain_type,
                                                 storage_type='nfs',
                                                 name='my_iso'):
        """
        Attach ISO/export domain into data center.

        :param name: ISO or Export name.
        :param host_name: host name.
        :param dc_name: data center name.
        :param path: ISO/export domain path.
        :param address: ISO/export domain address.
        :param domain_type: storage domain type, it may be 'iso' or 'export'.
        :param storage_type: storage type, it may be 'nfs', 'iscsi', or 'fc'.
        """
        dc = self.api.datacenters.get(dc_name)
        host = self.api.hosts.get(host_name)
        storage_params = param.Storage(type_=storage_type,
                                       address=address,
                                       path=path)

        storage_domain__params = param.StorageDomain(name=name,
                                                     data_center=dc,
                                                     type_=domain_type,
                                                     host=host,
                                                     storage=storage_params)

        try:
            logging.info('Create/import ISO storage domain %s' % name)
            if self.api.storagedomains.add(storage_domain__params):
                logging.info('%s domain was created/imported successfully' %
                             domain_type)

            logging.info('Attach ISO storage domain %s' % name)
            if self.api.datacenters.get(dc_name).storagedomains.add(
                    self.api.storagedomains.get(name)):
                logging.info('%s domain was attached successfully' %
                             domain_type)

            logging.info('Activate ISO storage domain %s' % name)
            if self.api.datacenters.get(dc_name).storagedomains.get(
                    name).activate():
                logging.info('%s domain was activated successfully' %
                             domain_type)
        except Exception as e:
            logging.error('Failed to add %s domain:\n%s' %
                          (domain_type, str(e)))
Exemplo n.º 11
0
def add_iso_storage_domain(prefix):
    api = prefix.virt_env.engine_vm().get_api()
    p = params.StorageDomain(
        name=SD_ISO_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='iso',
        host=params.Host(name=api.hosts.list().pop().name, ),
        storage=params.Storage(
            type_='nfs',
            address=_get_host_ip(prefix, SD_ISO_HOST_NAME),
            path=SD_ISO_PATH,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 12
0
def add_templates_storage_domain(api):
    p = params.StorageDomain(
        name=SD_TEMPLATES_NAME,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format='v3',
        host=params.Host(name=api.hosts.list().pop().name),
        storage=params.Storage(
            type_='nfs',
            address=SD_TEMPLATES_ADDRESS,
            path=SD_TEMPLATES_PATH,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 13
0
def ovirt_create_storage(module):

    name = module.params['name']
    datacenter = module.params['datacenter']
    host = module.params['host']
    path = module.params['path']
    type = module.params['type']
    storage_type = module.params['storage_type']
    storage_url = module.params['storage_url']
    username = module.params['username']
    password = module.params['password']
    url = module.params['url']

    try:
        api = API(url=url,
                  username=username,
                  password=password,
                  insecure=True,
                  session_timeout=60)
    except Exception as ex:
        module.fail_json(msg='could not connect to ovirt api')

    isoParams = params.StorageDomain(
        name=name,
        data_center=api.datacenters.get(datacenter),
        type_=storage_type,
        host=api.hosts.get(host),
        storage=params.Storage(
            type_=type,
            address=storage_url,
            path=path,
        ))

    if api.datacenters.get(datacenter).storagedomains.get(name):
        module.exit_json(changed=False)

    if module.check_mode:
        module.exit_json(changed=True)

    try:
        sd = api.storagedomains.add(isoParams)
        api.datacenters.get(datacenter).storagedomains.add(
            api.storagedomains.get(name))
    except Exception as ex:
        module.fail_json(msg='Adding storage domain failed' + str(ex))

    module.exit_json(changed=True)
Exemplo n.º 14
0
def add_generic_nfs_storage_domain_3(prefix, sd_nfs_name, nfs_host_name, mount_path, sd_format=SD_FORMAT, sd_type='data', nfs_version='v4_1'):
    api = prefix.virt_env.engine_vm().get_api()
    p = params.StorageDomain(
        name=sd_nfs_name,
        data_center=params.DataCenter(
            name=DC_NAME,
        ),
        type_=sd_type,
        storage_format=sd_format,
        host=_random_host_from_dc(api, DC_NAME),
        storage=params.Storage(
            type_='nfs',
            address=_get_host_ip(prefix, nfs_host_name),
            path=mount_path,
            nfs_version=nfs_version,
        ),
    )
    _add_storage_domain_3(api, p)
Exemplo n.º 15
0
def create_nfs_storage(api, spm, storage_type):
    # TODO : make a better function with dynamic storage selection
    # for making it simple the type and the name are the same
    storage_formats = {'data': 'V3', 'export': 'V1'}

    storage_params = params.StorageDomain(name=storage_type,
                                          data_center=api.datacenters.get(
                                              "Default"),
                                          storage_format=storage_formats[
                                              storage_type],
                                          type_=storage_type,
                                          host=spm,
                                          storage=params.Storage(type_="NFS",
                                                                 address="192.168.100.100",
                                                                 path='/' + storage_type))
    api.storagedomains.add(storage_params)
    api.datacenters.get(name="Default").storagedomains.add(
        api.storagedomains.get(name=storage_type))
Exemplo n.º 16
0
def add_generic_nfs_storage_domain(prefix, sd_nfs_name, nfs_host_name, mount_path, sd_format='v3', sd_type='data'):
    api = prefix.virt_env.engine_vm().get_api()
    p = params.StorageDomain(
        name=sd_nfs_name,
        data_center=params.DataCenter(
            name=DC_NAME,
        ),
        type_=sd_type,
        storage_format=sd_format,
        host=params.Host(
            name=api.hosts.list().pop().name,
        ),
        storage=params.Storage(
            type_='nfs',
            address=_get_host_ip(prefix, nfs_host_name),
            path=mount_path,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 17
0
def add_glusterfs_storage_domain(prefix, sdname, volname):
    api = prefix.virt_env.engine_vm().get_api()
    hosts = sorted([vm.name() for vm in prefix.virt_env.host_vms()])
    mount_path = "{0}://{1}".format(hosts[0], volname)
    mount_options = "backup-volfile-servers={0}".format(':'.join(hosts[1:]))

    p = params.StorageDomain(
        name=sdname,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format='v3',
        host=_random_host_from_dc(api, DC_NAME),
        storage=params.Storage(
            type_='glusterfs',
            path=mount_path,
            vfs_type='glusterfs',
            mount_options=mount_options,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 18
0
def add_glusterfs_storage_domain(prefix, sdname, volname):
    api = prefix.virt_env.engine_vm().get_api()
    mount_path = "{0}://{1}".format(_get_host_ip(prefix, GLUSTER_HOST0),
                                    volname)
    mount_options = "backup-volfile-servers={0}:{1}".format(
        _get_host_ip(prefix, GLUSTER_HOST1),
        _get_host_ip(prefix, GLUSTER_HOST2))
    p = params.StorageDomain(
        name=sdname,
        data_center=params.DataCenter(name=DC_NAME, ),
        type_='data',
        storage_format='v3',
        host=_random_host_from_dc(api, DC_NAME),
        storage=params.Storage(
            type_='glusterfs',
            path=mount_path,
            vfs_type='glusterfs',
            mount_options=mount_options,
        ),
    )
    _add_storage_domain(api, p)
Exemplo n.º 19
0
    def connect_direct_lun_to_appliance(self, vm_name, disconnect):
        """Connects or disconnects the direct lun disk to an appliance.

        Args:
            vm_name: Name of the VM with the appliance.
            disconnect: If False, it will connect, otherwise it will disconnect
        """
        if "provider_key" in self.kwargs:
            provider_name = self.kwargs["provider_key"]
        else:
            raise TypeError("provider_key not supplied to the provider.")
        # check that the vm exists on the rhev provider, get the ip address if so
        try:
            vm = self.api.vms.get(vm_name)
            ip_addr = self.get_ip_address(vm_name)
        except:
            raise NameError("{} not found on  {}".format(
                vm_name, provider_name))

        # check for direct lun definition on provider's cfme_data.yaml
        if 'direct_lun' not in self.kwargs:
            raise ValueError(
                "direct_lun key not in cfme_data.yaml under provider {}, exiting..."
                .format(provider_name))

        # does the direct lun exist
        prov_data = self.kwargs
        dlun_name = prov_data['direct_lun']['name']
        dlun = self.api.disks.get(dlun_name)
        if dlun is None:

            #    Create the iSCSI storage connection:
            sc = params.StorageConnection()
            sc.set_address(prov_data['direct_lun']['ip_address'])
            sc.set_type("iscsi")
            sc.set_port(int(prov_data['direct_lun']['port']))
            sc.set_target(prov_data['direct_lun']['iscsi_target'])

            #    Add the direct LUN disk:
            lu = params.LogicalUnit()
            lu.set_id(prov_data['direct_lun']['iscsi_target'])
            lu.set_address(sc.get_address())
            lu.set_port(sc.get_port())
            lu.set_target(sc.get_target())
            storage = params.Storage()
            storage.set_type("iscsi")
            storage.set_logical_unit([lu])
            disk = params.Disk()
            disk.set_name(dlun_name)
            disk.set_interface("virtio")
            disk.set_type("iscsi")
            disk.set_format("raw")
            disk.set_lun_storage(storage)
            disk.set_shareable(True)
            disk = self.api.disks.add(disk)
            dlun = self.api.disks.get(dlun_name)

        # add it
        if not disconnect:
            retries = 0
            while retries < 3:
                retries += 1
                direct_lun = params.Disk(id=dlun.id)
                try:
                    # is the disk present and active?
                    vm_disk_list = vm.get_disks().list()
                    for vm_disk in vm_disk_list:
                        if vm_disk.name == dlun_name:
                            if vm_disk.active:
                                return
                            else:
                                vm_disk.activate()
                                return

                    # if not present, add it and activate
                    direct_lun = params.Disk(id=dlun.id)
                    added_lun = vm.disks.add(direct_lun)
                    added_lun.activate()
                except Exception as e:
                    logger.error("Exception caught: %s", str(e))
                    if retries == 3:
                        logger.error("exhausted retries and giving up")
                        raise
                    else:
                        logger.info(
                            "sleeping for 30s and retrying to connect direct lun"
                        )
                        time.sleep(30)

            # Init SSH client, run pvscan on the appliance
            ssh_kwargs = {
                'username': conf.credentials['ssh']['username'],
                'password': conf.credentials['ssh']['password'],
                'hostname': ip_addr
            }
            with SSHClient(**ssh_kwargs) as ssh_client:
                status, out = ssh_client.run_command('pvscan', timeout=5 * 60)

        # remove it
        else:
            vm_dlun = vm.disks.get(name=dlun_name)
            if vm_dlun is None:
                return
            else:
                detach = params.Action(detach=True)
                vm_dlun.delete(action=detach)
Exemplo n.º 20
0
while not os.path.isfile(CA):
    print "Missing certificate, attempting to get from the server"
    CERT = urllib2.urlopen("https://rhevm.example.com/ca.crt")
    output = open(CA, 'wb')
    output.write(CERT.read())
    output.close()

api = API(url=URL, username=USERNAME, password=PASSWORD, ca_file=CA)

try:

    dc = api.datacenters.get(name="Default")
    h = api.hosts.get(name=HOST_NAME)

    s = params.Storage(address="192.168.103.1",
                       path="/srv/rhev-sd1",
                       type_="nfs")
    sd_params = params.StorageDomain(name=STORAGE_NAME,
                                     data_center=dc,
                                     host=h,
                                     type_="data",
                                     storage_format="v3",
                                     storage=s)

    try:
        for sd in api.storagedomains.list():
            print sd.name
    except Exception as ex:
        print "Problem listing storage domains %s." % ex
        sys.exit(2)
Exemplo n.º 21
0
    print 'Failed to setup network:\n%s' % str(e)

# Add data domain
''' Add iscsi target
    storage = params.Storage(type_='iscsi',
        volume_group=params.VolumeGroup(logical_unit=[params.LogicalUnit(id=LUN_GUID,
        address=STORAGE_ADDRESS,
        port=3260,
        target=TARGET_NAME)])))
'''
sdParams = params.StorageDomain(name=DATA_NAME,
                                data_center=api.datacenters.get(DC_NAME),
                                storage_format='v3',
                                type_='data',
                                host=api.hosts.get(HOST_NAME),
                                storage=params.Storage(type_='localfs',
                                                       path=DATA_PATH))

try:
    if api.storagedomains.add(sdParams):
        print 'Local Storage Domain was created successfully'
except Exception as e:
    print 'Failed to create Local Storage Domain:\n%s' % str(e)
    exit(1)

#try:
#    if api.datacenters.get(name=DC_NAME).storagedomains.add(api.storagedomains.get(name=STORAGE_NAME)):
#        print 'Local Storage Domain was attached successfully'
#except Exception as e:
#    print 'Failed to attach Local Storage Domain:\n%s' % str(e)

# Add iso domain