require 'socket' require_relative '../sysinfo' module Remon module Metrics class System CpuStat = Struct.new(:used, :idle, :iowait) def memory m = {} IO.foreach("/proc/meminfo").first(6).each do |line| split = line.split(":") key = split[0].to_sym value = split[1].split[0] m[key] = value end free = m[:MemAvailable].to_i || (m[:MemFree].to_i + m[:Buffers].to_i + m[:Cached].to_i) total = m[:MemTotal].to_i used = (1 - (free.to_f / total)).round(4) end def loadavg File.open("/proc/loadavg") { |f| f.gets(" ").to_f } end def loadavg_normalized (loadavg / Sysinfo.normalized_cores).round 2 end def uptime File.open('/proc/uptime') { |f| f.gets(" ").to_f } end def cpu_stat stat = File.open('/proc/stat', 'r') { |f| f.readline } @stat_regex ||= /^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/ mdata = stat.match(@stat_regex) if mdata user, nice, system = [mdata[1], mdata[2], mdata[3]].map { |i| i.to_i } cpu = CpuStat.new cpu.used = user + nice + system cpu.idle = mdata[4].to_i cpu.iowait = mdata[5].to_i return cpu else return nil end end def cpu_usage(old_cpu, new_cpu) used = new_cpu.used - old_cpu.used idle = new_cpu.idle - old_cpu.idle iowait = new_cpu.iowait - old_cpu.iowait total = used + idle + iowait used_frac = (used.to_f / total).round 4 iowait_frac = (iowait.to_f / total).round 4 [used_frac, iowait_frac] end end end end