adamcooke (owner)

Fork Of

Forks

Revisions

gist: 213628 Download_button fork
public
Description:
Passenger worker monitor to kill workers which use too much RAM. Needs to sudo otherwise RSS figures aren't available. Daemonized with Daemons gem for easy of use.
Public Clone URL: git://gist.github.com/213628.git
Embed All Files: show embed
Text only #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env ruby
 
require 'rubygems'
require 'daemons'
 
Daemons.run_proc('PassengerMonitor') do
 
  command = 'sudo passenger-memory-stats'
  memory_limit = 250
 
  def running?(pid)
    begin
      return Process.getpgid(pid) != -1
    rescue Errno::ESRCH
      return false
   end
  end
 
  loop do
    `#{command}`.each_line do |line|
      next unless /(\d+)\s+\d+\s+(\d+\.\d+)\s+MB\s+(\d+\.\d+)\s+MB\s+Rails:/.match(line)
      all, pid, vm_size, private = $~.to_a
      if private.to_i > memory_limit
        puts "#{Time.now}: Killing #{pid}, memory usage == #{private}"
        Process.kill("SIGUSR1", pid.to_i)
        puts "Finished kill attempt. Sleeping for 20 seconds to give it time to die..."
        sleep 20
        if running?(pid.to_i)
          puts "Process is still running - die bitch"
          Process.kill("KILL", pid.to_i)
        end
      else
        puts "Process ##{pid} is not above limit (#{private}MB)"
      end
    end
    sleep 120
  end
 
end