Skip to content

Instantly share code, notes, and snippets.

@jsierles
Created November 27, 2008 18:02
Show Gist options
  • Save jsierles/29838 to your computer and use it in GitHub Desktop.
Save jsierles/29838 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Find bloating passengers and kill them gracefully. Run from cron every minute.
#
# required for passenger since cron has no environment
ENV['HTTPD'] = 'httpd'
MEM_LIMIT = ARGV[0] || 500
module Process
def self.running?(pid)
begin
return Process.getpgid(pid) != -1
rescue Errno::ESRCH
return false
end
end
end
`passenger-memory-stats`.each_line do |line|
if line =~ /Rails: /
parts = line.split
pid, private_dirty_rss = parts[0].to_i, parts[4].to_f
if private_dirty_rss > MEM_LIMIT.to_i
puts "Found bloater #{pid} with size #{private_dirty_rss.to_s}"
puts "Killing with SIGUSR1 (graceful)..."
Process.kill("SIGUSR1", pid)
puts "Finished kill attempt. Sleeping for 8 seconds..."
sleep 8
if Process.running?(pid)
puts "Process is still running, so killing with extreme predjudice!"
Process.kill("TERM", pid)
end
puts "Done!"
end
end
end
@skrat
Copy link

skrat commented Nov 30, 2010

I could be reduced to following bash script:

for i in passenger-memory-stats 2> /dev/null |grep current|awk '{if ($2 > 260) print $1}'; do
kill -USR1 $i
sleep 3
kill -TERM $i
sleep 3
kill -KILL $i
done

@skrat
Copy link

skrat commented Nov 30, 2010

all of them suffer from one issue, if meanwhile new process with that ID is spawned, it will get killed.

@envygeeks
Copy link

ENV['HTTPD'] = 'httpd' < Why set that on ENV if you just overwrite it even if they set it? 😉

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