Skip to content

Instantly share code, notes, and snippets.

@takeru
Created April 15, 2010 03:52
Show Gist options
  • Select an option

  • Save takeru/366659 to your computer and use it in GitHub Desktop.

Select an option

Save takeru/366659 to your computer and use it in GitHub Desktop.
require "open-uri"
require "thread"
require "monitor"
$stdout.sync = true
class GaeWarm2
def initialize
@monitor = Monitor.new
@results = {}
@threads = []
end
def sync_puts(s)
@monitor.synchronize do
puts(s)
end
end
def current_time
Time.now - @start_time
end
def record_result(status, time)
@monitor.synchronize do
window_no = (current_time / @window_sec).floor
unless @results[window_no]
@results.keys.sort.each do |n|
rec = @results[n]
s = "%3d: threads=%3d %s" % [n, rec[:threads], s]
status_list = ((rec.keys-[:threads])+[200,500]).uniq.sort
status_list.each do |st|
rec[st] ||= {}
rec[st][:count] ||= 0
rec[st][:time ] ||= 0.0
time_per_req = rec[st][:count]==0 ? 0 : rec[st][:time]/rec[st][:count]
s << " | %3d=%4d(%4.1f)" % [st, rec[st][:count], time_per_req]
end
sync_puts(s)
end
sync_puts("--------")
end
@results[window_no] ||= {}
@results[window_no][status] ||= {}
@results[window_no][status][:count] ||= 0
@results[window_no][status][:count] += 1
@results[window_no][status][:time ] ||= 0.0
@results[window_no][status][:time ] += time
@results[window_no][:threads] ||= @threads.size
# sync_puts("window_no=#{window_no}")
end
nil
end
def send_request(thread_no, counter)
start_time = Time.now
begin
url = @url.kind_of?(Proc) ? @url.call : @url
open(url) do |f|
f.read
record_result(f.status[0].to_i, Time.now-start_time)
end
rescue OpenURI::HTTPError => e
record_result(e.io.status[0].to_i, Time.now-start_time)
end
end
def start_thread(_thread_no)
Thread.new(_thread_no) do |thread_no|
begin
counter = 0
loop{
counter += 1
send_request(thread_no, counter)
}
rescue => e
puts "#{e.inspect}\n #{e.backtrace.join("\n ")}"
end
end
end
def start
@thread_start_interval = 2.0
@window_sec = 10.0
@thread_max = 50
require 'optparse'
ARGV.options {|opt|
opt.on('-u URL' ){|v| @url = v }
opt.on('-i INTERVAL' ){|v| @thread_start_interval = v.to_f }
opt.on('-t THREADS_MAX' ){|v| @thread_max = v.to_i }
opt.on('-w WINDOW_SEC' ){|v| @window_sec = v.to_i }
opt.parse!
}
# jruby script/gae_warm2.rb -u 'http://000.latest.xxxx.appspot.com/task/task/ping?sleep_sec=eval{rand(8)/10.0+(rand(10)==0 ? 2 : 0)}' -i 1.0
if @url =~ /(.+=)eval\{(.+)\}/
base_url = $1
code = $2
@url = Proc.new{ base_url + eval(code).to_s }
end
unless @url
raise "url is nil"
end
@start_time = Time.now
loop_counter = 0
loop{
loop_counter += 1
th = start_thread(loop_counter)
@threads << th
sleep(@thread_start_interval)
break if @thread_max <= @threads.count
}
@threads.each{|th| th.join }
end
end
GaeWarm2.new.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment