public
Last active

  • Download Gist
gistfile1.rb
Ruby
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
class RackProctitle
def initialize(app, options = nil)
@app = app
@prefix = options.delete(:prefix) if options
@revision = APPLICATION_VERSION if defined?(APPLICATION_VERSION)
@mutex = Mutex.new
@titles = []
@request_threads = []
@queue_length = 0
@request_count = 0
 
@updater_thread = Thread.new do
while true
@mutex.synchronize do
set_request_list_title
end
sleep 0.5
end
end
end
 
def call(env)
Thread.current[:request_str] = ((env["REQUEST_URI"].nil? || env["REQUEST_URI"].empty?) ? "/" : env["REQUEST_URI"]).split("?", 2)[0]
Thread.current[:arrived_at] = Time.now.to_f
@mutex.synchronize do
@request_threads.push(Thread.current)
@queue_length += 1
set_request_list_title
end
begin
@app.call(env)
ensure
@mutex.synchronize do
@queue_length -= 1
@request_count += 1
 
@last_time = Time.now.to_f - Thread.current[:arrived_at].to_f
@last_request_str = Thread.current[:request_str].to_s
 
@request_threads.delete(Thread.current)
set_request_list_title
end
end
end
 
protected
def set_request_list_title
@title = if @request_threads.empty?
idle_message
else
now = Time.now.to_f
list = @request_threads.inject([]) do |str, thread|
str << "#{time_delta_abbriv(now - thread[:arrived_at])} #{thread[:request_str]}"
end.join(" | ")
"handling #{list}"
end
update_process_title
end
 
def idle_message
str = "idle#{' '*20}"
str << "[last #{time_delta_abbriv(@last_time)} #{@last_request_str}]" if @last_time && @last_request_str
str
end
 
def update_process_title
title = "#{@prefix || 'rack'}"
title << "/#{@revision}" if @revision
title << " ["
title << "#{@queue_length}/"
title << "#{@request_count}"
title << "]: #{@title}"
$0 = title
end
 
def time_delta_abbriv(delta)
if delta < 60
"%.1fs" % delta
elsif delta < 3600
"#{delta.to_i / 60}m#{delta.to_i % 60}s"
elsif delta < 86400
"#{delta.to_i / 3600}h#{(delta.to_i % 3600) / 60}m"
else
"#{delta.to_i / 86400}d#{(delta.to_i % 86400) / 3600}h"
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.