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, :pid_file
41 if self.times.kind_of?(Integer)
42 self.times = [self.times, self.times]
45 @timeline = Timeline.new(self.times[1])
53 self.watch.pid || File.read(self.pid_file).strip.to_i
58 valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil? && self.pid_file.nil?
59 valid &= complain("Attribute 'above' must be specified", self) if self.above.nil?
64 process = System::Process.new(self.pid)
65 @timeline.push(process.percent_cpu)
67 history = "[" + @timeline.map { |x| "#{x > self.above ? '*' : ''}#{x}%%" }.join(", ") + "]"
69 if @timeline.select { |x| x > self.above }.size >= self.times.first
70 self.info = "cpu out of bounds #{history}"
73 self.info = "cpu within bounds #{history}"