linux-tcp-listener-stats: synchronize stdout/stderr
[raindrops.git] / examples / linux-tcp-listener-stats.rb
blob522882a13851309c1bc50bb27b12844856b76296
1 #!/usr/bin/ruby
2 $stdout.sync = $stderr.sync = true
3 # this is used to show or watch the number of active and queued
4 # connections on any listener socket from the command line
6 require 'raindrops'
7 require 'optparse'
8 require 'ipaddr'
9 usage = "Usage: #$0 [-d delay] ADDR..."
10 ARGV.size > 0 or abort usage
11 delay = false
13 # "normal" exits when driven on the command-line
14 trap(:INT) { exit 130 }
15 trap(:PIPE) { exit 0 }
17 opts = OptionParser.new('', 24, '  ') do |opts|
18   opts.banner = usage
19   opts.on('-d', '--delay=delay') { |nr| delay = nr.to_i }
20   opts.parse! ARGV
21 end
23 ARGV.each do |addr|
24   addr =~ %r{\A(127\..+):(\d+)\z} or next
25   host, port = $1, $2
26   hex_port = '%X' % port.to_i
27   ip_addr = IPAddr.new(host)
28   hex_host = ip_addr.hton.each_byte.inject('') { |s,o| s << '%02X' % o }
29   socks = File.readlines('/proc/net/tcp')
30   hex_addr = "#{hex_host}:#{hex_port}"
31   if socks.grep(/^\s+\d+:\s+#{hex_addr}\s+/).empty? &&
32      ! socks.grep(/^\s+\d+:\s+00000000:#{hex_port}\s+/).empty?
33     warn "W: #{host}:#{port} (#{hex_addr}) not found in /proc/net/tcp"
34     warn "W: Did you mean 0.0.0.0:#{port}?"
35   end
36 end
38 fmt = "% 19s % 10u % 10u\n"
39 printf fmt.tr('u','s'), *%w(address active queued)
41 begin
42   stats = Raindrops::Linux.tcp_listener_stats(ARGV)
43   stats.each { |addr,stats| printf fmt, addr, stats.active, stats.queued }
44 end while delay && sleep(delay)