Sha256: 3bbabc4aab7f35c9efb8e70aff308be7beae06f1095f6c32fa8d1cbe880b3a2c

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
remon-0.1.0 lib/remon/metrics/system.rb