Determines if a particular virtual machine exists in the output

   * vm_name: The name of the virtual machine to look for
762065
def exists?(vm_name = nil)
      return (vm_names.count > 0) if vm_name.nil?
      vm_names.include? vm_name.to_sym
    end
1343651
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with '
            '-a or --action.'
        )

    vm_properties = [
        "config.hardware.device",
        "summary.storage.committed",
        "summary.storage.uncommitted",
        "summary.storage.unshared",
        "layoutEx.file",
        "config.guestFullName",
        "config.guestId",
        "guest.net",
        "config.hardware.memoryMB",
        "name",
        "config.hardware.numCPU",
        "config.files.vmPathName",
        "summary.runtime.powerState",
        "guest.toolsStatus"
    ]

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

    for vm in vm_list:
        if vm['name'] == name:
            return _format_instance_info(vm)

    return {}
477014
def vm_info(name, quiet=False):
    '''
    
    '''
    data = query(quiet=True)
    return _find_vm(name, data, quiet)
1262195
def set_vmname(self, vmname):
        

        if vmname == self._vmname:
            return

        if self.linked_clone:
            if self.status == "started":
                raise VirtualBoxError("You can't change the name of running VM {}".format(self._name))
            # We can't rename a VM to name that already exists
            vms = yield from self.manager.list_vms(allow_clone=True)
            if vmname in [vm["vmname"] for vm in vms]:
                raise VirtualBoxError("You can't change the name to {} it's already use in VirtualBox".format(vmname))
            yield from self._modify_vm('--name "{}"'.format(vmname))

        log.info("VirtualBox VM '{name}' [{id}] has set the VM name to '{vmname}'".format(name=self.name, id=self.id, vmname=vmname))
        self._vmname = vmname
183776
def pv_absent(name):
    '''
    
    '''
    ret = {'changes': {},
           'comment': '',
           'name': name,
           'result': True}

    if not __salt__['lvm.pvdisplay'](name, quiet=True):
        ret['comment'] = 'Physical Volume {0} does not exist'.format(name)
    elif __opts__['test']:
        ret['comment'] = 'Physical Volume {0} is set to be removed'.format(name)
        ret['result'] = None
        return ret
    else:
        changes = __salt__['lvm.pvremove'](name)

        if __salt__['lvm.pvdisplay'](name, quiet=True):
            ret['comment'] = 'Failed to remove Physical Volume {0}'.format(name)
            ret['result'] = False
        else:
            ret['comment'] = 'Removed Physical Volume {0}'.format(name)
            ret['changes']['removed'] = changes
    return ret
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
688582
def vm_updated(name, vm_name, cpu, memory, image, version, interfaces,
               disks, scsi_devices, serial_ports, datacenter, datastore,
               cd_dvd_drives=None, sata_controllers=None,
               advanced_configs=None, power_on=False):
    '''
    
    '''
    result = {'name': name,
              'result': None,
              'changes': {},
              'comment': ''}

    service_instance = __salt__['vsphere.get_service_instance_via_proxy']()
    current_config = __salt__['vsphere.get_vm_config'](
        vm_name,
        datacenter=datacenter,
        objects=False,
        service_instance=service_instance)

    diffs = __salt__['vsphere.compare_vm_configs'](
        {'name': vm_name,
         'cpu': cpu,
         'memory': memory,
         'image': image,
         'version': version,
         'interfaces': interfaces,
         'disks': disks,
         'scsi_devices': scsi_devices,
         'serial_ports': serial_ports,
         'datacenter': datacenter,
         'datastore': datastore,
         'cd_drives': cd_dvd_drives,
         'sata_controllers': sata_controllers,
         'advanced_configs': advanced_configs},
        current_config)
    if not diffs:
        result.update({
            'result': True,
            'changes': {},
            'comment': 'Virtual machine {0} is already up to date'.format(vm_name)})
        return result

    if __opts__['test']:
        comment = 'State vm_updated will update virtual machine \'{0}\' ' \
                  'in datacenter \'{1}\':\n{2}'.format(vm_name,
                                                       datacenter,
                  '\n'.join([':\n'.join([key, difference.changes_str])
                      for key, difference in six.iteritems(diffs)]))
        result.update({'result': None,
                       'comment': comment})
        __salt__['vsphere.disconnect'](service_instance)
        return result

    try:
        changes = __salt__['vsphere.update_vm'](vm_name, cpu, memory, image,
                                                version, interfaces, disks,
                                                scsi_devices, serial_ports,
                                                datacenter, datastore,
                                                cd_dvd_drives=cd_dvd_drives,
                                                sata_controllers=sata_controllers,
                                                advanced_configs=advanced_configs,
                                                service_instance=service_instance)
    except salt.exceptions.CommandExecutionError 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)
        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
        changes.update({'power_on': True})

    __salt__['vsphere.disconnect'](service_instance)

    result = {'name': name,
              'result': True,
              'changes': changes,
              'comment': 'Virtual machine '
                         '{0} was updated successfully'.format(vm_name)}

    return result
373788
def get_vm_failfast(self, name, verbose=False, vm_term='VM', path=""):
        
        if verbose:
            print("Finding VirtualMachine named %s..." % name)
        if path:
            vm = self.get_vm(name, path=path)
        else:
            vm = self.get_vm(name)
        if vm is None:
            print("Error: %s '%s' does not exist" % (vm_term, name))
            sys.exit(1)

        if verbose:
            print("Found VirtualMachine: %s Name: %s" % (vm, vm.name))

        return vm
681359
def list(self, engine):
        
        engine = self._get_engine(engine)
        vms = []
        try:
            for vm in (yield from engine.list()):
                vms.append({"vmname": vm["vmname"]})
        except GNS3VMError as e:
            # We raise error only if user activated the GNS3 VM
            # otherwise you have noise when VMware is not installed
            if self.enable:
                raise e
        return vms
7129
def entry_exists_on_disk(self, name):
        
        try:
            d = self.on_disk_entries
        except AttributeError:
            d = {}
            try:
                entries = os.listdir(self._abspath)
            except OSError:
                pass
            else:
                for entry in map(_my_normcase, entries):
                    d[entry] = True
            self.on_disk_entries = d
        if sys.platform == 'win32' or sys.platform == 'cygwin':
            name = _my_normcase(name)
            result = d.get(name)
            if result is None:
                # Belt-and-suspenders for Windows:  check directly for
                # 8.3 file names that don't show up in os.listdir().
                result = os.path.exists(self._abspath + OS_SEP + name)
                d[name] = result
            return result
        else:
            return name in d
517947
def check_exists(name, path):
    '''
    
    '''
    cmd = [_get_cmd(), '--display', name]
    out = __salt__['cmd.run_all'](cmd, python_shell=False)

    if out['retcode'] > 0 and out['stderr'] != '':
        return False

    return any((line.startswith(path) for line in out['stdout'].splitlines()))
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
1083468
def _get_vm_state(self):
        

        results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in results:
            if '=' in info:
                name, value = info.split('=', 1)
                if name == "VMState":
                    return value.strip('"')
        raise VirtualBoxError("Could not get VM state for {}".format(self._vmname))
470245
def state(vm_name)
      unless states.include? vm_name.to_sym
        raise Derelict::VirtualMachine::NotFound.new vm_name
      end

      states[vm_name.to_sym]
    end
601563
def exists(self, task_name):
        

        try:
            return os.path.exists(self._get_task_dir(task_name))

        except OSError:
            return False
1104777
def _get_server(vm_):
    '''
    
    '''
    description = config.get_cloud_config_value(
        'description', vm_, __opts__, default=None,
        search_global=False
    )

    ssh_key = load_public_key(vm_)

    server_type = config.get_cloud_config_value(
        'server_type', vm_, __opts__, default='cloud',
        search_global=False
    )
    vcore = None
    cores_per_processor = None
    ram = None
    fixed_instance_size_id = None
    baremetal_model_id = None

    if 'fixed_instance_size' in vm_:
        fixed_instance_size = get_size(vm_)
        fixed_instance_size_id = fixed_instance_size['id']
    elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
        vcore = config.get_cloud_config_value(
            'vcore', vm_, __opts__, default=None,
            search_global=False
        )
        cores_per_processor = config.get_cloud_config_value(
            'cores_per_processor', vm_, __opts__, default=None,
            search_global=False
        )
        ram = config.get_cloud_config_value(
            'ram', vm_, __opts__, default=None,
            search_global=False
        )
    elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
        baremetal_model_id = config.get_cloud_config_value(
            'baremetal_model_id', vm_, __opts__, default=None,
            search_global=False
        )
    else:
        raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
                                   "'cores_per_processor', 'ram', and 'hdds' "
                                   "must be provided for 'cloud' server. "
                                   "For 'baremetal' server, 'baremetal_model_id'"
                                   "must be provided.")

    appliance_id = config.get_cloud_config_value(
        'appliance_id', vm_, __opts__, default=None,
        search_global=False
    )

    password = config.get_cloud_config_value(
        'password', vm_, __opts__, default=None,
        search_global=False
    )

    firewall_policy_id = config.get_cloud_config_value(
        'firewall_policy_id', vm_, __opts__, default=None,
        search_global=False
    )

    ip_id = config.get_cloud_config_value(
        'ip_id', vm_, __opts__, default=None,
        search_global=False
    )

    load_balancer_id = config.get_cloud_config_value(
        'load_balancer_id', vm_, __opts__, default=None,
        search_global=False
    )

    monitoring_policy_id = config.get_cloud_config_value(
        'monitoring_policy_id', vm_, __opts__, default=None,
        search_global=False
    )

    datacenter_id = config.get_cloud_config_value(
        'datacenter_id', vm_, __opts__, default=None,
        search_global=False
    )

    private_network_id = config.get_cloud_config_value(
        'private_network_id', vm_, __opts__, default=None,
        search_global=False
    )

    power_on = config.get_cloud_config_value(
        'power_on', vm_, __opts__, default=True,
        search_global=False
    )

    public_key = config.get_cloud_config_value(
        'public_key_ids', vm_, __opts__, default=None,
        search_global=False
    )

    # Contruct server object
    return Server(
        name=vm_['name'],
        description=description,
        fixed_instance_size_id=fixed_instance_size_id,
        vcore=vcore,
        cores_per_processor=cores_per_processor,
        ram=ram,
        appliance_id=appliance_id,
        password=password,
        power_on=power_on,
        firewall_policy_id=firewall_policy_id,
        ip_id=ip_id,
        load_balancer_id=load_balancer_id,
        monitoring_policy_id=monitoring_policy_id,
        datacenter_id=datacenter_id,
        rsa_key=ssh_key,
        private_network_id=private_network_id,
        public_key=public_key,
        server_type=server_type,
        baremetal_model_id=baremetal_model_id
    )
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