change File.open {}.read to File.read
[god.git] / lib / god / conditions / cpu_usage.rb
blob76d35cdfdfd937c84a4063fec227e8dcd345ddf7
1 module God
2   module Conditions
3     
4     class CpuUsage < PollCondition
5       attr_accessor :above, :times
6     
7       def initialize
8         super
9         self.above = nil
10         self.times = [1, 1]
11       end
12       
13       def prepare
14         if self.times.kind_of?(Integer)
15           self.times = [self.times, self.times]
16         end
17         
18         @timeline = Timeline.new(self.times[1])
19       end
20     
21       def valid?
22         valid = true
23         valid &= complain("You must specify the 'pid_file' attribute on the Watch for :memory_usage") if self.watch.pid_file.nil?
24         valid &= complain("You must specify the 'above' attribute for :memory_usage") if self.above.nil?
25         valid
26       end
27     
28       def test
29         return false unless File.exist?(self.watch.pid_file)
30         
31         pid = File.read(self.watch.pid_file).strip
32         process = System::Process.new(pid)
33         @timeline.push(process.percent_cpu)
34         if @timeline.select { |x| x > self.above }.size >= self.times.first
35           @timeline.clear
36           return true
37         else
38           return false
39         end
40       end
41     end
42     
43   end
44 end