test_linux_all_tcp_listen_stats_leak: fix for 1.8
[raindrops.git] / lib / raindrops / watcher.rb
blobf2899708825aa62ea2cdc524bcf37950e8a42fc7
1 # -*- encoding: binary -*-
2 require "thread"
3 require "time"
4 require "socket"
5 require "rack"
6 require "aggregate"
8 # Raindrops::Watcher is a stand-alone Rack application for watching
9 # any number of TCP and UNIX listeners (all of them by default).
11 # It depends on the {Aggregate RubyGem}[http://rubygems.org/gems/aggregate]
13 # In your Rack config.ru:
15 #    run Raindrops::Watcher(options = {})
17 # It takes the following options hash:
19 # - :listeners - an array of listener names, (e.g. %w(0.0.0.0:80 /tmp/sock))
20 # - :delay - interval between stats updates in seconds (default: 1)
22 # Raindrops::Watcher is compatible any thread-safe/thread-aware Rack
23 # middleware.  It does not work well with multi-process web servers
24 # but can be used to monitor them.  It consumes minimal resources
25 # with the default :delay.
27 # == HTTP endpoints
29 # === GET /
31 # Returns an HTML summary listing of all listen interfaces watched on
33 # === GET /active/$LISTENER.txt
35 # Returns a plain text summary + histogram with X-* HTTP headers for
36 # active connections.
38 # e.g.: curl http://example.com/active/0.0.0.0%3A80.txt
40 # === GET /active/$LISTENER.html
42 # Returns an HTML summary + histogram with X-* HTTP headers for
43 # active connections.
45 # e.g.: curl http://example.com/active/0.0.0.0%3A80.html
47 # === GET /queued/$LISTENER.txt
49 # Returns a plain text summary + histogram with X-* HTTP headers for
50 # queued connections.
52 # e.g.: curl http://example.com/queued/0.0.0.0%3A80.txt
54 # === GET /queued/$LISTENER.html
56 # Returns an HTML summary + histogram with X-* HTTP headers for
57 # queued connections.
59 # e.g.: curl http://example.com/queued/0.0.0.0%3A80.html
61 # === GET /tail/$LISTENER.txt?active_min=1&queued_min=1
63 # Streams chunked a response to the client.
64 # Interval is the preconfigured +:delay+ of the application (default 1 second)
66 # The response is plain text in the following format:
68 #   ISO8601_TIMESTAMP LISTENER_NAME ACTIVE_COUNT QUEUED_COUNT LINEFEED
70 # Query parameters:
72 # - active_min - do not stream a line until this active count is reached
73 # - queued_min - do not stream a line until this queued count is reached
75 # == Response headers (mostly the same as Raindrops::LastDataRecv)
77 # - X-Count   - number of requests received
78 # - X-Last-Reset - date since the last reset
80 # The following headers are only present if X-Count is greater than one.
82 # - X-Min     - lowest last_data_recv time recorded (in milliseconds)
83 # - X-Max     - highest last_data_recv time recorded (in milliseconds)
84 # - X-Mean    - mean last_data_recv time recorded (rounded, in milliseconds)
85 # - X-Std-Dev - standard deviation of last_data_recv times
86 # - X-Outliers-Low - number of low outliers (hopefully many!)
87 # - X-Outliers-High - number of high outliers (hopefully zero!)
89 # = Demo Server
91 # There is a server running this app at http://raindrops-demo.bogomips.org/
92 # The Raindrops::Middleware demo is also accessible at
93 #   http://raindrops-demo.bogomips.org/_raindrops
95 # The demo server is only limited to 30 users, so be sure not to abuse it
96 # by using the /tail/ endpoint too much.
97 class Raindrops::Watcher
98   # :stopdoc:
99   attr_reader :snapshot
100   include Rack::Utils
101   include Raindrops::Linux
103   def initialize(opts = {})
104     @tcp_listeners = @unix_listeners = nil
105     if l = opts[:listeners]
106       tcp, unix = [], []
107       Array(l).each { |addr| (addr =~ %r{\A/} ? unix : tcp) << addr }
108       unless tcp.empty? && unix.empty?
109         @tcp_listeners = tcp
110         @unix_listeners = unix
111       end
112     end
114     agg_class = opts[:agg_class] || Aggregate
115     start = Time.now.utc
116     @active = Hash.new { |h,k| h[k] = agg_class.new }
117     @queued = Hash.new { |h,k| h[k] = agg_class.new }
118     @resets = Hash.new { |h,k| h[k] = start }
119     @snapshot = [ start, {} ]
120     @delay = opts[:delay] || 1
121     @lock = Mutex.new
122     @start = Mutex.new
123     @cond = ConditionVariable.new
124     @thr = nil
125   end
127   def hostname
128     Socket.gethostname
129   end
131   # rack endpoint
132   def call(env)
133     @start.synchronize { @thr ||= aggregator_thread(env["rack.logger"]) }
134     case env["REQUEST_METHOD"]
135     when "HEAD", "GET"
136       get env
137     when "POST"
138       post env
139     else
140       Rack::Response.new(["Method Not Allowed"], 405).finish
141     end
142   end
144   def aggregator_thread(logger) # :nodoc:
145     @socket = sock = Raindrops::InetDiagSocket.new
146     thr = Thread.new do
147       begin
148         combined = tcp_listener_stats(@tcp_listeners, sock)
149         combined.merge!(unix_listener_stats(@unix_listeners))
150         @lock.synchronize do
151           combined.each do |addr,stats|
152             @active[addr] << stats.active
153             @queued[addr] << stats.queued
154           end
155           @snapshot = [ Time.now.utc, combined ]
156           @cond.broadcast
157         end
158       rescue => e
159         logger.error "#{e.class} #{e.inspect}"
160       end while sleep(@delay) && @socket
161       sock.close
162     end
163     wait_snapshot
164     thr
165   end
167   def active_stats(addr) # :nodoc:
168     @lock.synchronize do
169       tmp = @active[addr] or return
170       [ @resets[addr], tmp.dup ]
171     end
172   end
174   def queued_stats(addr) # :nodoc:
175     @lock.synchronize do
176       tmp = @queued[addr] or return
177       [ @resets[addr], tmp.dup ]
178     end
179   end
181   def wait_snapshot
182     @lock.synchronize do
183       @cond.wait @lock
184       @snapshot
185     end
186   end
188   def agg_to_hash(reset_at, agg)
189     {
190       "X-Count" => agg.count.to_s,
191       "X-Min" => agg.min.to_s,
192       "X-Max" => agg.max.to_s,
193       "X-Mean" => agg.mean.to_s,
194       "X-Std-Dev" => agg.std_dev.to_s,
195       "X-Outliers-Low" => agg.outliers_low.to_s,
196       "X-Outliers-High" => agg.outliers_high.to_s,
197       "X-Last-Reset" => reset_at.httpdate,
198     }
199   end
201   def histogram_txt(agg)
202     reset_at, agg = *agg
203     headers = agg_to_hash(reset_at, agg)
204     body = agg.to_s
205     headers["Content-Type"] = "text/plain"
206     headers["Content-Length"] = bytesize(body).to_s
207     [ 200, headers, [ body ] ]
208   end
210   def histogram_html(agg, addr)
211     reset_at, agg = *agg
212     headers = agg_to_hash(reset_at, agg)
213     body = "<html>" \
214       "<head><title>#{hostname} - #{escape_html addr}</title></head>" \
215       "<body><table>" <<
216       headers.map { |k,v|
217         "<tr><td>#{k.gsub(/^X-/, '')}</td><td>#{v}</td></tr>"
218       }.join << "</table><pre>#{escape_html agg}</pre>" \
219       "<form action='/reset/#{escape addr}' method='post'>" \
220       "<input type='submit' name='x' value='reset' /></form>" \
221       "</body>"
222     headers["Content-Type"] = "text/html"
223     headers["Content-Length"] = bytesize(body).to_s
224     [ 200, headers, [ body ] ]
225   end
227   def get(env)
228     case env["PATH_INFO"]
229     when "/"
230       index
231     when %r{\A/active/(.+)\.txt\z}
232       histogram_txt(active_stats(unescape($1)))
233     when %r{\A/active/(.+)\.html\z}
234       addr = unescape $1
235       histogram_html(active_stats(addr), addr)
236     when %r{\A/queued/(.+)\.txt\z}
237       histogram_txt(queued_stats(unescape($1)))
238     when %r{\A/queued/(.+)\.html\z}
239       addr = unescape $1
240       histogram_html(queued_stats(addr), addr)
241     when %r{\A/tail/(.+)\.txt\z}
242       tail(unescape($1), env)
243     else
244       not_found
245     end
246   end
248   def not_found
249     Rack::Response.new(["Not Found"], 404).finish
250   end
252   def post(env)
253     case env["PATH_INFO"]
254     when %r{\A/reset/(.+)\z}
255       reset!(env, unescape($1))
256     else
257       Rack::Response.new(["Not Found"], 404).finish
258     end
259   end
261   def reset!(env, addr)
262     @lock.synchronize do
263       @active.include?(addr) or return not_found
264       @active.delete addr
265       @queued.delete addr
266       @resets[addr] = Time.now.utc
267       @cond.wait @lock
268     end
269     req = Rack::Request.new(env)
270     res = Rack::Response.new
271     url = req.referer || "#{req.host_with_port}/"
272     res.redirect(url)
273     res.content_type.replace "text/plain"
274     res.write "Redirecting to #{url}"
275     res.finish
276   end
278   def index
279     updated_at, all = snapshot
280     headers = {
281       "Content-Type" => "text/html",
282       "Last-Modified" => updated_at.httpdate,
283     }
284     body = "<html><head>" \
285       "<title>#{hostname} - all interfaces</title>" \
286       "</head><body><h3>Updated at #{updated_at.iso8601}</h3>" \
287       "<table><tr>" \
288         "<th>address</th><th>active</th><th>queued</th><th>reset</th>" \
289       "</tr>" <<
290       all.map do |addr,stats|
291         e_addr = escape addr
292         "<tr>" \
293           "<td><a href='/tail/#{e_addr}.txt'>#{escape_html addr}</a></td>" \
294           "<td><a href='/active/#{e_addr}.html'>#{stats.active}</a></td>" \
295           "<td><a href='/queued/#{e_addr}.html'>#{stats.queued}</a></td>" \
296           "<td><form action='/reset/#{e_addr}' method='post'>" \
297             "<input type='submit' name='x' value='x' /></form></td>" \
298         "</tr>" \
299       end.join << "</table></body></html>"
300     headers["Content-Length"] = bytesize(body).to_s
301     [ 200, headers, [ body ] ]
302   end
304   def tail(addr, env)
305     Tailer.new(self, addr, env).finish
306   end
307   # :startdoc:
309   # This is the response body returned for "/tail/$ADDRESS.txt".  This
310   # must use a multi-threaded Rack server with streaming response support.
311   # It is an internal class and not expected to be used directly
312   class Tailer
313     def initialize(rdmon, addr, env) # :nodoc:
314       @rdmon = rdmon
315       @addr = addr
316       q = Rack::Utils.parse_query env["QUERY_STRING"]
317       @active_min = q["active_min"].to_i
318       @queued_min = q["queued_min"].to_i
319       len = Rack::Utils.bytesize(addr)
320       len = 35 if len > 35
321       @fmt = "%20s % #{len}s % 10u % 10u\n"
322       case env["HTTP_VERSION"]
323       when "HTTP/1.0", nil
324         @chunk = false
325       else
326         @chunk = true
327       end
328     end
330     def finish
331       headers = { "Content-Type" => "text/plain" }
332       headers["Transfer-Encoding"] = "chunked" if @chunk
333       [ 200, headers, self ]
334     end
336     # called by the Rack server
337     def each # :nodoc:
338       begin
339         time, all = @rdmon.wait_snapshot
340         stats = all[@addr] or next
341         stats.queued >= @queued_min or next
342         stats.active >= @active_min or next
343         body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued)
344         body = "#{body.size.to_s(16)}\r\n#{body}\r\n" if @chunk
345         yield body
346       end while true
347       yield "0\r\n\r\n" if @chunk
348     end
349   end
351   # shuts down the background thread
352   def shutdown
353     @socket = nil
354     @thr.join if @thr
355     @thr = nil
356   end