Skip to content

Instantly share code, notes, and snippets.

@adamcooke
Forked from wmoxam/gist:41713
Created October 19, 2009 18:59
Show Gist options
  • Save adamcooke/213628 to your computer and use it in GitHub Desktop.
Save adamcooke/213628 to your computer and use it in GitHub Desktop.
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.
#!/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
@bhushangahire
Copy link

How do you run it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment