de3a265b264bfb40639e1accc280fcd58cddba88
[god.git] / lib / god / conditions / process_exits.rb
blobde3a265b264bfb40639e1accc280fcd58cddba88
1 module God
2   module Conditions
3     
4     # Condition Symbol :process_exits
5     # Type: Event
6     # 
7     # Trigger when a process exits.
8     #
9     # Paramaters
10     #   Required
11     #     +pid_file+ is the pid file of the process in question. Automatically
12     #                populated for Watches.
13     #
14     # Examples
15     #
16     # Trigger if process exits (from a Watch):
17     #
18     #   on.condition(:process_exits)
19     #
20     # Trigger if process exits:
21     #
22     #   on.condition(:process_exits) do |c|
23     #     c.pid_file = "/var/run/mongrel.3000.pid"
24     #   end
25     class ProcessExits < EventCondition
26       def initialize
27         self.info = "process exited"
28       end
29       
30       def valid?
31         valid = true
32         valid &= complain("Attribute 'pid_file' must be specified", self) if self.watch.pid_file.nil?
33         valid
34       end
35     
36       def register
37         pid = File.read(self.watch.pid_file).strip.to_i
38         
39         begin
40           EventHandler.register(pid, :proc_exit) do |extra|
41             self.info = "process #{pid} exited #{extra.inspect}"
42             Hub.trigger(self)
43           end
44           
45           msg = "#{self.watch.name} registered 'proc_exit' event for pid #{pid}"
46           applog(self.watch, :info, msg)
47         rescue StandardError
48           raise EventRegistrationFailedError.new
49         end
50       end
51       
52       def deregister
53         if File.exist?(self.watch.pid_file)
54           pid = File.read(self.watch.pid_file).strip.to_i
55           EventHandler.deregister(pid, :proc_exit)
56           
57           msg = "#{self.watch.name} deregistered 'proc_exit' event for pid #{pid}"
58           applog(self.watch, :info, msg)
59         else
60           applog(self.watch, :error, "#{self.watch.name} could not deregister: no such PID file #{self.watch.pid_file} (#{self.base_name})")
61         end
62       end
63     end
64     
65   end
66 end