Return some CPU information on Windows minions
437074
def _windows_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    grains = {}
    if 'NUMBER_OF_PROCESSORS' in os.environ:
        # Cast to int so that the logic isn't broken when used as a
        # conditional in templating. Also follows _linux_cpudata()
        try:
            grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
        except ValueError:
            grains['num_cpus'] = 1
    grains['cpu_model'] = salt.utils.win_reg.read_value(
        hive="HKEY_LOCAL_MACHINE",
        key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
        vname="ProcessorNameString").get('vdata')
    return grains
477072
def _get_cpu_info_from_registry():
	'''
	
	'''
	try:
		# Just return {} if not on Windows
		if not DataSource.is_windows:
			return {}

		# Get the CPU name
		processor_brand = DataSource.winreg_processor_brand().strip()

		# Get the CPU vendor id
		vendor_id = DataSource.winreg_vendor_id_raw()

		# Get the CPU arch and bits
		arch_string_raw = DataSource.winreg_arch_string_raw()
		arch, bits = _parse_arch(arch_string_raw)

		# Get the actual CPU Hz
		hz_actual = DataSource.winreg_hz_actual()
		hz_actual = _to_decimal_string(hz_actual)

		# Get the advertised CPU Hz
		hz_advertised, scale = _parse_cpu_brand_string(processor_brand)

		# If advertised hz not found, use the actual hz
		if hz_advertised == '0.0':
			scale = 6
			hz_advertised = _to_decimal_string(hz_actual)

		# Get the CPU features
		feature_bits = DataSource.winreg_feature_bits()

		def is_set(bit):
			mask = 0x80000000 >> bit
			retval = mask & feature_bits > 0
			return retval

		# http://en.wikipedia.org/wiki/CPUID
		# http://unix.stackexchange.com/questions/43539/what-do-the-flags-in-proc-cpuinfo-mean
		# http://www.lohninger.com/helpcsuite/public_constants_cpuid.htm
		flags = {
			'fpu' : is_set(0), # Floating Point Unit
			'vme' : is_set(1), # V86 Mode Extensions
			'de' : is_set(2), # Debug Extensions - I/O breakpoints supported
			'pse' : is_set(3), # Page Size Extensions (4 MB pages supported)
			'tsc' : is_set(4), # Time Stamp Counter and RDTSC instruction are available
			'msr' : is_set(5), # Model Specific Registers
			'pae' : is_set(6), # Physical Address Extensions (36 bit address, 2MB pages)
			'mce' : is_set(7), # Machine Check Exception supported
			'cx8' : is_set(8), # Compare Exchange Eight Byte instruction available
			'apic' : is_set(9), # Local APIC present (multiprocessor operation support)
			'sepamd' : is_set(10), # Fast system calls (AMD only)
			'sep' : is_set(11), # Fast system calls
			'mtrr' : is_set(12), # Memory Type Range Registers
			'pge' : is_set(13), # Page Global Enable
			'mca' : is_set(14), # Machine Check Architecture
			'cmov' : is_set(15), # Conditional MOVe instructions
			'pat' : is_set(16), # Page Attribute Table
			'pse36' : is_set(17), # 36 bit Page Size Extensions
			'serial' : is_set(18), # Processor Serial Number
			'clflush' : is_set(19), # Cache Flush
			#'reserved1' : is_set(20), # reserved
			'dts' : is_set(21), # Debug Trace Store
			'acpi' : is_set(22), # ACPI support
			'mmx' : is_set(23), # MultiMedia Extensions
			'fxsr' : is_set(24), # FXSAVE and FXRSTOR instructions
			'sse' : is_set(25), # SSE instructions
			'sse2' : is_set(26), # SSE2 (WNI) instructions
			'ss' : is_set(27), # self snoop
			#'reserved2' : is_set(28), # reserved
			'tm' : is_set(29), # Automatic clock control
			'ia64' : is_set(30), # IA64 instructions
			'3dnow' : is_set(31) # 3DNow! instructions available
		}

		# Get a list of only the flags that are true
		flags = [k for k, v in flags.items() if v]
		flags.sort()

		info = {
		'vendor_id_raw' : vendor_id,
		'brand_raw' : processor_brand,

		'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
		'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 6),
		'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
		'hz_actual' : _hz_short_to_full(hz_actual, 6),

		'flags' : flags
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		return {}
951771
def vm_info(vm_=None):
    '''
    
    '''
    with _get_xapi_session() as xapi:

        def _info(vm_):
            vm_rec = _get_record_by_label(xapi, 'VM', vm_)
            if vm_rec is False:
                return False
            vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec)

            return {'cpu': vm_metrics_rec['VCPUs_number'],
                    'maxCPU': _get_val(vm_rec, ['VCPUs_max']),
                    'cputime': vm_metrics_rec['VCPUs_utilisation'],
                    'disks': get_disks(vm_),
                    'nics': get_nics(vm_),
                    'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])),
                    'mem': int(vm_metrics_rec['memory_actual']),
                    'state': _get_val(vm_rec, ['power_state'])
                    }
        info = {}
        if vm_:
            ret = _info(vm_)
            if ret is not None:
                info[vm_] = ret
        else:
            for vm_ in list_domains():
                ret = _info(vm_)
                if ret is not None:
                    info[vm_] = _info(vm_)
        return info
1190056
def get_memory_info(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
        return output
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)
34985
def _available_cpu_count():
    
    try:
        return len(os.sched_getaffinity(0))
    except AttributeError:
        pass
    import re
    try:
        with open('/proc/self/status') as f:
            status = f.read()
        m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', status)
        if m:
            res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        pass
    try:
        import multiprocessing
        return multiprocessing.cpu_count()
    except (ImportError, NotImplementedError):
        return 1
854108
def get_cpu_info(self):
        
        info = snap7.snap7types.S7CpuInfo()
        result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))
        check_error(result, context="client")
        return info
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()}
293747
def _get_cpu_info_from_wmic():
	'''
	
	'''

	try:
		# Just return {} if not Windows or there is no wmic
		if not DataSource.is_windows or not DataSource.has_wmic():
			return {}

		returncode, output = DataSource.wmic_cpu()
		if output == None or returncode != 0:
			return {}

		# Break the list into key values pairs
		value = output.split("\n")
		value = [s.rstrip().split('=') for s in value if '=' in s]
		value = {k: v for k, v in value if v}

		# Get the advertised MHz
		processor_brand = value.get('Name')
		hz_advertised, scale_advertised = _parse_cpu_brand_string(processor_brand)

		# Get the actual MHz
		hz_actual = value.get('CurrentClockSpeed')
		scale_actual = 6
		if hz_actual:
			hz_actual = _to_decimal_string(hz_actual)

		# Get cache sizes
		l2_cache_size = value.get('L2CacheSize')
		if l2_cache_size:
			l2_cache_size = l2_cache_size + ' KB'

		l3_cache_size = value.get('L3CacheSize')
		if l3_cache_size:
			l3_cache_size = l3_cache_size + ' KB'

		# Get family, model, and stepping
		family, model, stepping = '', '', ''
		description = value.get('Description') or value.get('Caption')
		entries = description.split(' ')

		if 'Family' in entries and entries.index('Family') < len(entries)-1:
			i = entries.index('Family')
			family = int(entries[i + 1])

		if 'Model' in entries and entries.index('Model') < len(entries)-1:
			i = entries.index('Model')
			model = int(entries[i + 1])

		if 'Stepping' in entries and entries.index('Stepping') < len(entries)-1:
			i = entries.index('Stepping')
			stepping = int(entries[i + 1])

		info = {
			'vendor_id_raw' : value.get('Manufacturer'),
			'brand_raw' : processor_brand,

			'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale_advertised),
			'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, scale_actual),
			'hz_advertised' : _hz_short_to_full(hz_advertised, scale_advertised),
			'hz_actual' : _hz_short_to_full(hz_actual, scale_actual),

			'l2_cache_size' : l2_cache_size,
			'l3_cache_size' : l3_cache_size,

			'stepping' : stepping,
			'model' : model,
			'family' : family,
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		#raise # NOTE: To have this throw on error, uncomment this line
		return {}
678164
def num_unused_cpus(thresh=10):
    
    import psutil
    cpu_usage = psutil.cpu_percent(percpu=True)
    return sum([p < thresh for p in cpu_usage])
583871
def get_cpu_timings(self):
        
        timings = {}
        with open('/proc/stat', 'r') as file_obj:
            for line in file_obj:
                if 'cpu' in line:
                    line = line.strip().split()
                    timings[line[0]] = [int(x) for x in line[1:]]

        return timings
224266
def cpuinfo():
    """"""
    f = open("/proc/cpuinfo")
    hwinfo = {}
    for line in f.readlines():
        cpul = line.split(":")
        name = cpul[0].strip()
        if (len(cpul) > 1):
            val = cpul[1].strip()
        if (name == "model name"):
            hwinfo["CPU"] = val
        elif (name == "cpu MHz"):
            hwinfo["MHz"] = int(round(float(val)))
    f.close()
    return hwinfo
1238757
def update_local(self):
        """"""
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
        # Get all possible values for CPU stats: user, system, idle,
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
        # The following stats are returned by the API but not displayed in the UI:
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)

        # Init new stats
        stats = self.get_init_value()

        stats['total'] = cpu_percent.get()
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
        for stat in ['user', 'system', 'idle', 'nice', 'iowait',
                     'irq', 'softirq', 'steal', 'guest', 'guest_nice']:
            if hasattr(cpu_times_percent, stat):
                stats[stat] = getattr(cpu_times_percent, stat)

        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
        # ctx_switches: number of context switches (voluntary + involuntary) per second
        # interrupts: number of interrupts per second
        # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS.
        # syscalls: number of system calls since boot. Always set to 0 on Linux.
        cpu_stats = psutil.cpu_stats()
        # By storing time data we enable Rx/s and Tx/s calculations in the
        # XML/RPC API, which would otherwise be overly difficult work
        # for users of the API
        time_since_update = getTimeSinceLastUpdate('cpu')

        # Previous CPU stats are stored in the cpu_stats_old variable
        if not hasattr(self, 'cpu_stats_old'):
            # First call, we init the cpu_stats_old var
            self.cpu_stats_old = cpu_stats
        else:
            for stat in cpu_stats._fields:
                if getattr(cpu_stats, stat) is not None:
                    stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat)

            stats['time_since_update'] = time_since_update

            # Core number is needed to compute the CTX switch limit
            stats['cpucore'] = self.nb_log_core

            # Save stats to compute next step
            self.cpu_stats_old = cpu_stats

        return stats
314523
protected function _cpuinfo()
    {

        if (CommonFunctions::executeProgram('sysinfo', '-cpu', $bufr, PSI_DEBUG)) {
            $cpus = preg_split("/\nCPU #\d+/", $bufr, -1, PREG_SPLIT_NO_EMPTY);
            $cpuspeed = "";
            foreach ($cpus as $cpu) {
                if (preg_match("/^.*running at (\d+)MHz/", $cpu, $ar_buf)) {
                    $cpuspeed = $ar_buf[1];
                } elseif (preg_match("/^: \"(.*)\"/", $cpu, $ar_buf)) {
                    $dev = new CpuDevice();
                    $dev->setModel($ar_buf[1]);
                    $arrLines = preg_split("/\n/", $cpu, -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($arrLines as $Line) {
                        if (preg_match("/^\s+Data TLB:\s+(.*)K-byte/", $Line, $Line_buf)) {
                            $dev->setCache(max($Line_buf[1]*1024, $dev->getCache()));
                        } elseif (preg_match("/^\s+Data TLB:\s+(.*)M-byte/", $Line, $Line_buf)) {
                            $dev->setCache(max($Line_buf[1]*1024*1024, $dev->getCache()));
                        } elseif (preg_match("/^\s+Data TLB:\s+(.*)G-byte/", $Line, $Line_buf)) {
                            $dev->setCache(max($Line_buf[1]*1024*1024*1024, $dev->getCache()));
                        } elseif (preg_match("/\s+VMX/", $Line, $Line_buf)) {
                            $dev->setVirt("vmx");
                        } elseif (preg_match("/\s+SVM/", $Line, $Line_buf)) {
                            $dev->setVirt("svm");
                        }
                    }
                    if ($cpuspeed != "") {
                        $dev->setCpuSpeed($cpuspeed);
                    }
                    $this->sys->setCpus($dev);
                }
            }
        }
    }
810639
def get_cpu_props(cls, family, arch='x86'):
        

        cpus = cls.get_cpus_by_arch(arch)
        try:
            return cpus.xpath('model[@name="{0}"]'.format(family))[0]
        except IndexError:
            raise LagoException('No such CPU family: {0}'.format(family))
590589
def _get_bios_setting(self, bios_property):
        """"""
        headers, bios_uri, bios_settings = self._check_bios_resource([
            bios_property])
        return bios_settings[bios_property]
480750
def _get_cpu(self):
        '''
        
        '''
        # CPU data in grains is OK-ish, but lscpu is still better in this case
        out = __salt__['cmd.run_all']("lscpu")
        salt.utils.fsutils._verify_run(out)
        data = dict()
        for descr, value in [elm.split(":", 1) for elm in out['stdout'].split(os.linesep)]:
            data[descr.strip()] = value.strip()

        return data