prevent carry-over conditions
[god.git] / lib / god / conditions / process_running.rb
blobecc6f69f638e2aa246fa2e8e3d67573199482954
1 module God
2   module Conditions
3     
4     # Condition Symbol :process_running
5     # Type: Poll
6     # 
7     # Trigger when a process is running or not running depending on attributes.
8     #
9     # Paramaters
10     #   Required
11     #     +pid_file+ is the pid file of the process in question. Automatically
12     #                populated for Watches.
13     #     +running" specifies whether you want to trigger if the process is 
14     #               running (true) or whether it is not running (false)
15     #
16     # Examples
17     #
18     # Trigger if process IS NOT running (from a Watch):
19     #
20     #   on.condition(:process_running) do |c|
21     #     c.running = false
22     #   end
23     #
24     # Trigger if process IS running (from a Watch):
25     #
26     #   on.condition(:process_running) do |c|
27     #     c.running = true
28     #   end
29     #
30     # Non-Watch Tasks must specify a PID file:
31     #
32     #   on.condition(:process_running) do |c|
33     #     c.running = false
34     #     c.pid_file = "/var/run/mongrel.3000.pid"
35     #   end
36     class ProcessRunning < PollCondition
37       attr_accessor :running, :pid_file
38       
39       def pid
40         self.watch.pid || File.read(self.pid_file).strip.to_i
41       end
42       
43       def valid?
44         valid = true
45         valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil? && self.pid_file.nil?
46         valid &= complain("Attribute 'running' must be specified", self) if self.running.nil?
47         valid
48       end
49       
50       def test
51         self.info = []
52         
53         # unless File.exist?(self.watch.pid_file)
54         #   self.info << "#{self.watch.name} #{self.class.name}: no such pid file: #{self.watch.pid_file}"
55         #   return !self.running
56         # end
57         
58         pid = self.watch.pid
59         active = pid && System::Process.new(pid).exists?
60         
61         if (self.running && active)
62           self.info << "process is running"
63           true
64         elsif (!self.running && !active)
65           self.info << "process is not running"
66           true
67         else
68           if self.running
69             self.info << "process is not running"
70           else
71             self.info << "process is running"
72           end
73           false
74         end
75       end
76     end
77     
78   end
79 end