549337450fc78f8d27cf725824847239fadd34dd
[raindrops.git] / lib / raindrops / watcher.rb
blob549337450fc78f8d27cf725824847239fadd34dd
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://raindrops-demo.bogomips.org/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://raindrops-demo.bogomips.org/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://raindrops-demo.bogomips.org/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://raindrops-demo.bogomips.org/queued/0.0.0.0%3A80.html
61 # === POST /reset/$LISTENER
63 # Resets the active and queued statistics for the given listener.
65 # === GET /tail/$LISTENER.txt?active_min=1&queued_min=1
67 # Streams chunked a response to the client.
68 # Interval is the preconfigured +:delay+ of the application (default 1 second)
70 # The response is plain text in the following format:
72 #   ISO8601_TIMESTAMP LISTENER_NAME ACTIVE_COUNT QUEUED_COUNT LINEFEED
74 # Query parameters:
76 # - active_min - do not stream a line until this active count is reached
77 # - queued_min - do not stream a line until this queued count is reached
79 # == Response headers (mostly the same names as Raindrops::LastDataRecv)
81 # - X-Count   - number of samples polled
82 # - X-Last-Reset - date since the last reset
84 # The following headers are only present if X-Count is greater than one.
86 # - X-Min     - lowest number of connections recorded
87 # - X-Max     - highest number of connections recorded
88 # - X-Mean    - mean number of connections recorded
89 # - X-Std-Dev - standard deviation of connection count
90 # - X-Outliers-Low - number of low outliers (hopefully many for queued)
91 # - X-Outliers-High - number of high outliers (hopefully zero for queued)
92 # - X-Current - current number of connections
93 # - X-First-Peak-At - date of when X-Max was first reached
94 # - X-Last-Peak-At - date of when X-Max was last reached
96 # = Demo Server
98 # There is a server running this app at http://raindrops-demo.bogomips.org/
99 # The Raindrops::Middleware demo is also accessible at
100 # http://raindrops-demo.bogomips.org/_raindrops
102 # The demo server is only limited to 30 users, so be sure not to abuse it
103 # by using the /tail/ endpoint too much.
104 class Raindrops::Watcher
105   # :stopdoc:
106   attr_reader :snapshot
107   include Rack::Utils
108   include Raindrops::Linux
109   DOC_URL = "http://raindrops.bogomips.org/Raindrops/Watcher.html"
110   Peak = Struct.new(:first, :last)
112   def initialize(opts = {})
113     @tcp_listeners = @unix_listeners = nil
114     if l = opts[:listeners]
115       tcp, unix = [], []
116       Array(l).each { |addr| (addr =~ %r{\A/} ? unix : tcp) << addr }
117       unless tcp.empty? && unix.empty?
118         @tcp_listeners = tcp
119         @unix_listeners = unix
120       end
121     end
123     @agg_class = opts[:agg_class] || Aggregate
124     @start_time = Time.now.utc
125     @active = Hash.new { |h,k| h[k] = @agg_class.new }
126     @queued = Hash.new { |h,k| h[k] = @agg_class.new }
127     @resets = Hash.new { |h,k| h[k] = @start_time }
128     @peak_active = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) }
129     @peak_queued = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) }
130     @snapshot = [ @start_time, {} ]
131     @delay = opts[:delay] || 1
132     @lock = Mutex.new
133     @start = Mutex.new
134     @cond = ConditionVariable.new
135     @thr = nil
136   end
138   def hostname
139     Socket.gethostname
140   end
142   # rack endpoint
143   def call(env)
144     @start.synchronize { @thr ||= aggregator_thread(env["rack.logger"]) }
145     case env["REQUEST_METHOD"]
146     when "HEAD", "GET"
147       get env
148     when "POST"
149       post env
150     else
151       Rack::Response.new(["Method Not Allowed"], 405).finish
152     end
153   end
155   def aggregate!(agg_hash, peak_hash, addr, number, now)
156     agg = agg_hash[addr]
157     if (max = agg.max) && number > 0 && number >= max
158       peak = peak_hash[addr]
159       peak.first = now if number > max
160       peak.last = now
161     end
162     agg << number
163   end
165   def aggregator_thread(logger) # :nodoc:
166     @socket = sock = Raindrops::InetDiagSocket.new
167     thr = Thread.new do
168       begin
169         combined = tcp_listener_stats(@tcp_listeners, sock)
170         combined.merge!(unix_listener_stats(@unix_listeners))
171         @lock.synchronize do
172           now = Time.now.utc
173           combined.each do |addr,stats|
174             aggregate!(@active, @peak_active, addr, stats.active, now)
175             aggregate!(@queued, @peak_queued, addr, stats.queued, now)
176           end
177           @snapshot = [ now, combined ]
178           @cond.broadcast
179         end
180       rescue => e
181         logger.error "#{e.class} #{e.inspect}"
182       end while sleep(@delay) && @socket
183       sock.close
184     end
185     wait_snapshot
186     thr
187   end
189   def non_existent_stats(time)
190     [ time, @start_time, @agg_class.new, 0, Peak.new(@start_time, @start_time) ]
191   end
193   def active_stats(addr) # :nodoc:
194     @lock.synchronize do
195       time, combined = @snapshot
196       stats = combined[addr] or return non_existent_stats(time)
197       tmp, peak = @active[addr], @peak_active[addr]
198       [ time, @resets[addr], tmp.dup, stats.active, peak ]
199     end
200   end
202   def queued_stats(addr) # :nodoc:
203     @lock.synchronize do
204       time, combined = @snapshot
205       stats = combined[addr] or return non_existent_stats(time)
206       tmp, peak = @queued[addr], @peak_queued[addr]
207       [ time, @resets[addr], tmp.dup, stats.queued, peak ]
208     end
209   end
211   def wait_snapshot
212     @lock.synchronize do
213       @cond.wait @lock
214       @snapshot
215     end
216   end
218   def std_dev(agg)
219     agg.std_dev.to_s
220   rescue Errno::EDOM
221     "NaN"
222   end
224   def agg_to_hash(reset_at, agg, current, peak)
225     {
226       "X-Count" => agg.count.to_s,
227       "X-Min" => agg.min.to_s,
228       "X-Max" => agg.max.to_s,
229       "X-Mean" => agg.mean.to_s,
230       "X-Std-Dev" => std_dev(agg),
231       "X-Outliers-Low" => agg.outliers_low.to_s,
232       "X-Outliers-High" => agg.outliers_high.to_s,
233       "X-Last-Reset" => reset_at.httpdate,
234       "X-Current" => current.to_s,
235       "X-First-Peak-At" => peak.first.httpdate,
236       "X-Last-Peak-At" => peak.last.httpdate,
237     }
238   end
240   def histogram_txt(agg)
241     updated_at, reset_at, agg, current, peak = *agg
242     headers = agg_to_hash(reset_at, agg, current, peak)
243     body = agg.to_s
244     headers["Content-Type"] = "text/plain"
245     headers["Expires"] = (updated_at + @delay).httpdate
246     headers["Content-Length"] = bytesize(body).to_s
247     [ 200, headers, [ body ] ]
248   end
250   def histogram_html(agg, addr)
251     updated_at, reset_at, agg, current, peak = *agg
252     headers = agg_to_hash(reset_at, agg, current, peak)
253     body = "<html>" \
254       "<head><title>#{hostname} - #{escape_html addr}</title></head>" \
255       "<body><table>" <<
256       headers.map { |k,v|
257         "<tr><td>#{k.gsub(/^X-/, '')}</td><td>#{v}</td></tr>"
258       }.join << "</table><pre>#{escape_html agg}</pre>" \
259       "<form action='/reset/#{escape addr}' method='post'>" \
260       "<input type='submit' name='x' value='reset' /></form>" \
261       "</body>"
262     headers["Content-Type"] = "text/html"
263     headers["Expires"] = (updated_at + @delay).httpdate
264     headers["Content-Length"] = bytesize(body).to_s
265     [ 200, headers, [ body ] ]
266   end
268   def get(env)
269     retried = false
270     begin
271       case env["PATH_INFO"]
272       when "/"
273         index
274       when %r{\A/active/(.+)\.txt\z}
275         histogram_txt(active_stats(unescape($1)))
276       when %r{\A/active/(.+)\.html\z}
277         addr = unescape $1
278         histogram_html(active_stats(addr), addr)
279       when %r{\A/queued/(.+)\.txt\z}
280         histogram_txt(queued_stats(unescape($1)))
281       when %r{\A/queued/(.+)\.html\z}
282         addr = unescape $1
283         histogram_html(queued_stats(addr), addr)
284       when %r{\A/tail/(.+)\.txt\z}
285         tail(unescape($1), env)
286       else
287         not_found
288       end
289     rescue Errno::EDOM
290       raise if retried
291       retried = true
292       wait_snapshot
293       retry
294     end
295   end
297   def not_found
298     Rack::Response.new(["Not Found"], 404).finish
299   end
301   def post(env)
302     case env["PATH_INFO"]
303     when %r{\A/reset/(.+)\z}
304       reset!(env, unescape($1))
305     else
306       not_found
307     end
308   end
310   def reset!(env, addr)
311     @lock.synchronize do
312       @active.include?(addr) or return not_found
313       @active.delete addr
314       @queued.delete addr
315       @resets[addr] = Time.now.utc
316       @cond.wait @lock
317     end
318     req = Rack::Request.new(env)
319     res = Rack::Response.new
320     url = req.referer || "#{req.host_with_port}/"
321     res.redirect(url)
322     res.content_type.replace "text/plain"
323     res.write "Redirecting to #{url}"
324     res.finish
325   end
327   def index
328     updated_at, all = snapshot
329     headers = {
330       "Content-Type" => "text/html",
331       "Last-Modified" => updated_at.httpdate,
332       "Expires" => (updated_at + @delay).httpdate,
333     }
334     body = "<html><head>" \
335       "<title>#{hostname} - all interfaces</title>" \
336       "</head><body><h3>Updated at #{updated_at.iso8601}</h3>" \
337       "<table><tr>" \
338         "<th>address</th><th>active</th><th>queued</th><th>reset</th>" \
339       "</tr>" <<
340       all.sort do |a,b|
341         a[0] <=> b[0] # sort by addr
342       end.map do |addr,stats|
343         e_addr = escape addr
344         "<tr>" \
345           "<td><a href='/tail/#{e_addr}.txt' " \
346             "title='&quot;tail&quot; output in real time'" \
347             ">#{escape_html addr}</a></td>" \
348           "<td><a href='/active/#{e_addr}.html' " \
349             "title='show active connection stats'>#{stats.active}</a></td>" \
350           "<td><a href='/queued/#{e_addr}.html' " \
351             "title='show queued connection stats'>#{stats.queued}</a></td>" \
352           "<td><form action='/reset/#{e_addr}' method='post'>" \
353             "<input title='reset statistics' " \
354               "type='submit' name='x' value='x' /></form></td>" \
355         "</tr>" \
356       end.join << "</table>" \
357       "<p>" \
358         "This is running the #{self.class}</a> service, see " \
359         "<a href='#{DOC_URL}'>#{DOC_URL}</a> " \
360         "for more information and options." \
361       "</p>" \
362       "</body></html>"
363     headers["Content-Length"] = bytesize(body).to_s
364     [ 200, headers, [ body ] ]
365   end
367   def tail(addr, env)
368     Tailer.new(self, addr, env).finish
369   end
371   # This is the response body returned for "/tail/$ADDRESS.txt".  This
372   # must use a multi-threaded Rack server with streaming response support.
373   # It is an internal class and not expected to be used directly
374   class Tailer
375     def initialize(rdmon, addr, env) # :nodoc:
376       @rdmon = rdmon
377       @addr = addr
378       q = Rack::Utils.parse_query env["QUERY_STRING"]
379       @active_min = q["active_min"].to_i
380       @queued_min = q["queued_min"].to_i
381       len = Rack::Utils.bytesize(addr)
382       len = 35 if len > 35
383       @fmt = "%20s % #{len}s % 10u % 10u\n"
384       case env["HTTP_VERSION"]
385       when "HTTP/1.0", nil
386         @chunk = false
387       else
388         @chunk = true
389       end
390     end
392     def finish
393       headers = {
394         "Content-Type" => "text/plain",
395         "Cache-Control" => "no-transform",
396         "Expires" => Time.at(0).httpdate,
397       }
398       headers["Transfer-Encoding"] = "chunked" if @chunk
399       [ 200, headers, self ]
400     end
402     # called by the Rack server
403     def each # :nodoc:
404       begin
405         time, all = @rdmon.wait_snapshot
406         stats = all[@addr] or next
407         stats.queued >= @queued_min or next
408         stats.active >= @active_min or next
409         body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued)
410         body = "#{body.size.to_s(16)}\r\n#{body}\r\n" if @chunk
411         yield body
412       end while true
413       yield "0\r\n\r\n" if @chunk
414     end
415   end
417   # shuts down the background thread, only for tests
418   def shutdown
419     @socket = nil
420     @thr.join if @thr
421     @thr = nil
422   end
423   # :startdoc: