/
harakiri.rb
58 lines (49 loc) · 1.29 KB
/
harakiri.rb
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module Rack
# Simple Rack Middleware to kill Unicorns after X requests.
#
# Use as follows in e.g. your rackup File:
#
# Rack::Harakiri.after = 100
# use Rack::Harakiri
#
# Then the Unicorn will commit suicide after 100 requests (50 is the default).
#
# The Master Unicorn process forks a new child Unicorn to replace the old one.
#
class Harakiri
# Set the amount of requests before the Unicorn commits Harakiri.
#
class << self
attr_accessor :after
end
def initialize app
@app = app
@requests = 0
@quit_after_requests = self.class.after || 50
end
# #call interface method.
#
# Harakiri is a middleware, so it forwards the the app or
# the next middleware after checking if it is time to honorably retire.
#
def call env
harakiri
@app.call env
end
# Checks to see if it is time to honorably retire.
#
# If yes, kills itself (Unicorn will answer the request, honorably).
#
# Note: Sends its process a QUIT signal if it is time.
#
def harakiri
@requests = @requests + 1
Process.kill(:QUIT, Process.pid) if harakiri?
end
# Is it time to honorably retire?
#
def harakiri?
@requests >= @quit_after_requests
end
end
end