Search for vm in vcenter, return the object if found
        :return:
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
1070976
def vcenter_connect(self):
        
        try:
            si = SmartConnect(
                host=self.host,
                user=self.user,
                pwd=self.password,
                port=self.port)
            # disconnect vc
            atexit.register(Disconnect, si)
        except vim.fault.InvalidLogin as e:
            print "Unable to connect to vcenter because of: {}".format(e.msg)
            sys.exit(5)
        return si
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
789111
def load_vm_uuid_by_name(self, si, vcenter_data_model, vm_name):
        
        path = VMLocation.combine([vcenter_data_model.default_datacenter, vm_name])
        paths = path.split('/')
        name = paths[len(paths) - 1]
        path = VMLocation.combine(paths[:len(paths) - 1])
        vm = self.pv_service.find_vm_by_name(si, path, name)
        if not vm:
            raise ValueError('Could not find the vm in the given path: {0}/{1}'.format(path, name))

        if isinstance(vm, vim.VirtualMachine):
            return vm.config.uuid

        raise ValueError('The given object is not a vm: {0}/{1}'.format(path, name))
219485
def _get_proxy_target(service_instance):
    '''
    
    '''
    proxy_type = get_proxy_type()
    if not salt.utils.vmware.is_connection_to_a_vcenter(service_instance):
        raise CommandExecutionError('\'_get_proxy_target\' not supported '
                                    'when connected via the ESXi host')
    reference = None
    if proxy_type == 'esxcluster':
        host, username, password, protocol, port, mechanism, principal, \
            domain, datacenter, cluster = _get_esxcluster_proxy_details()

        dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
        reference = salt.utils.vmware.get_cluster(dc_ref, cluster)
    elif proxy_type == 'esxdatacenter':
        # esxdatacenter proxy
        host, username, password, protocol, port, mechanism, principal, \
            domain, datacenter = _get_esxdatacenter_proxy_details()

        reference = salt.utils.vmware.get_datacenter(service_instance,
                                                     datacenter)
    elif proxy_type == 'vcenter':
        # vcenter proxy - the target is the root folder
        reference = salt.utils.vmware.get_root_folder(service_instance)
    elif proxy_type == 'esxi':
        # esxi proxy
        details = __proxy__['esxi.get_details']()
        if 'vcenter' not in details:
            raise InvalidEntityError('Proxies connected directly to ESXi '
                                     'hosts are not supported')
        references = salt.utils.vmware.get_hosts(
            service_instance, host_names=details['esxi_host'])
        if not references:
            raise VMwareObjectRetrievalError(
                'ESXi host \'{0}\' was not found'.format(details['esxi_host']))
        reference = references[0]
    log.trace('reference = %s', reference)
    return reference
1308393
def get_inventory(self, context):
        
        vcenter_vm_name = context.resource.attributes['vCenter VM']
        vcenter_vm_name = vcenter_vm_name.replace('\\', '/')
        vcenter_name = context.resource.attributes['vCenter Name']

        self.logger.info('start autoloading vm_path: {0} on vcenter: {1}'.format(vcenter_vm_name, vcenter_name))

        with CloudShellSessionContext(context) as cloudshell_session:
            session = cloudshell_session

        vcenter_api_res = session.GetResourceDetails(vcenter_name)
        vcenter_resource = self.model_parser.convert_to_vcenter_model(vcenter_api_res)

        si = None

        try:
            self.logger.info('connecting to vcenter ({0})'.format(vcenter_api_res.Address))
            si = self._get_connection_to_vcenter(self.pv_service, session, vcenter_resource, vcenter_api_res.Address)

            self.logger.info('loading vm uuid')
            vm_loader = VMLoader(self.pv_service)
            uuid = vm_loader.load_vm_uuid_by_name(si, vcenter_resource, vcenter_vm_name)
            self.logger.info('vm uuid: {0}'.format(uuid))
            self.logger.info('loading the ip of the vm')
            ip = self._try_get_ip(self.pv_service, si, uuid, vcenter_resource)
            if ip:
                session.UpdateResourceAddress(context.resource.name, ip)

        except Exception:
            self.logger.exception("Get inventory command failed")
            raise
        finally:
            if si:
                self.pv_service.disconnect(si)

        return self._get_auto_load_response(uuid, vcenter_name, context.resource)
1084764
def show_instance(vm_name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )
    conn = get_conn()
    node = _expand_node(conn.ex_get_node(vm_name))
    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
    return node
205218
def get_conn():
    '''
    
    '''
    vm_ = get_configured_provider()
    driver = get_driver(Provider.DIMENSIONDATA)

    region = config.get_cloud_config_value(
         'region', vm_, __opts__
    )

    user_id = config.get_cloud_config_value(
        'user_id', vm_, __opts__
    )
    key = config.get_cloud_config_value(
        'key', vm_, __opts__
    )

    if key is not None:
        log.debug('DimensionData authenticating using password')

    return driver(
        user_id,
        key,
        region=region
    )
468941
def find_volume(self, name):
        
        try:
            return Volume(self.virsp.storageVolLookupByName(name), self)
        except libvirtError:
            return None
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
1127092
def find_available_vc_vers(self):
        
        ms = self.ri.microsoft
        vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs)
        vc_vers = []
        for hkey in self.ri.HKEYS:
            for key in vckeys:
                try:
                    bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)
                except (OSError, IOError):
                    continue
                subkeys, values, _ = winreg.QueryInfoKey(bkey)
                for i in range(values):
                    try:
                        ver = float(winreg.EnumValue(bkey, i)[0])
                        if ver not in vc_vers:
                            vc_vers.append(ver)
                    except ValueError:
                        pass
                for i in range(subkeys):
                    try:
                        ver = float(winreg.EnumKey(bkey, i))
                        if ver not in vc_vers:
                            vc_vers.append(ver)
                    except ValueError:
                        pass
        return sorted(vc_vers)
659231
async def get_vm(self, vm_id):
        '''
        
        '''
        result = await self.nova.servers.get(vm_id)
        return self._map_vm_structure(result["server"])
964379
def _get_vm(name=None, session=None):
    '''
    
    '''
    if session is None:
        session = _get_session()
    vms = session.xenapi.VM.get_by_name_label(name)
    if len(vms) == 1:
        return vms[0]
    return None
363507
def get_vmconfig(vmid, node=None, node_type='openvz'):
    '''
    
    '''
    if node is None:
        # We need to figure out which node this VM is on.
        for host_name, host_details in six.iteritems(avail_locations()):
            for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)):
                if item['vmid'] == vmid:
                    node = host_name

    # If we reached this point, we have all the information we need
    data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid))

    return data
298930
def get_network_adapter_object_type(adapter_object):
    '''
    
    '''
    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet2):
        return 'vmxnet2'
    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet3):
        return 'vmxnet3'
    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet):
        return 'vmxnet'
    if isinstance(adapter_object, vim.vm.device.VirtualE1000e):
        return 'e1000e'
    if isinstance(adapter_object, vim.vm.device.VirtualE1000):
        return 'e1000'

    raise ValueError('An unknown network adapter object type.')
399892
def _action(action='get', search=None, one=True, force=False):
    '''
    
    '''
    vms = {}
    matched_vms = []
    client = salt.client.get_local_client(__opts__['conf_file'])

    ## lookup vms
    try:
        vmadm_args = {}
        vmadm_args['order'] = 'uuid,alias,hostname,state'
        if '=' in search:
            vmadm_args['search'] = search
        for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
                                  'vmadm.list', kwarg=vmadm_args,
                                  tgt_type='compound'):
            if not cn:
                continue
            node = next(six.iterkeys(cn))
            if not isinstance(cn[node], dict) or \
                    'ret' not in cn[node] or \
                    not isinstance(cn[node]['ret'], dict):
                continue
            for vm in cn[node]['ret']:
                vmcfg = cn[node]['ret'][vm]
                vmcfg['node'] = node
                vms[vm] = vmcfg
    except SaltClientError as client_error:
        pass

    ## check if we have vms
    if not vms:
        return {'Error': 'No vms found.'}

    ## simple search
    if '=' not in search:
        loop_pass = 0
        while loop_pass < 3:
            ## each pass will try a different field
            if loop_pass == 0:
                field = 'uuid'
            elif loop_pass == 1:
                field = 'hostname'
            else:
                field = 'alias'

            ## loop vms and try to match
            for vm in vms:
                if field == 'uuid' and vm == search:
                    matched_vms.append(vm)
                    break  # exit for on uuid match (max = 1)
                elif field in vms[vm] and vms[vm][field] == search:
                    matched_vms.append(vm)

            ## exit on match(es) or try again
            if matched_vms:
                break
            else:
                loop_pass += 1
    else:
        for vm in vms:
            matched_vms.append(vm)

    ## check if we have vms
    if not matched_vms:
        return {'Error': 'No vms matched.'}

    ## multiple allowed?
    if one and len(matched_vms) > 1:
        return {
            'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),
            'Matches': matched_vms
        }

    ## perform action
    ret = {}
    if action in ['start', 'stop', 'reboot', 'get']:
        for vm in matched_vms:
            vmadm_args = {
                'key': 'uuid',
                'vm': vm
            }
            try:
                for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):
                    if not vmadm_res:
                        continue
                    if vms[vm]['node'] in vmadm_res:
                        ret[vm] = vmadm_res[vms[vm]['node']]['ret']
            except SaltClientError as client_error:
                ret[vm] = False
    elif action in ['is_running']:
        ret = True
        for vm in matched_vms:
            if vms[vm]['state'] != 'running':
                ret = False
                break
    return ret
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