4 # Condition Symbol :cpu_usage
7 # Trigger when the percent of CPU use of a process is above a specified limit.
8 # On multi-core systems, this number could conceivably be above 100.
12 # +pid_file+ is the pid file of the process in question. Automatically
13 # populated for Watches.
14 # +above+ is the percent CPU above which to trigger the condition. You
15 # may use #percent to clarify this amount (see examples).
19 # Trigger if the process is using more than 25 percent of the cpu (from a Watch):
21 # on.condition(:cpu_usage) do |c|
22 # c.above = 25.percent
25 # Non-Watch Tasks must specify a PID file:
27 # on.condition(:cpu_usage) do |c|
28 # c.above = 25.percent
29 # c.pid_file = "/var/run/mongrel.3000.pid"
31 class CpuUsage < PollCondition
32 attr_accessor :above, :times
41 if self.times.kind_of?(Integer)
42 self.times = [self.times, self.times]
45 @timeline = Timeline.new(self.times[1])
54 valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil?
55 valid &= complain("Attribute 'above' must be specified", self) if self.above.nil?
60 return false unless File.exist?(self.watch.pid_file)
62 pid = File.read(self.watch.pid_file).strip
63 process = System::Process.new(pid)
64 @timeline.push(process.percent_cpu)
66 history = "[" + @timeline.map { |x| "#{x > self.above ? '*' : ''}#{x}%%" }.join(", ") + "]"
68 if @timeline.select { |x| x > self.above }.size >= self.times.first
69 self.info = "cpu out of bounds #{history}"
72 self.info = "cpu within bounds #{history}"