Created
February 15, 2013 07:34
-
-
Save lloydmeta/4958987 to your computer and use it in GitHub Desktop.
Using OOBGC with Unicorn along with a UnicornKiller that kills workers if they use too much memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#--- Credit: http://kzk9.net/unicorn-configuration-on-heroku | |
# config.ru | |
# This file is used by Rack-based servers to start the application. | |
require ::File.expand_path('../config/environment', __FILE__) | |
# Unicorn self-process killer | |
require ::File.expand_path('../lib/unicorn/unicorn_killer', __FILE__) | |
use UnicornKiller::MaxRequests, 10240 + Random.rand(10240) #adjust as required | |
use UnicornKiller::Oom, 96 * 1024 + Random.rand(32) * 1024 #adjust as required | |
# Out-Of-Band GC | |
require 'unicorn/oob_gc' | |
use Unicorn::OobGC | |
run App::Application | |
#------------- | |
# lib/unicorn/unicorn_killer.rb | |
# from https://gist.github.com/1258681 | |
module UnicornKiller | |
module Kill | |
def quit | |
sec = (Time.now - @process_start).to_i | |
warn "#{self.class} send SIGQUIT (pid: #{Process.pid})\talive: #{sec} sec" | |
Process.kill :QUIT, Process.pid | |
end | |
end | |
class Oom | |
include Kill | |
def initialize(app, memory_size= 512 * 1024, check_cycle = 16) | |
@app = app | |
@memory_size = memory_size | |
@check_cycle = check_cycle | |
@check_count = 0 | |
end | |
def rss | |
`ps -o rss= -p #{Process.pid}`.to_i | |
end | |
def call(env) | |
@process_start ||= Time.now | |
if (@check_count += 1) % @check_cycle == 0 | |
@check_count = 0 | |
quit if rss > @memory_size | |
end | |
@app.call env | |
end | |
end | |
class MaxRequests | |
include Kill | |
def initialize(app, max_requests = 1000) | |
@app = app | |
@max_requests = max_requests | |
end | |
def call(env) | |
@process_start ||= Time.now | |
quit if (@max_requests -= 1) == 0 | |
@app.call env | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment