-------------------------- CPU - Processor Data
334607
function cpu(callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      getCpu().then(result => {
        if (callback) { callback(result); }
        resolve(result);
      });
    });
  });
}
330088
def _aix_cpudata():
    '''
    
    '''
    # Provides:
    #   cpuarch
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    cmd = salt.utils.path.which('prtconf')
    if cmd:
        data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
        for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'),
                                ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'),
                                ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'),
                                ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')):
            for regex in [re.compile(r) for r in [regstring]]:
                res = regex.search(data)
                if res and len(res.groups()) >= 1:
                    grains[dest] = res.group(1).strip().replace("'", '')
    else:
        log.error('The \'prtconf\' binary was not found in $PATH.')
    return grains
173605
function num_of_cpus() {
  try {
    if(process.env['OMP_NUM_THREADS']) {
      return process.env['OMP_NUM_THREADS'];
    }

    return Math.ceil(jsonConfig.info.limits.cpu);
  } catch (err) {
    throw new Error('Could not get number of cpus');
  }
}
137458
def system_info(data):
    '''
    
    '''
    if not data:
        return {}
    info = {
        'software': _parse_software(data),
        'hardware': _parse_hardware(data),
        'plugins': _parse_plugins(data),
    }
    return {'nxos': info}
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)()
102779
function CpuSlice(cat, title, colorId, start, args, opt_duration) {
    Slice.apply(this, arguments);
    this.threadThatWasRunning = undefined;
    this.cpu = undefined;
  }
749552
protected function cpu_info()
    {

        $this->cpu_info = array();
        if (!stristr(PHP_OS, 'win')) {
            exec("cat /proc/cpuinfo", $output);
            foreach ($output as $line) {
                $parts = explode(':', $line);

                if (empty($parts[0])) continue;

                $this->cpu_info[trim($parts[0])] = (!empty($parts[1])) ? trim($parts[1]) : null;
            }
        }

        return true;
    }
1114394
def get_cpu_info(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo')
        return output
958125
def is_cpu(self):
        
        return self._device.get_info(cl.device_info.TYPE) == cl.device_type.CPU
597182
function get_cpu_idle() {
  var idle = 0;
  var cpus = os.cpus();
  var i, len;
  for (i=0, len = cpus.length; i < len; i += 1) {
    var cpu = cpus[i];
    var total = cpu.times.sys + cpu.times.idle + cpu.times.user + cpu.times.nice + cpu.times.irq;
    idle += (cpu.times.idle/total*100);
  }
  idle = idle / cpus.length;
  return idle;
}
1104838
def cpustats():
    '''
    
    '''
    # Tries to gather information similar to that returned by a Linux machine
    # Avoid using WMI as there's a lot of overhead

    # Time related info
    user, system, idle, interrupt, dpc = psutil.cpu_times()
    cpu = {'user': user,
           'system': system,
           'idle': idle,
           'irq': interrupt,
           'dpc': dpc}
    # Count related info
    ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
    intr = {'irqs': {'irqs': [],
                     'total': interrupts}}
    soft_irq = {'softirqs': [],
               'total': soft_interrupts}
    return {'btime': psutil.boot_time(),
            'cpu': cpu,
            'ctxt': ctx_switches,
            'intr': intr,
            'processes': len(psutil.pids()),
            'softirq': soft_irq,
            'syscalls': sys_calls}
441950
def _get_cpu_info_from_sysctl():
	'''
	
	'''
	try:
		# Just return {} if there is no sysctl
		if not DataSource.has_sysctl():
			return {}

		# If sysctl fails return {}
		returncode, output = DataSource.sysctl_machdep_cpu_hw_cpufrequency()
		if output == None or returncode != 0:
			return {}

		# Various fields
		vendor_id = _get_field(False, output, None, None, 'machdep.cpu.vendor')
		processor_brand = _get_field(True, output, None, None, 'machdep.cpu.brand_string')
		cache_size = _get_field(False, output, None, None, 'machdep.cpu.cache.size')
		stepping = _get_field(False, output, int, 0, 'machdep.cpu.stepping')
		model = _get_field(False, output, int, 0, 'machdep.cpu.model')
		family = _get_field(False, output, int, 0, 'machdep.cpu.family')

		# Flags
		flags = _get_field(False, output, None, '', 'machdep.cpu.features').lower().split()
		flags.extend(_get_field(False, output, None, '', 'machdep.cpu.leaf7_features').lower().split())
		flags.extend(_get_field(False, output, None, '', 'machdep.cpu.extfeatures').lower().split())
		flags.sort()

		# Convert from GHz/MHz string to Hz
		hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
		hz_actual = _get_field(False, output, None, None, 'hw.cpufrequency')
		hz_actual = _to_decimal_string(hz_actual)

		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, 0),
		'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
		'hz_actual' : _hz_short_to_full(hz_actual, 0),

		'l2_cache_size' : _to_friendly_bytes(cache_size),

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

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		return {}
1301511
def _actual_get_cpu_info_from_cpuid(queue):
	'''
	
	'''

	# Pipe all output to nothing
	sys.stdout = open(os.devnull, 'w')
	sys.stderr = open(os.devnull, 'w')

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

	# Return none if this is not an X86 CPU
	if not arch in ['X86_32', 'X86_64']:
		queue.put(_obj_to_b64({}))
		return

	# Return none if SE Linux is in enforcing mode
	cpuid = CPUID()
	if cpuid.is_selinux_enforcing:
		queue.put(_obj_to_b64({}))
		return

	# Get the cpu info from the CPUID register
	max_extension_support = cpuid.get_max_extension_support()
	cache_info = cpuid.get_cache(max_extension_support)
	info = cpuid.get_info()

	processor_brand = cpuid.get_processor_brand(max_extension_support)

	# Get the Hz and scale
	hz_actual = cpuid.get_raw_hz()
	hz_actual = _to_decimal_string(hz_actual)

	# Get the Hz and scale
	hz_advertised, scale = _parse_cpu_brand_string(processor_brand)
	info = {
	'vendor_id_raw' : cpuid.get_vendor_id(),
	'hardware_raw' : '',
	'brand_raw' : processor_brand,

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

	'l2_cache_size' : _to_friendly_bytes(cache_info['size_kb']),
	'l2_cache_line_size' : cache_info['line_size_b'],
	'l2_cache_associativity' : hex(cache_info['associativity']),

	'stepping' : info['stepping'],
	'model' : info['model'],
	'family' : info['family'],
	'processor_type' : info['processor_type'],
	'extended_model' : info['extended_model'],
	'extended_family' : info['extended_family'],
	'flags' : cpuid.get_flags(max_extension_support)
	}

	info = {k: v for k, v in info.items() if v}
	queue.put(_obj_to_b64(info))
78270
def read_stat():
    
    data = []
    with open("/proc/stat", "rb") as stat_file:
        for line in stat_file:
            cpu_stat = line.split()
            if cpu_stat[0][:3] != b"cpu":
                break
            # First cpu line is aggregation of following lines, skip it
            if len(cpu_stat[0]) == 3:
                continue
            data.append(
                {
                    "times": {
                        "user": int(cpu_stat[1]),
                        "nice": int(cpu_stat[2]),
                        "sys": int(cpu_stat[3]),
                        "idle": int(cpu_stat[4]),
                        "irq": int(cpu_stat[6]),
                    }
                }
            )
    return data
401949
def _get_cpu_info_internal():
	'''
	
	'''

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

	friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unknown bits'
	friendly_version = "{0}.{1}.{2}.{3}.{4}".format(*sys.version_info)
	PYTHON_VERSION = "{0} ({1})".format(friendly_version, friendly_maxsize)

	info = {
		'python_version' : PYTHON_VERSION,
		'cpuinfo_version' : CPUINFO_VERSION,
		'cpuinfo_version_string' : CPUINFO_VERSION_STRING,
		'arch' : arch,
		'bits' : bits,
		'count' : DataSource.cpu_count,
		'arch_string_raw' : DataSource.arch_string_raw,
	}

	# Try the Windows wmic
	_copy_new_fields(info, _get_cpu_info_from_wmic())

	# Try the Windows registry
	_copy_new_fields(info, _get_cpu_info_from_registry())

	# Try /proc/cpuinfo
	_copy_new_fields(info, _get_cpu_info_from_proc_cpuinfo())

	# Try cpufreq-info
	_copy_new_fields(info, _get_cpu_info_from_cpufreq_info())

	# Try LSCPU
	_copy_new_fields(info, _get_cpu_info_from_lscpu())

	# Try sysctl
	_copy_new_fields(info, _get_cpu_info_from_sysctl())

	# Try kstat
	_copy_new_fields(info, _get_cpu_info_from_kstat())

	# Try dmesg
	_copy_new_fields(info, _get_cpu_info_from_dmesg())

	# Try /var/run/dmesg.boot
	_copy_new_fields(info, _get_cpu_info_from_cat_var_run_dmesg_boot())

	# Try lsprop ibm,pa-features
	_copy_new_fields(info, _get_cpu_info_from_ibm_pa_features())

	# Try sysinfo
	_copy_new_fields(info, _get_cpu_info_from_sysinfo())

	# Try querying the CPU cpuid register
	_copy_new_fields(info, _get_cpu_info_from_cpuid())

	# Try platform.uname
	_copy_new_fields(info, _get_cpu_info_from_platform_uname())

	return info
1096546
def _get_cpu_info_from_cpuid():
	'''
	
	'''
	from multiprocessing import Process, Queue

	# Return {} if can't cpuid
	if not DataSource.can_cpuid:
		return {}

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

	# Return {} if this is not an X86 CPU
	if not arch in ['X86_32', 'X86_64']:
		return {}

	try:
		# Start running the function in a subprocess
		queue = Queue()
		p = Process(target=_actual_get_cpu_info_from_cpuid, args=(queue,))
		p.start()

		# Wait for the process to end, while it is still alive
		while p.is_alive():
			p.join(0)

		# Return {} if it failed
		if p.exitcode != 0:
			return {}

		# Return the result, only if there is something to read
		if not queue.empty():
			output = queue.get()
			return _b64_to_obj(output)
	except:
		pass

	# Return {} if everything failed
	return {}
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