Return CPU information for AIX systems
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
278488
def _get_cpu_info_from_cat_var_run_dmesg_boot():
	'''
	
	'''
	# Just return {} if there is no /var/run/dmesg.boot
	if not DataSource.has_var_run_dmesg_boot():
		return {}

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

	return _parse_dmesg_output(output)
1203758
def get_system_info():
    '''
    
    '''
    def byte_calc(val):
        val = float(val)
        if val < 2**10:
            return '{0:.3f}B'.format(val)
        elif val < 2**20:
            return '{0:.3f}KB'.format(val / 2**10)
        elif val < 2**30:
            return '{0:.3f}MB'.format(val / 2**20)
        elif val < 2**40:
            return '{0:.3f}GB'.format(val / 2**30)
        else:
            return '{0:.3f}TB'.format(val / 2**40)

    # Lookup dicts for Win32_OperatingSystem
    os_type = {1: 'Work Station',
               2: 'Domain Controller',
               3: 'Server'}

    # lookup dicts for Win32_ComputerSystem
    domain_role = {0: 'Standalone Workstation',
                   1: 'Member Workstation',
                   2: 'Standalone Server',
                   3: 'Member Server',
                   4: 'Backup Domain Controller',
                   5: 'Primary Domain Controller'}
    warning_states = {1: 'Other',
                      2: 'Unknown',
                      3: 'Safe',
                      4: 'Warning',
                      5: 'Critical',
                      6: 'Non-recoverable'}
    pc_system_types = {0: 'Unspecified',
                       1: 'Desktop',
                       2: 'Mobile',
                       3: 'Workstation',
                       4: 'Enterprise Server',
                       5: 'SOHO Server',
                       6: 'Appliance PC',
                       7: 'Performance Server',
                       8: 'Maximum'}

    # Connect to WMI
    with salt.utils.winapi.Com():
        conn = wmi.WMI()

        system = conn.Win32_OperatingSystem()[0]
        ret = {'name': get_computer_name(),
               'description': system.Description,
               'install_date': system.InstallDate,
               'last_boot': system.LastBootUpTime,
               'os_manufacturer': system.Manufacturer,
               'os_name': system.Caption,
               'users': system.NumberOfUsers,
               'organization': system.Organization,
               'os_architecture': system.OSArchitecture,
               'primary': system.Primary,
               'os_type': os_type[system.ProductType],
               'registered_user': system.RegisteredUser,
               'system_directory': system.SystemDirectory,
               'system_drive': system.SystemDrive,
               'os_version': system.Version,
               'windows_directory': system.WindowsDirectory}

        system = conn.Win32_ComputerSystem()[0]
        # Get pc_system_type depending on Windows version
        if platform.release() in ['Vista', '7', '8']:
            # Types for Vista, 7, and 8
            pc_system_type = pc_system_types[system.PCSystemType]
        else:
            # New types were added with 8.1 and newer
            pc_system_types.update({8: 'Slate', 9: 'Maximum'})
            pc_system_type = pc_system_types[system.PCSystemType]
        ret.update({
            'bootup_state': system.BootupState,
            'caption': system.Caption,
            'chassis_bootup_state': warning_states[system.ChassisBootupState],
            'chassis_sku_number': system.ChassisSKUNumber,
            'dns_hostname': system.DNSHostname,
            'domain': system.Domain,
            'domain_role': domain_role[system.DomainRole],
            'hardware_manufacturer': system.Manufacturer,
            'hardware_model': system.Model,
            'network_server_mode_enabled': system.NetworkServerModeEnabled,
            'part_of_domain': system.PartOfDomain,
            'pc_system_type': pc_system_type,
            'power_state': system.PowerState,
            'status': system.Status,
            'system_type': system.SystemType,
            'total_physical_memory': byte_calc(system.TotalPhysicalMemory),
            'total_physical_memory_raw': system.TotalPhysicalMemory,
            'thermal_state': warning_states[system.ThermalState],
            'workgroup': system.Workgroup
        })
        # Get processor information
        processors = conn.Win32_Processor()
        ret['processors'] = 0
        ret['processors_logical'] = 0
        ret['processor_cores'] = 0
        ret['processor_cores_enabled'] = 0
        ret['processor_manufacturer'] = processors[0].Manufacturer
        ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz'
        for processor in processors:
            ret['processors'] += 1
            ret['processors_logical'] += processor.NumberOfLogicalProcessors
            ret['processor_cores'] += processor.NumberOfCores
            ret['processor_cores_enabled'] += processor.NumberOfEnabledCore

        bios = conn.Win32_BIOS()[0]
        ret.update({'hardware_serial': bios.SerialNumber,
                    'bios_manufacturer': bios.Manufacturer,
                    'bios_version': bios.Version,
                    'bios_details': bios.BIOSVersion,
                    'bios_caption': bios.Caption,
                    'bios_description': bios.Description})
        ret['install_date'] = _convert_date_time_string(ret['install_date'])
        ret['last_boot'] = _convert_date_time_string(ret['last_boot'])
    return ret
64145
protected function _cpuinfo()
    {
        if (CommonFunctions::rfts('/proc/cpuinfo', $bufr, 0, 4096, false)) {
            $processors = preg_split('/\s?\n\s?\n/', trim($bufr));
            foreach ($processors as $processor) {
                $_n = ""; $_f = ""; $_m = ""; $_s = "";
                $dev = new CpuDevice();
                $details = preg_split("/\n/", $processor, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($details as $detail) {
                    $arrBuff = preg_split('/\s+:\s+/', trim($detail));
                    if (count($arrBuff) == 2) {
                        switch (strtolower($arrBuff[0])) {
                        case 'model name':
                            $_n = $arrBuff[1];
                            break;
                        case 'cpu mhz':
                            $dev->setCpuSpeed($arrBuff[1]);
                            break;
                        case 'cpu family':
                            $_f = $arrBuff[1];
                            break;
                        case 'model':
                            $_m = $arrBuff[1];
                            break;
                        case 'stepping':
                            $_s = $arrBuff[1];
                            break;
                        case 'flags':
                            if (preg_match("/ vmx/", $arrBuff[1])) {
                                $dev->setVirt("vmx");
                            } elseif (preg_match("/ svm/", $arrBuff[1])) {
                                $dev->setVirt("svm");
                            }
                        break;
                        }
                    }
                }
                if ($_n == "") $_n="CPU";
                if ($_f != "") $_n.=" Family ".$_f;
                if ($_m != "") $_n.=" Model ".$_m;
                if ($_s != "") $_n.=" Stepping ".$_s;
                $dev->SetModel($_n);
                $this->sys->setCpus($dev);
            }
        } else
        foreach ($this->readdmesg() as $line) {
            if (preg_match('/kernel: (CPU .*) freq (.*) MHz/', $line, $ar_buf)) {
                $dev = new CpuDevice();
                $dev->setModel($ar_buf[1]);
                $dev->setCpuSpeed($ar_buf[2]);
                $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);
                }
            }
        }
    }
796151
def _get_cpu_count(self):
        """"""
        try:
            from multiprocessing import cpu_count

            return cpu_count()
        except Exception as e:
            Config.main_logger.error("_get_cpu_count failed for %s" % e)
128083
def _bsd_cpudata(osdata):
    '''
    
    '''
    # Provides:
    #   cpuarch
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    sysctl = salt.utils.path.which('sysctl')
    arch = salt.utils.path.which('arch')
    cmds = {}

    if sysctl:
        cmds.update({
            'num_cpus': '{0} -n hw.ncpu'.format(sysctl),
            'cpuarch': '{0} -n hw.machine'.format(sysctl),
            'cpu_model': '{0} -n hw.model'.format(sysctl),
        })

    if arch and osdata['kernel'] == 'OpenBSD':
        cmds['cpuarch'] = '{0} -s'.format(arch)

    if osdata['kernel'] == 'Darwin':
        cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl)
        cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl)

    grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)])

    if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types):
        grains['cpu_flags'] = grains['cpu_flags'].split(' ')

    if osdata['kernel'] == 'NetBSD':
        grains['cpu_flags'] = []
        for line in __salt__['cmd.run']('cpuctl identify 0').splitlines():
            cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line)
            if cpu_match:
                flag = cpu_match.group(1).split(',')
                grains['cpu_flags'].extend(flag)

    if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'):
        grains['cpu_flags'] = []
        # TODO: at least it needs to be tested for BSD other then FreeBSD
        with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp:
            cpu_here = False
            for line in _fp:
                if line.startswith('CPU: '):
                    cpu_here = True  # starts CPU descr
                    continue
                if cpu_here:
                    if not line.startswith(' '):
                        break  # game over
                    if 'Features' in line:
                        start = line.find('<')
                        end = line.find('>')
                        if start > 0 and end > 0:
                            flag = line[start + 1:end].split(',')
                            grains['cpu_flags'].extend(flag)
    try:
        grains['num_cpus'] = int(grains['num_cpus'])
    except ValueError:
        grains['num_cpus'] = 1

    return grains
207509
def count_processors():
    """"""
    if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
    elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
         text = os.environ['SLURM_JOB_CPUS_PER_NODE']
         if is_integer(text): return int(text)
         else:
            n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0]
            return int(n) * int(N)
    else: return multiprocessing.cpu_count()
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
565046
def _generate_cpu_stats():
        
        cpu_name = urwid.Text("CPU Name N/A", align="center")
        try:
            cpu_name = urwid.Text(get_processor_name().strip(), align="center")
        except OSError:
            logging.info("CPU name not available")
        return [urwid.Text(('bold text', "CPU Detected"),
                           align="center"), cpu_name, urwid.Divider()]
852674
function cpuTemperature() {
  if (_windows) {
    return(NOT_SUPPORTED);
  }
  if (_linux) {
    return(NOT_SUPPORTED);
  }

  if (_darwin) {
    let result = {
      main: -1.0,
      cores: [],
      max: -1.0
    };
    let smc = require('../build/Release/smc');

    let cores = ['TC0P', 'TC1C', 'TC2C', 'TC3C', 'TC4C', 'TC5C', 'TC6C', 'TC7C', 'TC8C'];
    let sum = 0;
    let id = 0;
    cores.forEach(function(key) {
      let value = smc.get(key);
      if (id === 0) {
        if (value > 0) {
          result.main = value;
          result.max = value;
        }
        id = 1;
      } else {
        if (value > 0) {
          result.cores.push(value);
          sum = sum + value;
          if (value > result.max) result.max = value;
        }
      }
    });
    if (result.cores.length) {
      result.main = sum / result.cores.length;
    }

    return(result);
  }
}
419483
def all_host_infos():
    '''
        
    '''
    output = []
    output.append(["Operating system", os()])
    output.append(["CPUID information", cpu()])
    output.append(["CC information", compiler()])
    output.append(["JDK information", from_cmd("java -version")])
    output.append(["MPI information", from_cmd("mpirun -version")])
    output.append(["Scala information", from_cmd("scala -version")])
    output.append(["OpenCL headers", from_cmd(
        "find /usr/include|grep opencl.h")])
    output.append(["OpenCL libraries", from_cmd(
        "find /usr/lib/ -iname '*opencl*'")])
    output.append(["NVidia SMI", from_cmd("nvidia-smi -q")])
    output.append(["OpenCL Details", opencl()])
    return output
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}
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}
20185
def vmstats():
    '''
    
    '''
    def linux_vmstats():
        '''
        linux specific implementation of vmstats
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/vmstat', '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()
                ret[comps[0]] = _number(comps[1])
        return ret

    def generic_vmstats():
        '''
        generic implementation of vmstats
        note: works on FreeBSD, SunOS and OpenBSD (possibly others)
        '''
        ret = {}
        for line in __salt__['cmd.run']('vmstat -s').splitlines():
            comps = line.split()
            if comps[0].isdigit():
                ret[' '.join(comps[1:])] = _number(comps[0].strip())
        return ret

    # dict that returns a function that does the right thing per platform
    get_version = {
        'Linux': linux_vmstats,
        'FreeBSD': generic_vmstats,
        'OpenBSD': generic_vmstats,
        'SunOS': generic_vmstats,
        'AIX': generic_vmstats,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
107617
def _get_cpu_info_from_dmesg():
	'''
	
	'''
	# Just return {} if there is no dmesg
	if not DataSource.has_dmesg():
		return {}

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

	return _parse_dmesg_output(output)
137830
def getCPUuse(self):
        
        hz = os.sysconf('SC_CLK_TCK')
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            line = fp.readline()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        headers = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq', 'steal', 'guest']
        arr = line.split()
        if len(arr) > 1 and arr[0] == 'cpu':
            return dict(zip(headers[0:len(arr)], [(float(t) / hz) for t in arr[1:]]))
        return info_dict