Get virtual block devices on VM

    .. code-block:: bash

        salt-cloud -a destroy_vm_vdis  xenvm01
355964
def destroy_vm_vdis(name=None, session=None, call=None):
    '''
    

    '''
    if session is None:
        session = _get_session()
    ret = {}
    # get vm object
    vms = session.xenapi.VM.get_by_name_label(name)
    if len(vms) == 1:
        # read virtual block device (vdb)
        vbds = session.xenapi.VM.get_VBDs(vms[0])
        if vbds is not None:
            x = 0
            for vbd in vbds:
                vbd_record = session.xenapi.VBD.get_record(vbd)
                if vbd_record['VDI'] != 'OpaqueRef:NULL':
                    # read vdi on vdb
                    vdi_record = session.xenapi.VDI.get_record(
                        vbd_record['VDI'])
                    if 'iso' not in vdi_record['name_label']:
                        session.xenapi.VDI.destroy(vbd_record['VDI'])
                        ret['vdi-{}'.format(x)] = vdi_record['name_label']
                x += 1
    return ret
491875
def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
        
        vm = self.get_vm(block_header)
        return vm.block
606508
def get_nics(vm_):
    '''
    
    '''
    with _get_xapi_session() as xapi:
        nic = {}

        vm_rec = _get_record_by_label(xapi, 'VM', vm_)
        if vm_rec is False:
            return False
        for vif in vm_rec['VIFs']:
            vif_rec = _get_record(xapi, 'VIF', vif)
            nic[vif_rec['MAC']] = {
                'mac': vif_rec['MAC'],
                'device': vif_rec['device'],
                'mtu': vif_rec['MTU']
            }

        return nic
813521
def vb_get_manager():
    '''
    
    '''
    global _virtualboxManager
    if _virtualboxManager is None and HAS_LIBS:
        salt.utils.compat.reload(vboxapi)
        _virtualboxManager = vboxapi.VirtualBoxManager(None, None)

    return _virtualboxManager
1280380
def stop(self):
        

        self._hw_virtualization = False
        yield from self._stop_remote_console()
        yield from self._stop_ubridge()

        try:
            if (yield from self.is_running()):
                if self.acpi_shutdown:
                    # use ACPI to shutdown the VM
                    yield from self._control_vm("stop", "soft")
                else:
                    yield from self._control_vm("stop")
        finally:
            self._started = False
            self.status = "stopped"

            self._read_vmx_file()
            self._vmnets.clear()
            # remove the adapters managed by GNS3
            for adapter_number in range(0, self._adapters):
                vnet = "ethernet{}.vnet".format(adapter_number)
                if self._get_vmx_setting(vnet) or self._get_vmx_setting("ethernet{}.connectiontype".format(adapter_number)) is None:
                    if vnet in self._vmx_pairs:
                        vmnet = os.path.basename(self._vmx_pairs[vnet])
                        if not self.manager.is_managed_vmnet(vmnet):
                            continue
                    log.debug("removing adapter {}".format(adapter_number))
                    self._vmx_pairs[vnet] = "vmnet1"
                    self._vmx_pairs["ethernet{}.connectiontype".format(adapter_number)] = "custom"

            # re-enable any remaining network adapters
            for adapter_number in range(self._adapters, self._maximum_adapters):
                if self._get_vmx_setting("ethernet{}.present".format(adapter_number), "TRUE"):
                    log.debug("enabling remaining adapter {}".format(adapter_number))
                    self._vmx_pairs["ethernet{}.startconnected".format(adapter_number)] = "TRUE"
            self._write_vmx_file()

        yield from super().stop()
        log.info("VMware VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
552758
def get_vm_instances(instance_id=None):
    """"""
    return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX],
                         vnic_type=portbindings.VNIC_NORMAL,
                         instance_id=instance_id)
320619
def stop(self):
        

        self._hw_virtualization = False
        yield from self._stop_ubridge()
        yield from self._stop_remote_console()
        vm_state = yield from self._get_vm_state()
        if vm_state == "running" or vm_state == "paused" or vm_state == "stuck":
            if self.acpi_shutdown:
                # use ACPI to shutdown the VM
                result = yield from self._control_vm("acpipowerbutton")
                trial = 0
                while True:
                    vm_state = yield from self._get_vm_state()
                    if vm_state == "poweroff":
                        break
                    yield from asyncio.sleep(1)
                    trial += 1
                    if trial >= 120:
                        yield from self._control_vm("poweroff")
                        break
                self.status = "stopped"
                log.debug("ACPI shutdown result: {}".format(result))
            else:
                # power off the VM
                result = yield from self._control_vm("poweroff")
                self.status = "stopped"
                log.debug("Stop result: {}".format(result))

            log.info("VirtualBox VM '{name}' [{id}] stopped".format(name=self.name, id=self.id))
            yield from asyncio.sleep(0.5)  # give some time for VirtualBox to unlock the VM
            try:
                # deactivate the first serial port
                yield from self._modify_vm("--uart1 off")
            except VirtualBoxError as e:
                log.warn("Could not deactivate the first serial port: {}".format(e))

            for adapter_number in range(0, self._adapters):
                nio = self._ethernet_adapters[adapter_number].get_nio(0)
                if nio:
                    yield from self._modify_vm("--nictrace{} off".format(adapter_number + 1))
                    yield from self._modify_vm("--cableconnected{} off".format(adapter_number + 1))
                    yield from self._modify_vm("--nic{} null".format(adapter_number + 1))
        yield from super().stop()
1270552
def _erase_vm_info(name):
    '''
    
    '''
    try:
        # delete the machine record
        vm_ = get_vm_info(name)
        if vm_['machine']:
            key = _build_machine_uri(vm_['machine'], vm_.get('cwd', '.'))
            try:
                __utils__['sdb.sdb_delete'](key, __opts__)
            except KeyError:
                # no delete method found -- load a blank value
                __utils__['sdb.sdb_set'](key, None, __opts__)
    except Exception:
        pass

    uri = _build_sdb_uri(name)
    try:
        # delete the name record
        __utils__['sdb.sdb_delete'](uri, __opts__)
    except KeyError:
        # no delete method found -- load an empty dictionary
        __utils__['sdb.sdb_set'](uri, {}, __opts__)
    except Exception:
        pass
522752
def ext_pillar(minion_id,
               pillar,  # pylint: disable=W0613
               **kwargs):
    '''
    
    '''
    vmware_pillar = {}
    host = None
    username = None
    password = None
    property_types = []
    property_name = 'name'
    protocol = None
    port = None
    pillar_key = 'vmware'
    replace_default_attributes = False
    type_specific_pillar_attributes = {
        'VirtualMachine': [
            {
                'config':
                    [
                        'version',
                        'guestId',
                        'files',
                        'tools',
                        'flags',
                        'memoryHotAddEnabled',
                        'cpuHotAddEnabled',
                        'cpuHotRemoveEnabled',
                        'datastoreUrl',
                        'swapPlacement',
                        'bootOptions',
                        'scheduledHardwareUpgradeInfo',
                        'memoryAllocation',
                        'cpuAllocation',
                    ]
            },
            {
                'summary':
                    [
                        {
                            'runtime':
                                [
                                    {
                                        'host':
                                        [
                                            'name',
                                            {'parent': 'name'},
                                        ]
                                    },
                                    'bootTime',
                                ]
                        },
                        {
                            'guest':
                                [
                                    'toolsStatus',
                                    'toolsVersionStatus',
                                    'toolsVersionStatus2',
                                    'toolsRunningStatus',
                                ]
                        },
                        {
                            'config':
                                [
                                    'cpuReservation',
                                    'memoryReservation',
                                ]
                        },
                        {
                            'storage':
                                [
                                    'committed',
                                    'uncommitted',
                                    'unshared',
                                ]
                        },
                        {'dasVmProtection': ['dasProtected']},
                    ]
            },
            {
                'storage':
                    [
                        {
                            'perDatastoreUsage':
                                [
                                    {
                                        'datastore': 'name'
                                    },
                                    'committed',
                                    'uncommitted',
                                    'unshared',
                                ]
                        }
                    ]
            },
        ],
        'HostSystem': [
            {
                'datastore':
                    [
                        'name',
                        'overallStatus',
                        {
                            'summary':
                                [
                                    'url',
                                    'freeSpace',
                                    'maxFileSize',
                                    'maxVirtualDiskCapacity',
                                    'maxPhysicalRDMFileSize',
                                    'maxVirtualRDMFileSize',
                                    {
                                        'vmfs':
                                            [
                                                'capacity',
                                                'blockSizeMb',
                                                'maxBlocks',
                                                'majorVersion',
                                                'version',
                                                'uuid',
                                                {
                                                    'extent':
                                                        [
                                                            'diskName',
                                                            'partition',
                                                        ]
                                                },
                                                'vmfsUpgradeable',
                                                'ssd',
                                                'local',
                                            ],
                                    },
                                ],
                        },
                        {'vm': 'name'}
                    ]
            },
            {
                'vm':
                    [
                        'name',
                        'overallStatus',
                        {
                            'summary':
                                [
                                    {'runtime': 'powerState'},
                                ]
                        },
                    ]
            },
        ]
    }
    pillar_attributes = [
        {
            'summary':
                [
                    'overallStatus'
                ]
        },
        {
            'network':
                [
                    'name',
                    {'config': {'distributedVirtualSwitch': 'name'}},
                ]
        },
        {
            'datastore':
                [
                    'name',
                ]
        },
        {
            'parent':
                [
                    'name'
                ]
        },
    ]

    if 'pillar_key' in kwargs:
        pillar_key = kwargs['pillar_key']
    vmware_pillar[pillar_key] = {}

    if 'host' not in kwargs:
        log.error('VMWare external pillar configured but host is not specified in ext_pillar configuration.')
        return vmware_pillar
    else:
        host = kwargs['host']
        log.debug('vmware_pillar -- host = %s', host)

    if 'username' not in kwargs:
        log.error('VMWare external pillar requested but username is not specified in ext_pillar configuration.')
        return vmware_pillar
    else:
        username = kwargs['username']
        log.debug('vmware_pillar -- username = %s', username)

    if 'password' not in kwargs:
        log.error('VMWare external pillar requested but password is not specified in ext_pillar configuration.')
        return vmware_pillar
    else:
        password = kwargs['password']
        log.debug('vmware_pillar -- password = %s', password)

    if 'replace_default_attributes' in kwargs:
        replace_default_attributes = kwargs['replace_default_attributes']
        if replace_default_attributes:
            pillar_attributes = []
            type_specific_pillar_attributes = {}

    if 'property_types' in kwargs:
        for prop_type in kwargs['property_types']:
            if isinstance(prop_type, dict):
                property_types.append(getattr(vim, prop_type.keys()[0]))
                if isinstance(prop_type[prop_type.keys()[0]], list):
                    pillar_attributes = pillar_attributes + prop_type[prop_type.keys()[0]]
                else:
                    log.warning('A property_type dict was specified, but its value is not a list')
            else:
                property_types.append(getattr(vim, prop_type))
    else:
        property_types = [vim.VirtualMachine]
    log.debug('vmware_pillar -- property_types = %s', property_types)

    if 'property_name' in kwargs:
        property_name = kwargs['property_name']
    else:
        property_name = 'name'
    log.debug('vmware_pillar -- property_name = %s', property_name)

    if 'protocol' in kwargs:
        protocol = kwargs['protocol']
        log.debug('vmware_pillar -- protocol = %s', protocol)

    if 'port' in kwargs:
        port = kwargs['port']
        log.debug('vmware_pillar -- port = %s', port)

    virtualgrain = None
    osgrain = None
    if 'virtual' in __grains__:
        virtualgrain = __grains__['virtual'].lower()
    if 'os' in __grains__:
        osgrain = __grains__['os'].lower()

    if virtualgrain == 'vmware' or osgrain == 'vmware esxi' or osgrain == 'esxi':
        vmware_pillar[pillar_key] = {}
        try:
            _conn = salt.utils.vmware.get_service_instance(host,
                                                           username,
                                                           password,
                                                           protocol,
                                                           port)
            if _conn:
                data = None
                for prop_type in property_types:
                    data = salt.utils.vmware.get_mor_by_property(_conn,
                                                                 prop_type,
                                                                 minion_id,
                                                                 property_name=property_name)
                    if data:
                        type_name = type(data).__name__.replace('vim.', '')
                        if hasattr(data, 'availableField'):
                            vmware_pillar[pillar_key]['annotations'] = {}
                            for availableField in data.availableField:
                                for customValue in data.customValue:
                                    if availableField.key == customValue.key:
                                        vmware_pillar[pillar_key]['annotations'][availableField.name] = customValue.value
                        type_specific_pillar_attribute = []
                        if type_name in type_specific_pillar_attributes:
                            type_specific_pillar_attribute = type_specific_pillar_attributes[type_name]
                        vmware_pillar[pillar_key] = dictupdate.update(vmware_pillar[pillar_key],
                                                                      _crawl_attribute(data,
                                                                      pillar_attributes +
                                                                      type_specific_pillar_attribute))
                        break
                # explicitly disconnect from vCenter when we are done, connections linger idle otherwise
                Disconnect(_conn)
            else:
                log.error(
                    'Unable to obtain a connection with %s, please verify '
                    'your vmware ext_pillar configuration', host
                )
        except RuntimeError:
            log.error(('A runtime error occurred in the vmware_pillar, '
                       'this is likely caused by an infinite recursion in '
                       'a requested attribute.  Verify your requested attributes '
                       'and reconfigure the pillar.'))

        return vmware_pillar
    else:
        return {}
651916
def reset(name):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.reset',
                [name],
                timeout=600)
        for comp in cmd_ret:
            ret.update(comp)
        __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
1155121
def GetCpuShares(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetCpuShares(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
761930
def destroy_vm_by_uuid(self, si, vm_uuid, vm_path, logger):
        
        if vm_uuid is not None:
            vm = self.find_by_uuid(si, vm_uuid, vm_path)
            if vm:
                return self.destroy_vm(vm, logger)
        # return 'vm not found'
        # for apply the same Interface as for 'destroy_vm_by_name'
        raise ValueError('vm not found')
20185
def vmstats():
    '''
    
    '''
    def linux_vmstats():
        '''
        linux specific implementation of vmstats
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
                stats = salt.utils.stringutils.to_unicode(fp_.read())
        except IOError:
            pass
        else:
            for line in stats.splitlines():
                if not line:
                    continue
                comps = line.split()
                ret[comps[0]] = _number(comps[1])
        return ret

    def generic_vmstats():
        '''
        generic implementation of vmstats
        note: works on FreeBSD, SunOS and OpenBSD (possibly others)
        '''
        ret = {}
        for line in __salt__['cmd.run']('vmstat -s').splitlines():
            comps = line.split()
            if comps[0].isdigit():
                ret[' '.join(comps[1:])] = _number(comps[0].strip())
        return ret

    # dict that returns a function that does the right thing per platform
    get_version = {
        'Linux': linux_vmstats,
        'FreeBSD': generic_vmstats,
        'OpenBSD': generic_vmstats,
        'SunOS': generic_vmstats,
        'AIX': generic_vmstats,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
442549
def map_vnics(vm):
        
        return {device.deviceInfo.label: device
                for device in vm.config.hardware.device
                if isinstance(device, vim.vm.device.VirtualEthernetCard)}
439777
def get_vm_obj(self):
        
        uuid = VcenterInterfaces.get_vcenter_vm_uuid_by_name(self.host, self.user, self.password, self.name)
        # connect to vc

        # Getting VM data
        vm_obj = self.vcenter_conn.content.searchIndex.FindByUuid(None, uuid, True, True)
        # VM does exist
        if not vm_obj:
            print 'VM {} does not exist'.format(uuid)
            sys.exit(1)

        # VM must be powered off to export
        if not vm_obj.runtime.powerState == \
                vim.VirtualMachine.PowerState.poweredOff:
            print 'VM {} must be powered off'.format(vm_obj.name)
            sys.exit(1)

        return vm_obj
1010690
def virtual_machines_list_all(**kwargs):
    '''
    

    '''
    result = {}
    compconn = __utils__['azurearm.get_client']('compute', **kwargs)
    try:
        vms = __utils__['azurearm.paged_object_to_list'](
            compconn.virtual_machines.list_all()
        )
        for vm in vms:  # pylint: disable=invalid-name
            result[vm['name']] = vm
    except CloudError as exc:
        __utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
        result = {'error': str(exc)}

    return result
1124011
def vm_registered(vm_name, datacenter, placement, vm_file, power_on=False):
    '''
    
    '''
    result = {'name': vm_name,
              'result': None,
              'changes': {},
              'comment': ''}

    vmx_path = '{0}{1}'.format(vm_file.folderPath, vm_file.file[0].path)
    log.trace('Registering virtual machine with vmx file: %s', vmx_path)
    service_instance = __salt__['vsphere.get_service_instance_via_proxy']()
    try:
        __salt__['vsphere.register_vm'](vm_name, datacenter,
                                        placement, vmx_path,
                                        service_instance=service_instance)
    except salt.exceptions.VMwareMultipleObjectsError as exc:
        log.error('Error: %s', exc)
        if service_instance:
            __salt__['vsphere.disconnect'](service_instance)
        result.update({'result': False,
                       'comment': six.text_type(exc)})
        return result
    except salt.exceptions.VMwareVmRegisterError as exc:
        log.error('Error: %s', exc)
        if service_instance:
            __salt__['vsphere.disconnect'](service_instance)
        result.update({'result': False,
                       'comment': six.text_type(exc)})
        return result

    if power_on:
        try:
            __salt__['vsphere.power_on_vm'](vm_name, datacenter,
                                            service_instance=service_instance)
        except salt.exceptions.VMwarePowerOnError as exc:
            log.error('Error: %s', exc)
            if service_instance:
                __salt__['vsphere.disconnect'](service_instance)
            result.update({
                'result': False,
                'comment': six.text_type(exc)})
            return result
    __salt__['vsphere.disconnect'](service_instance)
    result.update({'result': True,
                   'changes': {'name': vm_name, 'power_on': power_on},
                   'comment': 'Virtual machine '
                              '{0} registered successfully'.format(vm_name)})

    return result