Gets VMware VM list.
177348
def list_vms(self):
        

        # check for the right VMware version
        yield from self.check_vmware_version()
        vmware_vms = []
        inventory_path = self.get_vmware_inventory_path()
        if os.path.exists(inventory_path) and self.host_type != "player":
            # inventory may exist for VMware player if VMware workstation has been previously installed
            vmware_vms = self._get_vms_from_inventory(inventory_path)
        if not vmware_vms:
            # backup methods when no VMware inventory file exists or for VMware player which has no inventory file
            vmware_preferences_path = self.get_vmware_preferences_path()
            pairs = {}
            if os.path.exists(vmware_preferences_path):
                # the default vm path may be present in VMware preferences file.
                try:
                    pairs = self.parse_vmware_file(vmware_preferences_path)
                except OSError as e:
                    log.warning('Could not read VMware preferences file "{}": {}'.format(vmware_preferences_path, e))
                if "prefvmx.defaultvmpath" in pairs:
                    default_vm_path = pairs["prefvmx.defaultvmpath"]
                    if not os.path.isdir(default_vm_path):
                        raise VMwareError('Could not find or access the default VM directory: "{default_vm_path}". Please change "prefvmx.defaultvmpath={default_vm_path}" in "{vmware_preferences_path}"'.format(default_vm_path=default_vm_path,
                                                                                                                                                                                                                  vmware_preferences_path=vmware_preferences_path))
                    vmware_vms = self._get_vms_from_directory(default_vm_path)

            if not vmware_vms:
                # the default vm path is not in the VMware preferences file or that directory is empty
                # let's search the default locations for VMs
                for default_vm_path in self.get_vmware_default_vm_paths():
                    if os.path.isdir(default_vm_path):
                        vmware_vms.extend(self._get_vms_from_directory(default_vm_path))

            if not vmware_vms:
                log.warning("Could not find any VMware VM in default locations")

            # look for VMX paths in the preferences file in case not all VMs are in a default directory
            for key, value in pairs.items():
                m = re.match(r'pref.mruVM(\d+)\.filename', key)
                if m:
                    display_name = "pref.mruVM{}.displayName".format(m.group(1))
                    if display_name in pairs:
                        found = False
                        for vmware_vm in vmware_vms:
                            if vmware_vm["vmname"] == display_name:
                                found = True
                        if found is False:
                            vmware_vms.append({"vmname": pairs[display_name], "vmx_path": value})
        return vmware_vms
1038795
def list_hosts():
    ''''''
    with Session() as session:
        try:
            resp = session.VFolder.list_hosts()
            print(f"Default vfolder host: {resp['default']}")
            print(f"Usable hosts: {', '.join(resp['allowed'])}")
        except Exception as e:
            print_error(e)
            sys.exit(1)
33563
def _get_vms_from_inventory(self, inventory_path):
        

        vm_entries = {}
        vmware_vms = []
        log.info('Searching for VMware VMs in inventory file "{}"'.format(inventory_path))
        try:
            pairs = self.parse_vmware_file(inventory_path)
            for key, value in pairs.items():
                if key.startswith("vmlist"):
                    try:
                        vm_entry, variable_name = key.split('.', 1)
                    except ValueError:
                        continue
                    if vm_entry not in vm_entries:
                        vm_entries[vm_entry] = {}
                    vm_entries[vm_entry][variable_name.strip()] = value
        except OSError as e:
            log.warning("Could not read VMware inventory file {}: {}".format(inventory_path, e))

        for vm_settings in vm_entries.values():
            if "displayname" in vm_settings and "config" in vm_settings:
                if os.path.exists(vm_settings["config"]):
                    log.debug('Found VM named "{}" with VMX file "{}"'.format(vm_settings["displayname"], vm_settings["config"]))
                    vmware_vms.append({"vmname": vm_settings["displayname"], "vmx_path": vm_settings["config"]})
        return vmware_vms
589563
def list_virtual(hostname, username, password, name):
    '''
    
    '''

    ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}

    if __opts__['test']:
        return _test_output(ret, 'list', params={
            'hostname': hostname,
            'username': username,
            'password': password,
            'name': name
        }
        )

    response = __salt__['bigip.list_virtual'](hostname, username, password, name)
    return _load_result(response, ret)
364319
def _get_vm_info(self):
        

        vm_info = {}
        results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in results:
            try:
                name, value = info.split('=', 1)
            except ValueError:
                continue
            vm_info[name.strip('"')] = value.strip('"')
        return vm_info
1032178
def _get_domain(conn, *vms, **kwargs):
    '''
    
    '''
    ret = list()
    lookup_vms = list()

    all_vms = []
    if kwargs.get('active', True):
        for id_ in conn.listDomainsID():
            all_vms.append(conn.lookupByID(id_).name())

    if kwargs.get('inactive', True):
        for id_ in conn.listDefinedDomains():
            all_vms.append(id_)

    if not all_vms:
        raise CommandExecutionError('No virtual machines found.')

    if vms:
        for name in vms:
            if name not in all_vms:
                raise CommandExecutionError('The VM "{name}" is not present'.format(name=name))
            else:
                lookup_vms.append(name)
    else:
        lookup_vms = list(all_vms)

    for name in lookup_vms:
        ret.append(conn.lookupByName(name))

    return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret
442549
def map_vnics(vm):
        
        return {device.deviceInfo.label: device
                for device in vm.config.hardware.device
                if isinstance(device, vim.vm.device.VirtualEthernetCard)}
826590
def get_view_menus(self, permission_name):
        """"""
        vm = set()
        for perm_name, vm_name in self.get_all_permissions():
            if perm_name == permission_name:
                vm.add(vm_name)
        return vm
152916
def getconnections(self, vhost = None):
        ""
        if vhost is None:
            return list(self.managed_connections)
        else:
            return [c for c in self.managed_connections if c.protocol.vhost == vhost]
640892
def list_vapps(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_vapps function must be called with '
            '-f or --function.'
        )

    return {'vApps': salt.utils.vmware.list_vapps(_get_si())}
317321
def list_folders(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_folders function must be called with '
            '-f or --function.'
        )

    return {'Folders': salt.utils.vmware.list_folders(_get_si())}
416515
def list_nodes_min(kwargs=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes_min function must be called '
            'with -f or --function.'
        )

    ret = {}
    vm_properties = ["name"]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        ret[vm['name']] = {'state': 'Running', 'id': vm['name']}

    return ret
1036596
def find_vmrun(self):
        

        # look for vmrun
        vmrun_path = self.config.get_section_config("VMware").get("vmrun_path")
        if not vmrun_path:
            if sys.platform.startswith("win"):
                vmrun_path = shutil.which("vmrun")
                if vmrun_path is None:
                    # look for vmrun.exe using the VMware Workstation directory listed in the registry
                    vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
                    if vmrun_path is None:
                        # look for vmrun.exe using the VIX directory listed in the registry
                        vmrun_path = self._find_vmrun_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware VIX")
            elif sys.platform.startswith("darwin"):
                vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
            else:
                vmrun_path = "vmrun"

        if vmrun_path and not os.path.isabs(vmrun_path):
            vmrun_path = shutil.which(vmrun_path)

        if not vmrun_path:
            raise VMwareError("Could not find VMware vmrun, please make sure it is installed")
        if not os.path.isfile(vmrun_path):
            raise VMwareError("vmrun {} is not accessible".format(vmrun_path))
        if not os.access(vmrun_path, os.X_OK):
            raise VMwareError("vmrun is not executable")
        if os.path.basename(vmrun_path).lower() not in ["vmrun", "vmrun.exe"]:
            raise VMwareError("Invalid vmrun executable name {}".format(os.path.basename(vmrun_path)))

        self._vmrun_path = vmrun_path
        return vmrun_path
183363
def vms
      logger.debug "get all VMs in all datacenters: begin"
      result = dcs.inject([]) do |r, dc|
        r + serviceContent.viewManager.CreateContainerView(
          container: dc.vmFolder,
          type: ['VirtualMachine'],
          recursive: true
        ).view
      end
      logger.debug "get all VMs in all datacenters: end"
      result
    end
885968
def _get_hdds(vm_):
    '''
    
    '''
    _hdds = config.get_cloud_config_value(
        'hdds', vm_, __opts__, default=None,
        search_global=False
    )

    hdds = []

    for hdd in _hdds:
        hdds.append(
            Hdd(
                size=hdd['size'],
                is_main=hdd['is_main']
            )
        )

    return hdds
1179510
def vif_list(name, call=None, kwargs=None):
    '''
    

    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'This function must be called with -a, --action argument.'
        )
    if name is None:
        return 'A name kwarg is rquired'
    ret = {}
    data = {}
    session = _get_session()
    vm = _get_vm(name)
    vifs = session.xenapi.VM.get_VIFs(vm)
    if vifs is not None:
        x = 0
        for vif in vifs:
            vif_record = session.xenapi.VIF.get_record(vif)
            data['vif-{}'.format(x)] = vif_record
            x += 1
    ret[name] = data
    return ret
353303
def list_datacenters(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_datacenters function must be called with '
            '-f or --function.'
        )

    return {'Datacenters': salt.utils.vmware.list_datacenters(_get_si())}