Class: Qless::Middleware::MemoryUsageMonitor

Inherits:
Module
  • Object
show all
Defined in:
lib/qless/middleware/memory_usage_monitor.rb

Overview

Monitors the memory usage of the Qless worker, instructing it to shutdown when memory exceeds the given :max_memory threshold.

Constant Summary collapse

SHELL_OUT_FOR_MEMORY =
-> do
  # Taken from:
  # http://stackoverflow.com/a/4133642/29262
  Integer(`ps -o rss= -p #{Process.pid}`)
end

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ MemoryUsageMonitor

Returns a new instance of MemoryUsageMonitor.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/qless/middleware/memory_usage_monitor.rb', line 7

def initialize(options)
  max_memory = options.fetch(:max_memory)

  module_eval do
    job_counter = 0

    define_method :around_perform do |job|
      job_counter += 1

      begin
        super(job)
      ensure
        current_mem = MemoryUsageMonitor.current_usage_in_kb
        if current_mem > max_memory
          log(:info, "Exiting after job #{job_counter} since current memory " \
                     "(#{current_mem} KB) has exceeded max allowed memory " \
                     "(#{max_memory} KB).")
          shutdown
        end
      end
    end
  end
end