4b0437d22360bae497f66c1ce9cbac79a18ae994
[god.git] / lib / god / conditions / process_exits.rb
blob4b0437d22360bae497f66c1ce9cbac79a18ae994
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         rescue StandardError
45           raise EventRegistrationFailedError.new
46         end
47       end
48       
49       def deregister
50         if File.exist?(self.watch.pid_file)
51           pid = File.read(self.watch.pid_file).strip.to_i
52           EventHandler.deregister(pid, :proc_exit)
53         else
54           applog(self.watch, :error, "#{self.watch.name} could not deregister: no such PID file #{self.watch.pid_file} (#{self.base_name})")
55         end
56       end
57     end
58     
59   end
60 end