tighten up Hub and add comments
[god.git] / lib / god / conditions / process_exits.rb
blobbe955e2fae7f9d8424e96814066fb5d2d6a502b4
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             formatted_extra = extra.size > 0 ? " #{extra.inspect}" : ""
42             self.info = "process #{pid} exited#{formatted_extra}"
43             Hub.trigger(self)
44           end
45           
46           msg = "#{self.watch.name} registered 'proc_exit' event for pid #{pid}"
47           applog(self.watch, :info, msg)
48         rescue StandardError
49           raise EventRegistrationFailedError.new
50         end
51       end
52       
53       def deregister
54         if File.exist?(self.watch.pid_file)
55           pid = File.read(self.watch.pid_file).strip.to_i
56           EventHandler.deregister(pid, :proc_exit)
57           
58           msg = "#{self.watch.name} deregistered 'proc_exit' event for pid #{pid}"
59           applog(self.watch, :info, msg)
60         else
61           applog(self.watch, :error, "#{self.watch.name} could not deregister: no such PID file #{self.watch.pid_file} (#{self.base_name})")
62         end
63       end
64     end
65     
66   end
67 end