deprecate God.init in favor of directly setting options
[god.git] / lib / god.rb
blobe11eccf626c040187ea066a466964a1507bb343a
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 = '')
90     $run = false
91     LOG.log(nil, :error, text) unless text.empty?
92     abort_orig(text)
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   end
237   
238   def self.unwatch(watch)
239     # unmonitor
240     watch.unmonitor
241     
242     # unregister
243     watch.unregister!
244     
245     # remove from watches
246     self.watches.delete(watch.name)
247     
248     # remove from groups
249     if watch.group
250       self.groups[watch.group].delete(watch)
251     end
252   end
253   
254   def self.contact(kind)
255     self.internal_init
256     
257     # create the condition
258     begin
259       c = Contact.generate(kind)
260     rescue NoSuchContactError => e
261       abort e.message
262     end
263     
264     # send to block so config can set attributes
265     yield(c) if block_given?
266     
267     # call prepare on the contact
268     c.prepare
269     
270     # ensure the new contact has a unique name
271     if self.contacts[c.name] || self.contact_groups[c.name]
272       abort "Contact name '#{c.name}' already used for a Contact or Contact Group"
273     end
274     
275     # abort if the Contact is invalid, the Contact will have printed
276     # out its own error messages by now
277     unless Contact.valid?(c) && c.valid?
278       abort "Exiting on invalid contact"
279     end
280     
281     # add to list of contacts
282     self.contacts[c.name] = c
283     
284     # add to contact group if specified
285     if c.group
286       # ensure group name hasn't been used for a contact already
287       if self.contacts[c.group]
288         abort "Contact Group name '#{c.group}' already used for a Contact"
289       end
290     
291       self.contact_groups[c.group] ||= []
292       self.contact_groups[c.group] << c
293     end
294   end
295     
296   def self.control(name, command)
297     # get the list of watches
298     watches = Array(self.watches[name] || self.groups[name])
299   
300     jobs = []
301     
302     # do the command
303     case command
304       when "start", "monitor"
305         watches.each { |w| jobs << Thread.new { w.monitor if w.state != :up } }
306       when "restart"
307         watches.each { |w| jobs << Thread.new { w.move(:restart) } }
308       when "stop"
309         watches.each { |w| jobs << Thread.new { w.unmonitor.action(:stop) if w.state != :unmonitored } }
310       when "unmonitor"
311         watches.each { |w| jobs << Thread.new { w.unmonitor if w.state != :unmonitored } }
312       else
313         raise InvalidCommandError.new
314     end
315     
316     jobs.each { |j| j.join }
317     
318     watches
319   end
320   
321   def self.stop_all
322     self.watches.sort.each do |name, w|
323       Thread.new do
324         w.unmonitor if w.state != :unmonitored
325         w.action(:stop) if w.alive?
326       end
327     end
328     
329     10.times do
330       return true unless self.watches.map { |name, w| w.alive? }.any?
331       sleep 1
332     end
333     
334     return false
335   end
336   
337   def self.terminate
338     exit!(0)
339   end
340   
341   def self.status
342     info = {}
343     self.watches.map do |name, w|
344       info[name] = {:state => w.state}
345     end
346     info
347   end
348   
349   def self.running_log(watch_name, since)
350     unless self.watches[watch_name]
351       raise NoSuchWatchError.new
352     end
353     
354     LOG.watch_log_since(watch_name, since)
355   end
356   
357   def self.running_load(code, filename)
358     errors = ""
359     watches = []
360     
361     begin
362       LOG.start_capture
363       
364       CONFIG_FILE.replace(filename)
365       eval(code, nil, filename)
366       self.pending_watches.each { |w| w.monitor if w.autostart? }
367       watches = self.pending_watches.dup
368       self.pending_watches.clear
369     rescue Exception => e
370       # don't ever let running_load take down god
371       errors << LOG.finish_capture
372       
373       unless e.instance_of?(SystemExit)
374         errors << e.message << "\n"
375         errors << e.backtrace.join("\n")
376       end
377     end
378     
379     [watches, errors]
380   end
381   
382   def self.load(glob)
383     Dir[glob].each do |f|
384       Kernel.load f
385     end
386   end
387   
388   def self.setup
389     # Make pid directory
390     unless test(?d, self.pid_file_directory)
391       begin
392         FileUtils.mkdir_p(self.pid_file_directory)
393       rescue Errno::EACCES => e
394         abort "Failed to create pid file directory: #{e.message}"
395       end
396     end
397   end
398     
399   def self.validater
400     unless test(?w, self.pid_file_directory)
401       abort "The pid file directory (#{self.pid_file_directory}) is not writable by #{Etc.getlogin}"
402     end
403   end
404   
405   def self.start
406     self.internal_init
407     self.setup
408     self.validater
409     
410     # instantiate server
411     self.server = Server.new(self.host, self.port, self.allow)
412     
413     # start event handler system
414     EventHandler.start if EventHandler.loaded?
415     
416     # start the timer system
417     Timer.get
418     
419     # start monitoring any watches set to autostart
420     self.watches.values.each { |w| w.monitor if w.autostart? }
421     
422     # clear pending watches
423     self.pending_watches.clear
424     
425     # mark as running
426     self.running = true
427     
428     # join the timer thread so we don't exit
429     Timer.get.join
430   end
431   
432   def self.at_exit
433     self.start
434   end
437 at_exit do
438   God.at_exit if $run