add condition clearing on entry, report contact match failures
[god.git] / lib / god / conditions / memory_usage.rb
blobebdf44b22e4307c96c6644fc6442e5b1fa6f2d2a
1 module God
2   module Conditions
3     
4     class MemoryUsage < 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 reset
22         @timeline.clear
23       end
24       
25       def valid?
26         valid = true
27         valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil?
28         valid &= complain("Attribute 'above' must be specified", self) if self.above.nil?
29         valid
30       end
31       
32       def test
33         return false unless File.exist?(self.watch.pid_file)
34         
35         pid = File.read(self.watch.pid_file).strip
36         process = System::Process.new(pid)
37         @timeline.push(process.memory)
38         
39         history = "[" + @timeline.map { |x| "#{x > self.above ? '*' : ''}#{x}kb" }.join(", ") + "]"
40         
41         if @timeline.select { |x| x > self.above }.size >= self.times.first
42           self.info = "memory out of bounds #{history}"
43           return true
44         else
45           self.info = "memory within bounds #{history}"
46           return false
47         end
48       end
49     end
50     
51   end
52 end