Class: Rmemlimit

Inherits:
Object
  • Object
show all
Defined in:
lib/rmemlimit.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.gc_mbObject

Returns the value of attribute gc_mb.



4
5
6
# File 'lib/rmemlimit.rb', line 4

def gc_mb
  @gc_mb
end

.kill_mbObject

Returns the value of attribute kill_mb.



4
5
6
# File 'lib/rmemlimit.rb', line 4

def kill_mb
  @kill_mb
end

.sleep_timeObject

Returns the value of attribute sleep_time.



4
5
6
# File 'lib/rmemlimit.rb', line 4

def sleep_time
  @sleep_time
end

Class Method Details

.gcthreadObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rmemlimit.rb', line 6

def gcthread
  if !@gcthread || !@gcthread.alive?
    @gcthread = Thread.new do
      begin
        loop do
          mb = rss_mb
          if kill_mb && mb > kill_mb
            STDERR.puts "#{self}: Exceeded kill memory limit (#{mb} > #{kill_mb} MB)"
            Process.kill(9, $$)
          elsif gc_mb && mb > gc_mb
            run_gc
          end
          sleep sleep_time
        end
      rescue
        puts "Exception: #{$!.class} #{$!}"
      end
    end
  end
end

.pagesizeObject



33
34
35
# File 'lib/rmemlimit.rb', line 33

def pagesize
  4096
end

.rss_kbObject



41
42
43
# File 'lib/rmemlimit.rb', line 41

def rss_kb
  pagesize * (File.read("/proc/#{$$}/statm").split(' ')[1].to_i rescue 0) >> 10
end

.rss_mbObject



37
38
39
# File 'lib/rmemlimit.rb', line 37

def rss_mb
  rss_kb >> 10
end

.run_gcObject



27
28
29
30
31
# File 'lib/rmemlimit.rb', line 27

def run_gc
  GC.enable
  GC.start
  GC.disable
end

.setupObject



45
46
47
48
49
50
51
52
53
54
# File 'lib/rmemlimit.rb', line 45

def setup
  self.sleep_time ||= 1
  self.gc_mb = ENV['RUBY_GC_MB'].to_i if ENV['RUBY_GC_MB']
  if ENV['RUBY_KILL_MB']
    self.kill_mb = ENV['RUBY_KILL_MB'].to_i
    self.kill_mb = nil unless Rmemlimit.kill_mb > 1
  end
  GC.disable if gc_mb
  self.gcthread
end