public
Fork of mojombo/god
Description: Ruby process monitor
Homepage: http://god.rubyforge.org
Clone URL: git://github.com/kevinclark/god.git
kevinclark (author)
Tue May 13 21:20:32 -0700 2008
commit  4f12e1ceb12a9da7444a4de3572b3288f623276b
tree    4822c8a09e8d7873f4df7f02971e7c597c396069
parent  57bd329169794773b962e631d239cf3c8a3ed9de
god / lib / god / system / slash_proc_poller.rb
100644 63 lines (54 sloc) 1.908 kb
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
module God
  module System
    class SlashProcPoller < PortablePoller
      @@kb_per_page = 4 # TODO: Need to make this portable
      @@hertz = 100
      @@total_mem = nil
      
      def initialize(pid)
        super(pid)
        
        unless @@total_mem # in K
          File.open("/proc/meminfo") do |f|
            @@total_mem = f.gets.split[1]
          end
        end
      end
      
      def memory
        stat[:rss].to_i * @@kb_per_page
      end
      
      def percent_memory
        (memory / @@total_mem.to_f) * 100
      end
      
      # TODO: Change this to calculate the wma instead
      def percent_cpu
        stats = stat
        total_time = stats[:utime].to_i + stats[:stime].to_i # in jiffies
        seconds = uptime - stats[:starttime].to_i / @@hertz
        if seconds == 0
          0
        else
          ((total_time * 1000 / @@hertz) / seconds) / 10
        end
      end
      
      private
      
      # in seconds
      def uptime
        File.read('/proc/uptime').split[0].to_f
      end
      
      def stat
        stats = {}
        stats[:pid], stats[:comm], stats[:state], stats[:ppid], stats[:pgrp],
        stats[:session], stats[:tty_nr], stats[:tpgid], stats[:flags],
        stats[:minflt], stats[:cminflt], stats[:majflt], stats[:cmajflt],
        stats[:utime], stats[:stime], stats[:cutime], stats[:cstime],
        stats[:priority], stats[:nice], _, stats[:itrealvalue],
        stats[:starttime], stats[:vsize], stats[:rss], stats[:rlim],
        stats[:startcode], stats[:endcode], stats[:startstack], stats[:kstkesp],
        stats[:kstkeip], stats[:signal], stats[:blocked], stats[:sigignore],
        stats[:sigcatch], stats[:wchan], stats[:nswap], stats[:cnswap],
        stats[:exit_signal], stats[:processor], stats[:rt_priority],
        stats[:policy] = File.read("/proc/#{@pid}/stat").split
        stats
      end
    end
  end
end