Class: WorkerKiller::MemoryLimiter

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min:, max:, check_cycle: 16, verbose: false) ⇒ MemoryLimiter

Returns a new instance of MemoryLimiter.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/worker_killer/memory_limiter.rb', line 8

def initialize(min:, max:, check_cycle: 16, verbose: false)
  if min
    # set static memory limits
    @min = min
    @max = max
  else
    # prepare for relative memory limits
    @max_percent = max
  end

  @check_cycle = check_cycle
  @check_count = 0
  @verbose = verbose
end

Instance Attribute Details

#check_cycleObject (readonly)

Returns the value of attribute check_cycle.



6
7
8
# File 'lib/worker_killer/memory_limiter.rb', line 6

def check_cycle
  @check_cycle
end

#limitObject (readonly)

Returns the value of attribute limit.



6
7
8
# File 'lib/worker_killer/memory_limiter.rb', line 6

def limit
  @limit
end

#maxObject (readonly)

Returns the value of attribute max.



6
7
8
# File 'lib/worker_killer/memory_limiter.rb', line 6

def max
  @max
end

#minObject (readonly)

Returns the value of attribute min.



6
7
8
# File 'lib/worker_killer/memory_limiter.rb', line 6

def min
  @min
end

#started_atObject (readonly)

Returns the value of attribute started_at.



6
7
8
# File 'lib/worker_killer/memory_limiter.rb', line 6

def started_at
  @started_at
end

Instance Method Details

#checkObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/worker_killer/memory_limiter.rb', line 23

def check
  @started_at ||= Time.now
  @check_count += 1


  return nil if (@check_count % @check_cycle) != 0

  rss = GetProcessMem.new.bytes

  # initialize relative memory limits on first check
  if @limit.nil?
    if min.nil?
      set_limits(rss, rss + rss * @max_percent)
    else
      set_limits(min, min + WorkerKiller.randomize(max - min + 1))
    end
  end

  do_check(rss)
end

#do_check(rss) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/worker_killer/memory_limiter.rb', line 44

def do_check(rss)
  rss_mb = (rss / 1024 / 1024).round(1)

  if @verbose
    logger.info "#{self.class}: worker (pid: #{Process.pid}) using #{rss_mb} MB (of #{@limit_mb} MB)"
  end
  @check_count = 0

  return false if rss <= @limit

  logger.warn "#{self.class}: worker (pid: #{Process.pid}) exceeds memory limit (#{rss_mb} MB > #{@limit_mb} MB)"

  true
end

#loggerObject



66
67
68
# File 'lib/worker_killer/memory_limiter.rb', line 66

def logger
  WorkerKiller.configuration.logger
end

#set_limits(min, max) ⇒ Object



59
60
61
62
63
64
# File 'lib/worker_killer/memory_limiter.rb', line 59

def set_limits(min, max)
  @min = min
  @limit = max
  @max ||= max
  @limit_mb = (@limit / 1024 / 1024).round(1)
end