Collect the CPU information for the local environment.
513815
def _collect_cpu_info(run_info):
  """"""
  cpu_info = {}

  cpu_info["num_cores"] = multiprocessing.cpu_count()

  # Note: cpuinfo is not installed in the TensorFlow OSS tree.
  # It is installable via pip.
  import cpuinfo    # pylint: disable=g-import-not-at-top

  info = cpuinfo.get_cpu_info()
  cpu_info["cpu_info"] = info["brand"]
  cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6

  run_info["machine_config"]["cpu_info"] = cpu_info
554729
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        # Grab per-CPU stats using psutil's cpu_percent(percpu=True) and
        # cpu_times_percent(percpu=True) methods
        if self.input_method == 'local':
            stats = cpu_percent.get(percpu=True)
        else:
            # Update stats using SNMP
            pass

        # Update the stats
        self.stats = stats

        return self.stats
693921
def collect(self):
        

        def cpu_time_list():
            """
            get cpu time list
            """

            statFile = open(self.PROC, "r")
            timeList = statFile.readline().split(" ")[2:6]
            for i in range(len(timeList)):
                timeList[i] = int(timeList[i])
            statFile.close()
            return timeList

        def cpu_delta_time(interval):
            """
            Get before and after cpu times for usage calc
            """
            pre_check = cpu_time_list()
            time.sleep(interval)
            post_check = cpu_time_list()
            for i in range(len(pre_check)):
                post_check[i] -= pre_check[i]
            return post_check

        if os.access(self.PROC, os.R_OK):

            # If simple only return aggregate CPU% metric
            if str_to_bool(self.config['simple']):
                dt = cpu_delta_time(self.INTERVAL)
                cpuPct = 100 - (dt[len(dt) - 1] * 100.00 / sum(dt))
                self.publish('percent', str('%.4f' % cpuPct))
                return True

            results = {}
            # Open file
            file = open(self.PROC)

            ncpus = -1  # dont want to count the 'cpu'(total) cpu.
            for line in file:
                if not line.startswith('cpu'):
                    continue

                ncpus += 1
                elements = line.split()

                cpu = elements[0]

                if cpu == 'cpu':
                    cpu = 'total'
                elif not str_to_bool(self.config['percore']):
                    continue

                results[cpu] = {}

                if len(elements) >= 2:
                    results[cpu]['user'] = elements[1]
                if len(elements) >= 3:
                    results[cpu]['nice'] = elements[2]
                if len(elements) >= 4:
                    results[cpu]['system'] = elements[3]
                if len(elements) >= 5:
                    results[cpu]['idle'] = elements[4]
                if len(elements) >= 6:
                    results[cpu]['iowait'] = elements[5]
                if len(elements) >= 7:
                    results[cpu]['irq'] = elements[6]
                if len(elements) >= 8:
                    results[cpu]['softirq'] = elements[7]
                if len(elements) >= 9:
                    results[cpu]['steal'] = elements[8]
                if len(elements) >= 10:
                    results[cpu]['guest'] = elements[9]
                if len(elements) >= 11:
                    results[cpu]['guest_nice'] = elements[10]

            # Close File
            file.close()

            metrics = {'cpu_count': ncpus}

            for cpu in results.keys():
                stats = results[cpu]
                for s in stats.keys():
                    # Get Metric Name
                    metric_name = '.'.join([cpu, s])
                    # Get actual data
                    if ((str_to_bool(self.config['normalize']) and
                         cpu == 'total' and
                         ncpus > 0)):
                        metrics[metric_name] = self.derivative(
                            metric_name,
                            long(stats[s]),
                            self.MAX_VALUES[s]) / ncpus
                    else:
                        metrics[metric_name] = self.derivative(
                            metric_name,
                            long(stats[s]),
                            self.MAX_VALUES[s])

            # Check for a bug in xen where the idle time is doubled for guest
            # See https://bugzilla.redhat.com/show_bug.cgi?id=624756
            if self.config['xenfix'] is None or self.config['xenfix'] is True:
                if os.path.isdir('/proc/xen'):
                    total = 0
                    for metric_name in metrics.keys():
                        if 'cpu0.' in metric_name:
                            total += int(metrics[metric_name])
                    if total > 110:
                        self.config['xenfix'] = True
                        for mname in metrics.keys():
                            if '.idle' in mname:
                                metrics[mname] = float(metrics[mname]) / 2
                    elif total > 0:
                        self.config['xenfix'] = False
                else:
                    self.config['xenfix'] = False

            # Publish Metric Derivative
            for metric_name in metrics.keys():
                self.publish(metric_name,
                             metrics[metric_name],
                             precision=2)
            return True

        else:
            if not psutil:
                self.log.error('Unable to import psutil')
                self.log.error('No cpu metrics retrieved')
                return None

            cpu_time = psutil.cpu_times(True)
            cpu_count = len(cpu_time)
            total_time = psutil.cpu_times()
            for i in range(0, len(cpu_time)):
                metric_name = 'cpu' + str(i)
                self.publish(
                    metric_name + '.user',
                    self.derivative(metric_name + '.user',
                                    cpu_time[i].user,
                                    self.MAX_VALUES['user']),
                    precision=2)

                if hasattr(cpu_time[i], 'nice'):
                    self.publish(
                        metric_name + '.nice',
                        self.derivative(metric_name + '.nice',
                                        cpu_time[i].nice,
                                        self.MAX_VALUES['nice']),
                        precision=2)

                self.publish(
                    metric_name + '.system',
                    self.derivative(metric_name + '.system',
                                    cpu_time[i].system,
                                    self.MAX_VALUES['system']),
                    precision=2)

                self.publish(
                    metric_name + '.idle',
                    self.derivative(metric_name + '.idle',
                                    cpu_time[i].idle,
                                    self.MAX_VALUES['idle']),
                    precision=2)

            metric_name = 'total'
            self.publish(
                metric_name + '.user',
                self.derivative(metric_name + '.user',
                                total_time.user,
                                self.MAX_VALUES['user']) / cpu_count,
                precision=2)

            if hasattr(total_time, 'nice'):
                self.publish(
                    metric_name + '.nice',
                    self.derivative(metric_name + '.nice',
                                    total_time.nice,
                                    self.MAX_VALUES['nice']) / cpu_count,
                    precision=2)

            self.publish(
                metric_name + '.system',
                self.derivative(metric_name + '.system',
                                total_time.system,
                                self.MAX_VALUES['system']) / cpu_count,
                precision=2)

            self.publish(
                metric_name + '.idle',
                self.derivative(metric_name + '.idle',
                                total_time.idle,
                                self.MAX_VALUES['idle']) / cpu_count,
                precision=2)

            self.publish('cpu_count', psutil.cpu_count())

            return True

        return None
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
881228
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            # Update stats using the standard system lib
            # Grab MEM using the psutil virtual_memory method
            vm_stats = psutil.virtual_memory()

            # Get all the memory stats (copy/paste of the psutil documentation)
            # total: total physical memory available.
            # available: the actual amount of available memory that can be given instantly to processes that request more memory in bytes; this is calculated by summing different memory values depending on the platform (e.g. free + buffers + cached on Linux) and it is supposed to be used to monitor actual memory usage in a cross platform fashion.
            # percent: the percentage usage calculated as (total - available) / total * 100.
            # used: memory used, calculated differently depending on the platform and designed for informational purposes only.
            # free: memory not being used at all (zeroed) that is readily available; note that this doesn’t reflect the actual memory available (use ‘available’ instead).
            # Platform-specific fields:
            # active: (UNIX): memory currently in use or very recently used, and so it is in RAM.
            # inactive: (UNIX): memory that is marked as not used.
            # buffers: (Linux, BSD): cache for things like file system metadata.
            # cached: (Linux, BSD): cache for various things.
            # wired: (BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.
            # shared: (BSD): memory that may be simultaneously accessed by multiple processes.
            self.reset()
            for mem in ['total', 'available', 'percent', 'used', 'free',
                        'active', 'inactive', 'buffers', 'cached',
                        'wired', 'shared']:
                if hasattr(vm_stats, mem):
                    stats[mem] = getattr(vm_stats, mem)

            # Use the 'free'/htop calculation
            # free=available+buffer+cached
            stats['free'] = stats['available']
            if hasattr(stats, 'buffers'):
                stats['free'] += stats['buffers']
            if hasattr(stats, 'cached'):
                stats['free'] += stats['cached']
            # used=total-free
            stats['used'] = stats['total'] - stats['free']
        elif self.input_method == 'snmp':
            # Update stats using SNMP
            if self.short_system_name in ('windows', 'esxi'):
                # Mem stats for Windows|Vmware Esxi are stored in the FS table
                try:
                    fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
                                                  bulk=True)
                except KeyError:
                    self.reset()
                else:
                    for fs in fs_stat:
                        # The Physical Memory (Windows) or Real Memory (VMware)
                        # gives statistics on RAM usage and availability.
                        if fs in ('Physical Memory', 'Real Memory'):
                            stats['total'] = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
                            stats['used'] = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
                            stats['percent'] = float(stats['used'] * 100 / stats['total'])
                            stats['free'] = stats['total'] - stats['used']
                            break
            else:
                # Default behavor for others OS
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])

                if stats['total'] == '':
                    self.reset()
                    return self.stats

                for key in iterkeys(stats):
                    if stats[key] != '':
                        stats[key] = float(stats[key]) * 1024

                # Use the 'free'/htop calculation
                stats['free'] = stats['free'] - stats['total'] + (stats['buffers'] + stats['cached'])

                # used=total-free
                stats['used'] = stats['total'] - stats['free']

                # percent: the percentage usage calculated as (total - available) / total * 100.
                stats['percent'] = float((stats['total'] - stats['free']) / stats['total'] * 100)

        # Update the stats
        self.stats = stats

        return self.stats
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))
964053
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag, columns, limit):
    """"""

    manager = SoftLayer.HardwareManager(env.client)
    servers = manager.list_hardware(hostname=hostname,
                                    domain=domain,
                                    cpus=cpu,
                                    memory=memory,
                                    datacenter=datacenter,
                                    nic_speed=network,
                                    tags=tag,
                                    mask="mask(SoftLayer_Hardware_Server)[%s]" % columns.mask(),
                                    limit=limit)

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for server in servers:
        table.add_row([value or formatting.blank()
                       for value in columns.row(server)])

    env.fout(table)
445963
def get_environment(self):
        

        environment = {}
        # sys_resources contains cpu and mem output
        sys_resources = self._send_command("show system resources")
        temp_cmd = "show environment temperature"

        # cpu
        environment.setdefault("cpu", {})
        environment["cpu"]["0"] = {}
        environment["cpu"]["0"]["%usage"] = -1.0
        system_resources_cpu = helpers.textfsm_extractor(
            self, "system_resources", sys_resources
        )
        for cpu in system_resources_cpu:
            cpu_dict = {
                cpu.get("cpu_id"): {
                    "%usage": round(100 - float(cpu.get("cpu_idle")), 2)
                }
            }
            environment["cpu"].update(cpu_dict)

        # memory
        environment.setdefault("memory", {})
        for line in sys_resources.splitlines():
            # Memory usage:   16401224K total,   4798280K used,   11602944K free
            if "Memory usage:" in line:
                proc_total_mem, proc_used_mem, _ = line.split(",")
                proc_used_mem = re.search(r"\d+", proc_used_mem).group(0)
                proc_total_mem = re.search(r"\d+", proc_total_mem).group(0)
                break
        else:
            raise ValueError("Unexpected output from: {}".format(line))
        environment["memory"]["used_ram"] = int(proc_used_mem)
        environment["memory"]["available_ram"] = int(proc_total_mem)

        # temperature
        output = self._send_command(temp_cmd)
        environment.setdefault("temperature", {})
        for line in output.splitlines():
            # Module   Sensor        MajorThresh   MinorThres   CurTemp     Status
            # 1        Intake          70              42          28         Ok
            if re.match(r"^[0-9]", line):
                module, sensor, is_critical, is_alert, temp, _ = line.split()
                is_critical = float(is_critical)
                is_alert = float(is_alert)
                temp = float(temp)
                env_value = {
                    "is_alert": temp >= is_alert,
                    "is_critical": temp >= is_critical,
                    "temperature": temp,
                }
                location = "{0}-{1}".format(sensor, module)
                environment["temperature"][location] = env_value

        # Initialize 'power' and 'fan' to default values (not implemented)
        environment.setdefault("power", {})
        environment["power"]["invalid"] = {
            "status": True,
            "output": -1.0,
            "capacity": -1.0,
        }
        environment.setdefault("fans", {})
        environment["fans"]["invalid"] = {"status": True}

        return environment
1170478
protected function cpuinfo()
    {
        $dev = new CpuDevice();
        if (CommonFunctions::executeProgram('hostinfo', '| grep "Processor type"', $buf, PSI_DEBUG)) {
            $dev->setModel(preg_replace('/Processor type: /', '', $buf));
            $buf=$this->grabkey('hw.model');
            if (!is_null($buf) && (trim($buf) != "")) {
                $this->sys->setMachine(trim($buf));
                if (CommonFunctions::rfts(PSI_APP_ROOT.'/data/ModelTranslation.txt', $buffer)) {
                    $buffer = preg_split("/\n/", $buffer, -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($buffer as $line) {
                        $ar_buf = preg_split("/:/", $line, 3);
                        if (trim($buf) === trim($ar_buf[0])) {
                            $dev->setModel(trim($ar_buf[2]));
                            $this->sys->setMachine($this->sys->getMachine().' - '.trim($ar_buf[1]));
                            break;
                        }
                    }
                }
            }
            $buf=$this->grabkey('machdep.cpu.brand_string');
            if (!is_null($buf) && (trim($buf) != "") &&
                 ((trim($buf) != "i486 (Intel 80486)") || ($dev->getModel() == ""))) {
                $dev->setModel(trim($buf));
            }
            $buf=$this->grabkey('machdep.cpu.features');
            if (!is_null($buf) && (trim($buf) != "")) {
                if (preg_match("/ VMX/", $buf)) {
                    $dev->setVirt("vmx");
                } elseif (preg_match("/ SVM/", $buf)) {
                    $dev->setVirt("svm");
                }
            }
        }
        $dev->setCpuSpeed(round($this->grabkey('hw.cpufrequency') / 1000000));
        $dev->setBusSpeed(round($this->grabkey('hw.busfrequency') / 1000000));
        $bufn=$this->grabkey('hw.cpufrequency_min');
        $bufx=$this->grabkey('hw.cpufrequency_max');
        if (!is_null($bufn) && (trim($bufn) != "") && !is_null($bufx) && (trim($bufx) != "") && ($bufn != $bufx)) {
            $dev->setCpuSpeedMin(round($bufn / 1000000));
            $dev->setCpuSpeedMax(round($bufx / 1000000));
        }
        $buf=$this->grabkey('hw.l2cachesize');
        if (!is_null($buf) && (trim($buf) != "")) {
            $dev->setCache(round($buf));
        }
        $ncpu = $this->grabkey('hw.ncpu');
        if (is_null($ncpu) || (trim($ncpu) == "") || (!($ncpu >= 1)))
            $ncpu = 1;
        for ($ncpu ; $ncpu > 0 ; $ncpu--) {
            $this->sys->setCpus($dev);
        }
    }
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
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 {}
1271615
protected void parseCpuInfo(String[] cpuInfoFile) throws IOException {
    int numCpu = 0;
    double cpuTotalGHz = 0;
    for (String line : cpuInfoFile) {
      if (line.startsWith("processor")) {
        numCpu++;
      }
      if (line.startsWith("cpu MHz")) {
        cpuTotalGHz += Double.parseDouble(line.split(":")[1].trim()) / 1000d;
      }
    }
    ttUtilization.setNumCpu(numCpu);
    ttUtilization.setCpuTotalGHz(cpuTotalGHz);
  }
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
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);
                }
            }
        }
    }
85857
protected function _cpuinfo()
    {
        if (CommonFunctions::executeProgram('pidin', 'info', $buf)
           && preg_match('/^Processor\d+: (.*)/m', $buf)) {
            $lines = preg_split("/\n/", $buf, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($lines as $line) {
                if (preg_match('/^Processor\d+: (.+)/', $line, $proc)) {
                    $dev = new CpuDevice();
                    $dev->SetModel(trim($proc[1]));
                    if (preg_match('/(\d+)MHz/', $proc[1], $mhz)) {
                        $dev->setCpuSpeed($mhz[1]);
                    }
                    $this->sys->setCpus($dev);
                }
            }
        }
    }
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 {}
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)()