--- GET CPU USAGE OF A REMOTE NODE ---
164544
public int getCpuUsage(String nodeID) {
		if (this.nodeID.equals(nodeID)) {
			return monitor.getTotalCpuPercent();
		}
		NodeDescriptor node = nodes.get(nodeID);
		return node == null ? 0 : node.cpu;
	}
390018
public int getTotalCpuPercent() {
		if (invalidMonitor.get()) {
			return 0;
		}
		long now = System.currentTimeMillis();
		int cpu;
		synchronized (Monitor.class) {
			if (now - cpuDetectedAt > cacheTimeout) {
				try {
					cachedCPU = detectTotalCpuPercent();
				} catch (Throwable cause) {
					logger.info("Unable to detect CPU usage!", cause);
					invalidMonitor.set(true);
				}
				cpuDetectedAt = now;
			}
			cpu = cachedCPU;
		}
		return cpu;
	}
925351
def get_ntp_peers(self):
        """"""
        ntp_stats = self.get_ntp_stats()

        return {
            ntp_peer.get("remote"): {}
            for ntp_peer in ntp_stats
            if ntp_peer.get("remote")
        }
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}
886851
def _add_cpu_usage(self, cur_read):
        

        for executor_id, cur_data in cur_read.items():
            if executor_id in self.executors_prev_read:
                prev_data = self.executors_prev_read[executor_id]
                prev_stats = prev_data['statistics']
                cur_stats = cur_data['statistics']
                # from sum of current cpus time subtract previous sum
                cpus_time_diff_s = cur_stats['cpus_user_time_secs']
                cpus_time_diff_s += cur_stats['cpus_system_time_secs']
                cpus_time_diff_s -= prev_stats['cpus_user_time_secs']
                cpus_time_diff_s -= prev_stats['cpus_system_time_secs']
                ts_diff = cur_stats['timestamp'] - prev_stats['timestamp']
                if ts_diff != 0:
                    cur_stats['cpus_utilisation'] = cpus_time_diff_s / ts_diff

            self.executors_prev_read[executor_id] = cur_read[executor_id]
1355134
public long getLastHeartbeatTime(String nodeID) {
		if (this.nodeID.equals(nodeID)) {
			return System.currentTimeMillis();
		}
		NodeDescriptor node = nodes.get(nodeID);
		return node == null ? 0 : node.cpuWhen;
	}
1230997
def get_resource(remote):
    """"""
    cached_resource = session.pop('cern_resource', None)
    if cached_resource:
        return cached_resource

    response = remote.get(REMOTE_APP_RESOURCE_API_URL)
    dict_response = get_dict_from_response(response)
    session['cern_resource'] = dict_response
    return dict_response
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
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
461983
public static host_cpu_core[] get(nitro_service client) throws Exception
	{
		host_cpu_core resource = new host_cpu_core();
		resource.validate("get");
		return (host_cpu_core[]) resource.get_resources(client);
	}
642288
public int getSize() {
		if (size < 0) {
			size = 0;
			for (byte[] cache: start) {
				size += new RemoteOneFileCache(cache).getSize();
			}
			for (byte[] cache: end) {
				size += new RemoteOneFileCache(cache).getSize();
			}
		}
		return size;
	}
796908
def determine_node(self):
        

        # Manually set node_type as simultaneous.
        if self.node_type == "simultaneous":
            if self.nat_type != "unknown":
                return "simultaneous"

        # Get IP of binding interface.
        unspecific_bind = ["0.0.0.0", "127.0.0.1", "localhost"]
        if self.passive_bind in unspecific_bind:
            lan_ip = get_lan_ip(self.interface)
        else:
            lan_ip = self.passive_bind

        # Passive node checks.
        if lan_ip is not None \
                and self.passive_port is not None and self.enable_forwarding:
            self.debug_print("Checking if port is forwarded.")

            # Check port isn't already forwarded.
            if is_port_forwarded(lan_ip, self.passive_port, "TCP",
                                 self.forwarding_servers):
                msg = "Port already forwarded. Skipping NAT traversal."
                self.debug_print(msg)

                self.forwarding_type = "forwarded"
                return "passive"
            else:
                self.debug_print("Port is not already forwarded.")

            # Most routers.
            try:
                self.debug_print("Trying UPnP")

                UPnP(self.interface).forward_port("TCP", self.passive_port,
                                                  lan_ip)

                if is_port_forwarded(lan_ip, self.passive_port, "TCP",
                                     self.forwarding_servers):
                    self.forwarding_type = "UPnP"
                    self.debug_print("Forwarded port with UPnP.")
                else:
                    self.debug_print("UPnP failed to forward port.")

            except Exception as e:
                # Log exception.
                error = parse_exception(e)
                log_exception(self.error_log_path, error)
                self.debug_print("UPnP failed to forward port.")

                # Apple devices.
                try:
                    self.debug_print("Trying NATPMP.")
                    NatPMP(self.interface).forward_port("TCP",
                                                        self.passive_port,
                                                        lan_ip)
                    if is_port_forwarded(lan_ip, self.passive_port, "TCP",
                                         self.forwarding_servers):
                        self.forwarding_type = "NATPMP"
                        self.debug_print("Port forwarded with NATPMP.")
                    else:
                        self.debug_print("Failed to forward port with NATPMP.")
                        self.debug_print("Falling back on TCP hole punching or"
                                         " proxying.")
                except Exception as e:
                    # Log exception
                    error = parse_exception(e)
                    log_exception(self.error_log_path, error)
                    self.debug_print("Failed to forward port with NATPMP.")

            # Check it worked.
            if self.forwarding_type != "manual":
                return "passive"

        # Fail-safe node types.
        if self.nat_type != "unknown":
            return "simultaneous"
        else:
            return "active"
666073
def usage(self, callback=None, errback=None, **kwargs):
        
        stats = Stats(self.config)
        return stats.usage(zone=self.zone, callback=callback, errback=errback,
                           **kwargs)
824113
private void readBufferAndLogMetrics(final Operation currentOp,
    final ByteBuffer rbuf, final MemcachedNode node) throws IOException {
    currentOp.readFromBuffer(rbuf);
    if (currentOp.getState() == OperationState.COMPLETE) {
      getLogger().debug("Completed read op: %s and giving the next %d "
        + "bytes", currentOp, rbuf.remaining());
      Operation op = node.removeCurrentReadOp();
      assert op == currentOp : "Expected to pop " + currentOp + " got "
        + op;

      if (op.hasErrored()) {
        metrics.markMeter(OVERALL_RESPONSE_FAIL_METRIC);
      } else {
        metrics.markMeter(OVERALL_RESPONSE_SUCC_METRIC);
      }
    } else if (currentOp.getState() == OperationState.RETRY) {
      handleRetryInformation(currentOp.getErrorMsg());
      getLogger().debug("Reschedule read op due to NOT_MY_VBUCKET error: "
        + "%s ", currentOp);
      ((VBucketAware) currentOp).addNotMyVbucketNode(
        currentOp.getHandlingNode());
      Operation op = node.removeCurrentReadOp();
      assert op == currentOp : "Expected to pop " + currentOp + " got "
        + op;

      retryOperation(currentOp);
      metrics.markMeter(OVERALL_RESPONSE_RETRY_METRIC);
    }
  }
892414
function getLoad() {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let loads = os.loadavg().map(function (x) { return x / util.cores(); });
      let avgload = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
      let result = {};

      let now = Date.now() - _current_cpu.ms;
      if (now >= 200) {
        _current_cpu.ms = Date.now();
        const cpus = os.cpus();
        let totalUser = 0;
        let totalSystem = 0;
        let totalNice = 0;
        let totalIrq = 0;
        let totalIdle = 0;
        let cores = [];
        _corecount = cpus.length;

        for (let i = 0; i < _corecount; i++) {
          const cpu = cpus[i].times;
          totalUser += cpu.user;
          totalSystem += cpu.sys;
          totalNice += cpu.nice;
          totalIdle += cpu.idle;
          totalIrq += cpu.irq;
          let tmp_tick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
          let tmp_load = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
          let tmp_user = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
          let tmp_system = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
          let tmp_nice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
          let tmp_idle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
          let tmp_irq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
          _cpus[i] = cpu;
          _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].idle;
          _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq;
          _cpus[i].currentTick = _cpus[i].totalTick - tmp_tick;
          _cpus[i].load = (_cpus[i].totalLoad - tmp_load);
          _cpus[i].load_user = (_cpus[i].user - tmp_user);
          _cpus[i].load_system = (_cpus[i].sys - tmp_system);
          _cpus[i].load_nice = (_cpus[i].nice - tmp_nice);
          _cpus[i].load_idle = (_cpus[i].idle - tmp_idle);
          _cpus[i].load_irq = (_cpus[i].irq - tmp_irq);
          cores[i] = {};
          cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
          cores[i].load_user = _cpus[i].load_user / _cpus[i].currentTick * 100;
          cores[i].load_system = _cpus[i].load_system / _cpus[i].currentTick * 100;
          cores[i].load_nice = _cpus[i].load_nice / _cpus[i].currentTick * 100;
          cores[i].load_idle = _cpus[i].load_idle / _cpus[i].currentTick * 100;
          cores[i].load_irq = _cpus[i].load_irq / _cpus[i].currentTick * 100;
          cores[i].raw_load = _cpus[i].load;
          cores[i].raw_load_user = _cpus[i].load_user;
          cores[i].raw_load_system = _cpus[i].load_system;
          cores[i].raw_load_nice = _cpus[i].load_nice;
          cores[i].raw_load_idle = _cpus[i].load_idle;
          cores[i].raw_load_irq = _cpus[i].load_irq;
        }
        let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalIdle;
        let totalLoad = totalUser + totalSystem + totalNice + totalIrq;
        let currentTick = totalTick - _current_cpu.tick;
        result = {
          avgload: avgload,
          currentload: (totalLoad - _current_cpu.load) / currentTick * 100,
          currentload_user: (totalUser - _current_cpu.user) / currentTick * 100,
          currentload_system: (totalSystem - _current_cpu.system) / currentTick * 100,
          currentload_nice: (totalNice - _current_cpu.nice) / currentTick * 100,
          currentload_idle: (totalIdle - _current_cpu.idle) / currentTick * 100,
          currentload_irq: (totalIrq - _current_cpu.irq) / currentTick * 100,
          raw_currentload: (totalLoad - _current_cpu.load),
          raw_currentload_user: (totalUser - _current_cpu.user),
          raw_currentload_system: (totalSystem - _current_cpu.system),
          raw_currentload_nice: (totalNice - _current_cpu.nice),
          raw_currentload_idle: (totalIdle - _current_cpu.idle),
          raw_currentload_irq: (totalIrq - _current_cpu.irq),
          cpus: cores
        };
        _current_cpu = {
          user: totalUser,
          nice: totalNice,
          system: totalSystem,
          idle: totalIdle,
          irq: totalIrq,
          tick: totalTick,
          load: totalLoad,
          ms: _current_cpu.ms,
          currentload: result.currentload,
          currentload_user: result.currentload_user,
          currentload_system: result.currentload_system,
          currentload_nice: result.currentload_nice,
          currentload_idle: result.currentload_idle,
          currentload_irq: result.currentload_irq,
          raw_currentload: result.raw_currentload,
          raw_currentload_user: result.raw_currentload_user,
          raw_currentload_system: result.raw_currentload_system,
          raw_currentload_nice: result.raw_currentload_nice,
          raw_currentload_idle: result.raw_currentload_idle,
          raw_currentload_irq: result.raw_currentload_irq,
        };
      } else {
        let cores = [];
        for (let i = 0; i < _corecount; i++) {
          cores[i] = {};
          cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
          cores[i].load_user = _cpus[i].load_user / _cpus[i].currentTick * 100;
          cores[i].load_system = _cpus[i].load_system / _cpus[i].currentTick * 100;
          cores[i].load_nice = _cpus[i].load_nice / _cpus[i].currentTick * 100;
          cores[i].load_idle = _cpus[i].load_idle / _cpus[i].currentTick * 100;
          cores[i].load_irq = _cpus[i].load_irq / _cpus[i].currentTick * 100;
          cores[i].raw_load = _cpus[i].load;
          cores[i].raw_load_user = _cpus[i].load_user;
          cores[i].raw_load_system = _cpus[i].load_system;
          cores[i].raw_load_nice = _cpus[i].load_nice;
          cores[i].raw_load_idle = _cpus[i].load_idle;
          cores[i].raw_load_irq = _cpus[i].load_irq;
        }
        result = {
          avgload: avgload,
          currentload: _current_cpu.currentload,
          currentload_user: _current_cpu.currentload_user,
          currentload_system: _current_cpu.currentload_system,
          currentload_nice: _current_cpu.currentload_nice,
          currentload_idle: _current_cpu.currentload_idle,
          currentload_irq: _current_cpu.currentload_irq,
          raw_currentload: _current_cpu.raw_currentload,
          raw_currentload_user: _current_cpu.raw_currentload_user,
          raw_currentload_system: _current_cpu.raw_currentload_system,
          raw_currentload_nice: _current_cpu.raw_currentload_nice,
          raw_currentload_idle: _current_cpu.raw_currentload_idle,
          raw_currentload_irq: _current_cpu.raw_currentload_irq,
          cpus: cores
        };
      }
      resolve(result);
    });
  });
}
328170
def retrieveVals(self):
        """"""
        ntpinfo = NTPinfo()
        ntpstats = ntpinfo.getHostOffsets(self._remoteHosts)
        if ntpstats:
            for host in self._remoteHosts:
                hostkey = re.sub('\.', '_', host)
                hoststats = ntpstats.get(host)
                if hoststats:
                    if self.hasGraph('ntp_host_stratums'):
                        self.setGraphVal('ntp_host_stratums', hostkey, 
                                         hoststats.get('stratum'))
                    if self.hasGraph('ntp_host_offsets'):
                        self.setGraphVal('ntp_host_offsets', hostkey, 
                                         hoststats.get('offset'))
                    if self.hasGraph('ntp_host_delays'):
                        self.setGraphVal('ntp_host_delays', hostkey, 
                                         hoststats.get('delay'))
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