returns number of virtual cpus of VM
760562
def vcpu
      cpus = entity_xml
              .hardware_section
              .cpu
              .get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY])

      fail CloudError,
           "Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil?
      cpus.to_i
    end
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
628123
def get_size(conn, vm_):
    '''
    
    '''
    sizes = conn.list_sizes()
    vm_size = config.get_cloud_config_value('size', vm_, __opts__)
    if not vm_size:
        return sizes[0]

    for size in sizes:
        if vm_size and str(vm_size) in (str(size.id), str(size.name)):  # pylint: disable=blacklisted-function
            return size
    raise SaltCloudNotFound(
        'The specified size, \'{0}\', could not be found.'.format(vm_size)
    )
1069718
def _linux_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    cpuinfo = '/proc/cpuinfo'
    # Parse over the cpuinfo file
    if os.path.isfile(cpuinfo):
        with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
            grains['num_cpus'] = 0
            for line in _fp:
                comps = line.split(':')
                if not len(comps) > 1:
                    continue
                key = comps[0].strip()
                val = comps[1].strip()
                if key == 'processor':
                    grains['num_cpus'] += 1
                elif key == 'model name':
                    grains['cpu_model'] = val
                elif key == 'flags':
                    grains['cpu_flags'] = val.split()
                elif key == 'Features':
                    grains['cpu_flags'] = val.split()
                # ARM support - /proc/cpuinfo
                #
                # Processor       : ARMv6-compatible processor rev 7 (v6l)
                # BogoMIPS        : 697.95
                # Features        : swp half thumb fastmult vfp edsp java tls
                # CPU implementer : 0x41
                # CPU architecture: 7
                # CPU variant     : 0x0
                # CPU part        : 0xb76
                # CPU revision    : 7
                #
                # Hardware        : BCM2708
                # Revision        : 0002
                # Serial          : 00000000
                elif key == 'Processor':
                    grains['cpu_model'] = val.split('-')[0]
                    grains['num_cpus'] = 1
    if 'num_cpus' not in grains:
        grains['num_cpus'] = 0
    if 'cpu_model' not in grains:
        grains['cpu_model'] = 'Unknown'
    if 'cpu_flags' not in grains:
        grains['cpu_flags'] = []
    return grains
659231
async def get_vm(self, vm_id):
        '''
        
        '''
        result = await self.nova.servers.get(vm_id)
        return self._map_vm_structure(result["server"])
997644
def get_number_of_desktops(self):
        
        ndesktops = ctypes.c_long(0)
        _libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops))
        return ndesktops.value
773293
def GetMemShares(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetMemShares(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
1307822
private static String getPID() {
        String vmName = ManagementFactory.getRuntimeMXBean().getName();
        return vmName.substring(0, vmName.indexOf("@"));
    }
283358
def get_num_processes():
    """"""
    cpu_count = multiprocessing.cpu_count()

    if config.NUMBER_OF_CORES == 0:
        raise ValueError(
            'Invalid NUMBER_OF_CORES; value may not be 0.')

    if config.NUMBER_OF_CORES > cpu_count:
        log.info('Requesting %s cores; only %s available',
                 config.NUMBER_OF_CORES, cpu_count)
        return cpu_count

    if config.NUMBER_OF_CORES < 0:
        num = cpu_count + config.NUMBER_OF_CORES + 1
        if num <= 0:
            raise ValueError(
                'Invalid NUMBER_OF_CORES; negative value is too negative: '
                'requesting {} cores, {} available.'.format(num, cpu_count))

        return num

    return config.NUMBER_OF_CORES
1284707
def cpustats():
    '''
    
    '''
    def linux_cpustats():
        '''
        linux specific implementation of cpustats
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/stat', '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()
                if comps[0] == 'cpu':
                    ret[comps[0]] = {'idle': _number(comps[4]),
                                     'iowait': _number(comps[5]),
                                     'irq': _number(comps[6]),
                                     'nice': _number(comps[2]),
                                     'softirq': _number(comps[7]),
                                     'steal': _number(comps[8]),
                                     'system': _number(comps[3]),
                                     'user': _number(comps[1])}
                elif comps[0] == 'intr':
                    ret[comps[0]] = {'total': _number(comps[1]),
                                     'irqs': [_number(x) for x in comps[2:]]}
                elif comps[0] == 'softirq':
                    ret[comps[0]] = {'total': _number(comps[1]),
                                     'softirqs': [_number(x) for x in comps[2:]]}
                else:
                    ret[comps[0]] = _number(comps[1])
        return ret

    def freebsd_cpustats():
        '''
        freebsd specific implementation of cpustats
        '''
        vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
        vm0 = vmstat[0].split()
        cpu0loc = vm0.index('cpu0')
        vm1 = vmstat[1].split()
        usloc = vm1.index('us')
        vm2 = vmstat[2].split()
        cpuctr = 0
        ret = {}
        for cpu in vm0[cpu0loc:]:
            ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
                        'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
                        'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
            cpuctr += 1
        return ret

    def sunos_cpustats():
        '''
        sunos specific implementation of cpustats
        '''
        mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
        fields = mpstat[0].split()
        ret = {}
        for cpu in mpstat:
            if cpu.startswith('CPU'):
                continue
            cpu = cpu.split()
            ret[_number(cpu[0])] = {}
            for i in range(1, len(fields)-1):
                ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
        return ret

    def aix_cpustats():
        '''
        AIX specific implementation of cpustats
        '''
        ret = {}
        ret['mpstat'] = []
        procn = None
        fields = []
        for line in __salt__['cmd.run']('mpstat -a').splitlines():
            if not line:
                continue
            procn = len(ret['mpstat'])
            if line.startswith('System'):
                comps = line.split(':')
                ret['mpstat'].append({})
                ret['mpstat'][procn]['system'] = {}
                cpu_comps = comps[1].split()
                for i in range(0, len(cpu_comps)):
                    cpu_vals = cpu_comps[i].split('=')
                    ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]

            if line.startswith('cpu'):
                fields = line.split()
                continue

            if fields:
                cpustat = line.split()
                ret[_number(cpustat[0])] = {}
                for i in range(1, len(fields)-1):
                    ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])

        return ret

    def openbsd_cpustats():
        '''
        openbsd specific implementation of cpustats
        '''
        systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
        fields = systat[3].split()
        ret = {}
        for cpu in systat[4:]:
            cpu_line = cpu.split()
            cpu_idx = cpu_line[0]
            ret[cpu_idx] = {}

            for idx, field in enumerate(fields[1:]):
                ret[cpu_idx][field] = cpu_line[idx+1]

        return ret

    # dict that return a function that does the right thing per platform
    get_version = {
        'Linux': linux_cpustats,
        'FreeBSD': freebsd_cpustats,
        'OpenBSD': openbsd_cpustats,
        'SunOS': sunos_cpustats,
        'AIX': aix_cpustats,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
445096
def all_status():
    '''
    
    '''
    return {'cpuinfo': cpuinfo(),
            'cpustats': cpustats(),
            'diskstats': diskstats(),
            'diskusage': diskusage(),
            'loadavg': loadavg(),
            'meminfo': meminfo(),
            'netdev': netdev(),
            'netstats': netstats(),
            'uptime': uptime(),
            'vmstats': vmstats(),
            'w': w()}
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
127392
def get_macs(vm_):
    '''
    
    '''
    macs = []
    nics = get_nics(vm_)
    if nics is None:
        return None
    for nic in nics:
        macs.append(nic)

    return macs
118583
def physical_cpus():
    
    if platform.system() == 'Darwin':
        ncores = subprocess.check_output(
            ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False
        )
        return int(ncores.strip())

    sockets = set()
    with open('/proc/cpuinfo') as istr:
        for line in istr:
            if line.startswith('physical id'):
                sockets.add(line.split(':')[-1].strip())
    return len(sockets)
1151743
def list_vms(self, allow_clone=False):
        

        vbox_vms = []
        result = yield from self.execute("list", ["vms"])
        for line in result:
            if len(line) == 0 or line[0] != '"' or line[-1:] != "}":
                continue  # Broken output (perhaps a carriage return in VM name)
            vmname, _ = line.rsplit(' ', 1)
            vmname = vmname.strip('"')
            if vmname == "<inaccessible>":
                continue  # ignore inaccessible VMs
            extra_data = yield from self.execute("getextradata", [vmname, "GNS3/Clone"])
            if allow_clone or len(extra_data) == 0 or not extra_data[0].strip() == "Value: yes":
                # get the amount of RAM
                info_results = yield from self.execute("showvminfo", [vmname, "--machinereadable"])
                ram = 0
                for info in info_results:
                    try:
                        name, value = info.split('=', 1)
                        if name.strip() == "memory":
                            ram = int(value.strip())
                            break
                    except ValueError:
                        continue
                vbox_vms.append({"vmname": vmname, "ram": ram})
        return vbox_vms
333590
def GetCpuReservationMHz(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetCpuReservationMHz(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
898051
def list_domains():
    '''
    
    '''
    data = __salt__['vmadm.list'](keyed=True)
    vms = ["UUID                                  TYPE  RAM      STATE             ALIAS"]
    for vm in data:
        vms.append("{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format(
            vmuuid=vm.ljust(38),
            vmtype=data[vm]['type'].ljust(6),
            vmram=data[vm]['ram'].ljust(9),
            vmstate=data[vm]['state'].ljust(18),
            vmalias=data[vm]['alias'],
        ))
    return vms