aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/commands/process/inspector.rb
blob: 79e1cf9a614f7562701507d6359c6cc19714d2e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'optparse'

if RUBY_PLATFORM =~ /mswin32/ then abort("Inspector is only for Unix") end

OPTIONS = {
  :pid_path => File.expand_path(RAILS_ROOT + '/tmp/pids'),
  :pattern  => "dispatch.*.pid",
  :ps       => "ps -o pid,state,user,start,time,pcpu,vsz,majflt,command -p %s"
}

class Inspector
  def self.inspect(pid_path, pattern)
    new(pid_path, pattern).inspect
  end

  def initialize(pid_path, pattern)
    @pid_path, @pattern = pid_path, pattern
  end

  def inspect
    header = `#{OPTIONS[:ps] % 1}`.split("\n")[0] + "\n"
    lines  = pids.collect { |pid| `#{OPTIONS[:ps] % pid}`.split("\n")[1] }
    
    puts(header + lines.join("\n"))
  end

  private
    def pids
      pid_files.collect do |pid_file|
        File.read(pid_file).to_i
      end
    end

    def pid_files
      Dir.glob(@pid_path + "/" + @pattern)
    end
end


ARGV.options do |opts|
  opts.banner = "Usage: inspector [options]"

  opts.separator ""

  opts.on <<-EOF
  Description:
    Displays system information about Rails dispatchers (or other processes that use pid files) through
    the ps command.

  Examples:
    inspector                                             # default ps on all tmp/pids/dispatch.*.pid files
    inspector -s 'ps -o user,start,majflt,pcpu,vsz -p %s' # custom ps, %s is where the pid is interleaved
  EOF

  opts.on("  Options:")

  opts.on("-s", "--ps=command", "default: #{OPTIONS[:ps]}", String)           { |v| OPTIONS[:ps] = v }
  opts.on("-p", "--pidpath=path", "default: #{OPTIONS[:pid_path]}", String)   { |v| OPTIONS[:pid_path] = v }
  opts.on("-r", "--pattern=pattern", "default: #{OPTIONS[:pattern]}", String) { |v| OPTIONS[:pattern] = v }

  opts.separator ""

  opts.on("-h", "--help", "Show this help message.") { puts opts; exit }

  opts.parse!
end

Inspector.inspect(OPTIONS[:pid_path], OPTIONS[:pattern])