lib/tracebin/system_health_sample.rb in tracebin-0.0.10 vs lib/tracebin/system_health_sample.rb in tracebin-0.0.11

- old
+ new

@@ -1,12 +1,14 @@ module Tracebin class SystemHealthSample + include ::Tracebin::Helpers + DATA_TYPE = 'system_health_sample'.freeze def initialize(options = {}) @process = options[:process] || :web - @sampled_at = Time.new + @sampled_at = timestamp_string @metrics = sample_metrics end def payload { @@ -137,13 +139,15 @@ if darwin? info[:model_name] = get_sysctl_value('machdep.cpu.brand_string') info[:processor_count] = get_sysctl_value('hw.packages').to_i info[:core_count] = get_sysctl_value('hw.physicalcpu_max').to_i, info[:logical_cpu_count] = get_sysctl_value('hw.logicalcpu_max').to_i + info[:usage] = get_darwin_cpu_usage elsif linux? proc_string = read_proc('/proc/cpuinfo') info = parse_proc_cpuinfo_string(proc_string) + info[:usage] = get_linux_cpu_usage end info end def get_sysctl_value(key) @@ -180,8 +184,27 @@ model_name: model_name, processor_count: units.count, core_count: cores.count, logical_cpu_count: threads.count } + end + + def get_darwin_cpu_usage + iostat = `iostat 2>/dev/null`.split(/\n+/).map do |line| + line.strip.split(/\s+/) + end + cpu_idx = iostat[0].index('cpu') * 3 + user, sys, idle = iostat[2].map(&:to_f)[cpu_idx..cpu_idx + 2] + + (user + sys) / (user + sys + idle) + end + + def get_linux_cpu_usage + proc_data = File.readlines('/proc/stat').grep(/^cpu /).first.split(" ") + + usage = proc_data[1].to_i + proc_data[2].to_i + proc_data[3].to_i + total = usage + proc_data[4].to_i + + usage.to_f / total.to_f end end end