remove redundant rescues in cli
[god.git] / lib / god.rb
blob23a81485c4f4028f5a68fb2243270a36d5b4f321
1 $:.unshift File.dirname(__FILE__)     # For use/testing when no gem is installed
3 # core
4 require 'stringio'
5 require 'logger'
7 # stdlib
8 require 'syslog'
10 # internal requires
11 require 'god/errors'
12 require 'god/logger'
13 require 'god/system/process'
14 require 'god/dependency_graph'
15 require 'god/timeline'
16 require 'god/configurable'
18 require 'god/task'
20 require 'god/behavior'
21 require 'god/behaviors/clean_pid_file'
22 require 'god/behaviors/notify_when_flapping'
24 require 'god/condition'
25 require 'god/conditions/process_running'
26 require 'god/conditions/process_exits'
27 require 'god/conditions/tries'
28 require 'god/conditions/memory_usage'
29 require 'god/conditions/cpu_usage'
30 require 'god/conditions/always'
31 require 'god/conditions/lambda'
32 require 'god/conditions/degrading_lambda'
33 require 'god/conditions/flapping'
34 require 'god/conditions/http_response_code'
36 require 'god/contact'
37 require 'god/contacts/email'
39 require 'god/reporter'
40 require 'god/server'
41 require 'god/timer'
42 require 'god/hub'
44 require 'god/metric'
45 require 'god/watch'
47 require 'god/trigger'
48 require 'god/event_handler'
49 require 'god/registry'
50 require 'god/process'
52 require 'god/sugar'
54 $:.unshift File.join(File.dirname(__FILE__), *%w[.. ext god])
56 LOG = God::Logger.new
57 LOG.datetime_format = "%Y-%m-%d %H:%M:%S "
59 GOD_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
61 CONFIG_FILE = ''
62 def __CONFIG__
63   CONFIG_FILE
64 end
66 begin
67   Syslog.open('god')
68 rescue RuntimeError
69   Syslog.reopen('god')
70 end
72 def with_stdout_captured
73   old_stdout = $stdout
74   out = StringIO.new
75   $stdout = out
76   begin
77     yield
78   ensure
79     $stdout = old_stdout
80   end
81   out.string
82 end
84 God::EventHandler.load
86 module Kernel
87   alias_method :abort_orig, :abort
88   
89   def abort(text = nil)
90     $run = false
91     LOG.log(nil, :error, text) if text
92     text ? abort_orig(text) : exit(1)
93   end
94   
95   alias_method :exit_orig, :exit
96   
97   def exit(code = 0)
98     $run = false
99     exit_orig(code)
100   end
103 class Module
104   def safe_attr_accessor(*args)
105     args.each do |arg|
106       define_method((arg.to_s + "=").intern) do |other|
107         if !self.running && self.inited
108           abort "God.#{arg} must be set before any Tasks are defined"
109         end
110         
111         if self.running && self.inited
112           LOG.log(nil, :warn, "God.#{arg} can't be set while god is running")
113           return
114         end
115         
116         instance_variable_set(('@' + arg.to_s).intern, other)
117       end
118       
119       define_method(arg) do
120         instance_variable_get(('@' + arg.to_s).intern)
121       end
122     end
123   end
126 module God
127   VERSION = '0.5.0'
128   
129   LOG_BUFFER_SIZE_DEFAULT = 1000
130   PID_FILE_DIRECTORY_DEFAULT = '/var/run/god'
131   DRB_PORT_DEFAULT = 17165
132   DRB_ALLOW_DEFAULT = ['127.0.0.1']
133   
134   class << self
135     # user configurable
136     safe_attr_accessor :host,
137                        :port,
138                        :allow,
139                        :log_buffer_size,
140                        :pid_file_directory
141     
142     # internal
143     attr_accessor :inited,
144                   :running,
145                   :pending_watches,
146                   :server,
147                   :watches,
148                   :groups,
149                   :contacts,
150                   :contact_groups
151   end
152   
153   # deprecated
154   def self.init
155     yield self if block_given?
156   end
157   
158   def self.internal_init
159     # only do this once
160     return if self.inited
161     
162     # variable init
163     self.watches = {}
164     self.groups = {}
165     self.pending_watches = []
166     self.contacts = {}
167     self.contact_groups = {}
168     
169     # set defaults
170     self.log_buffer_size ||= LOG_BUFFER_SIZE_DEFAULT
171     self.pid_file_directory ||= PID_FILE_DIRECTORY_DEFAULT
172     self.port ||= DRB_PORT_DEFAULT
173     self.allow ||= DRB_ALLOW_DEFAULT
174     LOG.level = Logger::INFO
175     
176     # init has been executed
177     self.inited = true
178     
179     # not yet running
180     self.running = false
181   end
182   
183   # Instantiate a new, empty Watch object and pass it to the mandatory
184   # block. The attributes of the watch will be set by the configuration
185   # file.
186   def self.watch(&block)
187     self.task(Watch, &block)
188   end
189   
190   # Instantiate a new, empty Task object and pass it to the mandatory
191   # block. The attributes of the task will be set by the configuration
192   # file.
193   def self.task(klass = Task)
194     self.internal_init
195     
196     t = klass.new
197     yield(t)
198     
199     # do the post-configuration
200     t.prepare
201     
202     # if running, completely remove the watch (if necessary) to
203     # prepare for the reload
204     existing_watch = self.watches[t.name]
205     if self.running && existing_watch
206       self.unwatch(existing_watch)
207     end
208     
209     # ensure the new watch has a unique name
210     if self.watches[t.name] || self.groups[t.name]
211       abort "Task name '#{t.name}' already used for a Task or Group"
212     end
213     
214     # ensure watch is internally valid
215     t.valid? || abort("Task '#{t.name}' is not valid (see above)")
216     
217     # add to list of watches
218     self.watches[t.name] = t
219     
220     # add to pending watches
221     self.pending_watches << t
222     
223     # add to group if specified
224     if t.group
225       # ensure group name hasn't been used for a watch already
226       if self.watches[t.group]
227         abort "Group name '#{t.group}' already used for a Task"
228       end
229     
230       self.groups[t.group] ||= []
231       self.groups[t.group] << t
232     end
234     # register watch
235     t.register!
236     
237     # log
238     if self.running && existing_watch
239       LOG.log(t, :info, "#{t.name} Reloaded config")
240     elsif self.running
241       LOG.log(t, :info, "#{t.name} Loaded config")
242     end
243   end
244   
245   def self.unwatch(watch)
246     # unmonitor
247     watch.unmonitor
248     
249     # unregister
250     watch.unregister!
251     
252     # remove from watches
253     self.watches.delete(watch.name)
254     
255     # remove from groups
256     if watch.group
257       self.groups[watch.group].delete(watch)
258     end
259   end
260   
261   def self.contact(kind)
262     self.internal_init
263     
264     # create the condition
265     begin
266       c = Contact.generate(kind)
267     rescue NoSuchContactError => e
268       abort e.message
269     end
270     
271     # send to block so config can set attributes
272     yield(c) if block_given?
273     
274     # call prepare on the contact
275     c.prepare
276     
277     # ensure the new contact has a unique name
278     if self.contacts[c.name] || self.contact_groups[c.name]
279       abort "Contact name '#{c.name}' already used for a Contact or Contact Group"
280     end
281     
282     # abort if the Contact is invalid, the Contact will have printed
283     # out its own error messages by now
284     unless Contact.valid?(c) && c.valid?
285       abort "Exiting on invalid contact"
286     end
287     
288     # add to list of contacts
289     self.contacts[c.name] = c
290     
291     # add to contact group if specified
292     if c.group
293       # ensure group name hasn't been used for a contact already
294       if self.contacts[c.group]
295         abort "Contact Group name '#{c.group}' already used for a Contact"
296       end
297     
298       self.contact_groups[c.group] ||= []
299       self.contact_groups[c.group] << c
300     end
301   end
302     
303   def self.control(name, command)
304     # get the list of watches
305     watches = Array(self.watches[name] || self.groups[name])
306   
307     jobs = []
308     
309     # do the command
310     case command
311       when "start", "monitor"
312         watches.each { |w| jobs << Thread.new { w.monitor if w.state != :up } }
313       when "restart"
314         watches.each { |w| jobs << Thread.new { w.move(:restart) } }
315       when "stop"
316         watches.each { |w| jobs << Thread.new { w.unmonitor.action(:stop) if w.state != :unmonitored } }
317       when "unmonitor"
318         watches.each { |w| jobs << Thread.new { w.unmonitor if w.state != :unmonitored } }
319       else
320         raise InvalidCommandError.new
321     end
322     
323     jobs.each { |j| j.join }
324     
325     watches
326   end
327   
328   def self.stop_all
329     self.watches.sort.each do |name, w|
330       Thread.new do
331         w.unmonitor if w.state != :unmonitored
332         w.action(:stop) if w.alive?
333       end
334     end
335     
336     10.times do
337       return true unless self.watches.map { |name, w| w.alive? }.any?
338       sleep 1
339     end
340     
341     return false
342   end
343   
344   def self.terminate
345     exit!(0)
346   end
347   
348   def self.status
349     info = {}
350     self.watches.map do |name, w|
351       info[name] = {:state => w.state}
352     end
353     info
354   end
355   
356   def self.running_log(watch_name, since)
357     unless self.watches[watch_name]
358       raise NoSuchWatchError.new
359     end
360     
361     LOG.watch_log_since(watch_name, since)
362   end
363   
364   def self.running_load(code, filename)
365     errors = ""
366     watches = []
367     
368     begin
369       LOG.start_capture
370       
371       CONFIG_FILE.replace(filename)
372       eval(code, nil, filename)
373       self.pending_watches.each { |w| w.monitor if w.autostart? }
374       watches = self.pending_watches.dup
375       self.pending_watches.clear
376     rescue Exception => e
377       # don't ever let running_load take down god
378       errors << LOG.finish_capture
379       
380       unless e.instance_of?(SystemExit)
381         errors << e.message << "\n"
382         errors << e.backtrace.join("\n")
383       end
384     end
385     
386     [watches, errors]
387   end
388   
389   def self.load(glob)
390     Dir[glob].each do |f|
391       Kernel.load f
392     end
393   end
394   
395   def self.setup
396     # Make pid directory
397     unless test(?d, self.pid_file_directory)
398       begin
399         FileUtils.mkdir_p(self.pid_file_directory)
400       rescue Errno::EACCES => e
401         abort "Failed to create pid file directory: #{e.message}"
402       end
403     end
404   end
405     
406   def self.validater
407     unless test(?w, self.pid_file_directory)
408       abort "The pid file directory (#{self.pid_file_directory}) is not writable by #{Etc.getlogin}"
409     end
410   end
411   
412   def self.start
413     self.internal_init
414     self.setup
415     self.validater
416     
417     # instantiate server
418     self.server = Server.new(self.host, self.port, self.allow)
419     
420     # start event handler system
421     EventHandler.start if EventHandler.loaded?
422     
423     # start the timer system
424     Timer.get
425     
426     # start monitoring any watches set to autostart
427     self.watches.values.each { |w| w.monitor if w.autostart? }
428     
429     # clear pending watches
430     self.pending_watches.clear
431     
432     # mark as running
433     self.running = true
434     
435     # join the timer thread so we don't exit
436     Timer.get.join
437   end
438   
439   def self.at_exit
440     self.start
441   end
444 at_exit do
445   God.at_exit if $run