d500df0780c5c693bfd9379d0a7f35c6e33b83da
[god.git] / lib / god / conditions / process_running.rb
blobd500df0780c5c693bfd9379d0a7f35c6e33b83da
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
38       
39       def valid?
40         valid = true
41         valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil?
42         valid &= complain("Attribute 'running' must be specified", self) if self.running.nil?
43         valid
44       end
45     
46       def test
47         self.info = []
48         
49         unless File.exist?(self.watch.pid_file)
50           self.info << "#{self.watch.name} #{self.class.name}: no such pid file: #{self.watch.pid_file}"
51           return !self.running
52         end
53         
54         pid = File.read(self.watch.pid_file).strip
55         active = System::Process.new(pid).exists?
56         
57         if (self.running && active)
58           self.info << "process is running"
59           true
60         elsif (!self.running && !active)
61           self.info << "process is not running"
62           true
63         else
64           if self.running
65             self.info << "process is not running"
66           else
67             self.info << "process is running"
68           end
69           false
70         end
71       end
72     end
73     
74   end
75 end