Skip to content

Instantly share code, notes, and snippets.

@arya
Created October 9, 2009 16:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arya/206167 to your computer and use it in GitHub Desktop.
Save arya/206167 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment