fix god binary daemonization, create some sample setups
[god.git] / lib / god / hub.rb
blobb1c74f2a4b785b75e2e7e696295aec050d97953c
1 module God
2   
3   class Hub
4     # directory to hold conditions and their corresponding metric
5     #   key: condition
6     #   val: metric
7     @@directory = {}
8     
9     def self.attach(condition, metric)
10       # add the condition to the directory
11       @@directory[condition] = metric
12       
13       # schedule poll condition
14       # register event condition
15       if condition.kind_of?(PollCondition)
16         Timer.get.schedule(condition, 0)
17       else
18         condition.register
19       end
20     end
21     
22     def self.detach(condition)
23       # remove the condition from the directory
24       @@directory.delete(condition)
25       
26       # unschedule any pending polls
27       Timer.get.unschedule(condition)
28       
29       # deregister event condition
30       if condition.kind_of?(EventCondition)
31         condition.deregister
32       end
33     end
34     
35     def self.trigger(condition)
36       if condition.kind_of?(PollCondition)
37         self.handle_poll(condition)
38       elsif condition.kind_of?(EventCondition)
39         self.handle_event(condition)
40       end
41     end
42     
43     def self.handle_poll(condition)
44       Thread.new do
45         begin
46           metric = @@directory[condition]
47           watch = metric.watch
48         
49           watch.mutex.synchronize do
50             result = condition.test
51           
52             msg = watch.name + ' ' + condition.class.name + " [#{result}] " + metric.destination.inspect
53             Syslog.debug(msg)
54             puts msg
55           
56             condition.after
57           
58             if dest = metric.destination[result]
59               watch.move(dest)
60             else
61               # reschedule
62               Timer.get.schedule(condition)
63             end
64           end
65         rescue => e
66           message = format("Unhandled exception (%s): %s\n%s",
67                            e.class, e.message, e.backtrace.join("\n"))
68           Syslog.crit message
69           abort message
70         end
71       end
72     end
73     
74     def self.handle_event(condition)
75       Thread.new do
76         metric = @@directory[condition]
77         watch = metric.watch
78         
79         watch.mutex.synchronize do
80           msg = watch.name + ' ' + condition.class.name + " [true] " + metric.destination.inspect
81           Syslog.debug(msg)
82           puts msg
83           
84           dest = metric.destination[true]
85           watch.move(dest)
86         end
87       end
88     end
89   end
90   
91 end