class GetProcessMem

Cribbed from Unicorn Worker Killer, thanks!

Constants

CONVERSION
GB_TO_BYTE
KB_TO_BYTE
MB_TO_BYTE
ROUND_UP
VERSION

Attributes

pid[R]

Public Class Methods

new(pid = Process.pid) click to toggle source
# File lib/get_process_mem.rb, line 14
def initialize(pid = Process.pid)
  @process_file = Pathname.new "/proc/#{pid}/smaps"
  @pid          = pid
  @linux        = @process_file.exist?
end

Public Instance Methods

bytes() click to toggle source
# File lib/get_process_mem.rb, line 24
def bytes
  memory =   linux_memory if linux?
  memory ||= ps_memory
end
gb(b = bytes) click to toggle source
# File lib/get_process_mem.rb, line 37
def gb(b = bytes)
  (b/BigDecimal.new(GB_TO_BYTE.to_s)).to_f
end
inspect() click to toggle source
# File lib/get_process_mem.rb, line 41
def inspect
  b = bytes
  "#<#{self.class}:0x%08x @mb=#{ mb b } @gb=#{ gb b } @kb=#{ kb b } @bytes=#{b}>" % (object_id * 2)
end
kb(b = bytes) click to toggle source
# File lib/get_process_mem.rb, line 29
def kb(b = bytes)
  (b/BigDecimal.new(KB_TO_BYTE.to_s)).to_f
end
linux?() click to toggle source
# File lib/get_process_mem.rb, line 20
def linux?
  @linux
end
linux_memory(file = @process_file) click to toggle source

linux stores memory info in a file “/proc/#{pid}/smaps” If it’s available it uses less resources than shelling out to ps

# File lib/get_process_mem.rb, line 56
def linux_memory(file = @process_file)
  lines = file.each_line.select {|line| line.match /^Rss/ }
  return if lines.empty?
  lines.reduce(0) do |sum, line|
    m = line.match(/(\d*\.{0,1}\d+)\s+(\w\w)/)
    next unless m
    value = BigDecimal.new(m[1]) + ROUND_UP
    unit  = m[2].downcase
    sum  += CONVERSION[unit] * value
    sum
  end
rescue Errno::EACCES
  0
end
mb(b = bytes) click to toggle source
# File lib/get_process_mem.rb, line 33
def mb(b = bytes)
  (b/BigDecimal.new(MB_TO_BYTE.to_s)).to_f
end
mem_type() click to toggle source
# File lib/get_process_mem.rb, line 46
def mem_type
  @mem_type
end
mem_type=(mem_type) click to toggle source
# File lib/get_process_mem.rb, line 50
def mem_type=(mem_type)
  @mem_type = mem_type.downcase
end

Private Instance Methods

ps_memory() click to toggle source

Pull memory from ‘ps` command, takes more resources and can freeze in low memory situations

# File lib/get_process_mem.rb, line 75
def ps_memory
  KB_TO_BYTE * BigDecimal.new(`ps -o rss= -p #{pid}`)
end