1 $:.unshift File.dirname(__FILE__) # For use/testing when no gem is installed
13 require 'god/system/process'
14 require 'god/dependency_graph'
15 require 'god/timeline'
16 require 'god/configurable'
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'
35 require 'god/conditions/disk_usage'
36 require 'god/conditions/complex'
39 require 'god/contacts/email'
49 require 'god/event_handler'
50 require 'god/registry'
55 $:.unshift File.join(File.dirname(__FILE__), *%w[.. ext god])
57 # App wide logging system
59 LOG.datetime_format = "%Y-%m-%d %H:%M:%S "
61 def applog(watch, level, text)
62 LOG.log(watch, level, text)
65 # The $run global determines whether god should be started when the
66 # program would normally end. This should be set to true if when god
67 # should be started (e.g. `god -c <config file>`) and false otherwise
71 GOD_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
73 # Ensure that Syslog is open
80 # Return the binding of god's root level
85 # Load the event handler system
86 God::EventHandler.load
89 alias_method :abort_orig, :abort
93 applog(nil, :error, text) if text
94 # text ? abort_orig(text) : exit(1)
98 alias_method :exit_orig, :exit
107 def safe_attr_accessor(*args)
109 define_method((arg.to_s + "=").intern) do |other|
110 if !self.running && self.inited
111 abort "God.#{arg} must be set before any Tasks are defined"
114 if self.running && self.inited
115 applog(nil, :warn, "God.#{arg} can't be set while god is running")
119 instance_variable_set(('@' + arg.to_s).intern, other)
122 define_method(arg) do
123 instance_variable_get(('@' + arg.to_s).intern)
132 LOG_BUFFER_SIZE_DEFAULT = 1000
133 PID_FILE_DIRECTORY_DEFAULT = '/var/run/god'
134 DRB_PORT_DEFAULT = 17165
135 DRB_ALLOW_DEFAULT = ['127.0.0.1']
139 safe_attr_accessor :pid,
147 attr_accessor :inited,
150 :pending_watch_states,
158 # initialize class instance variables
163 self.log_buffer_size = nil
164 self.pid_file_directory = nil
166 def self.internal_init
168 return if self.inited
173 self.pending_watches = []
174 self.pending_watch_states = {}
176 self.contact_groups = {}
179 self.log_buffer_size ||= LOG_BUFFER_SIZE_DEFAULT
180 self.pid_file_directory ||= PID_FILE_DIRECTORY_DEFAULT
181 self.port ||= DRB_PORT_DEFAULT
182 self.allow ||= DRB_ALLOW_DEFAULT
183 LOG.level = Logger::INFO
185 # init has been executed
192 # Instantiate a new, empty Watch object and pass it to the mandatory
193 # block. The attributes of the watch will be set by the configuration
195 def self.watch(&block)
196 self.task(Watch, &block)
199 # Instantiate a new, empty Task object and pass it to the mandatory
200 # block. The attributes of the task will be set by the configuration
202 def self.task(klass = Task)
208 # do the post-configuration
211 # if running, completely remove the watch (if necessary) to
212 # prepare for the reload
213 existing_watch = self.watches[t.name]
214 if self.running && existing_watch
215 self.pending_watch_states[existing_watch.name] = existing_watch.state
216 self.unwatch(existing_watch)
219 # ensure the new watch has a unique name
220 if self.watches[t.name] || self.groups[t.name]
221 abort "Task name '#{t.name}' already used for a Task or Group"
224 # ensure watch is internally valid
225 t.valid? || abort("Task '#{t.name}' is not valid (see above)")
227 # add to list of watches
228 self.watches[t.name] = t
230 # add to pending watches
231 self.pending_watches << t
233 # add to group if specified
235 # ensure group name hasn't been used for a watch already
236 if self.watches[t.group]
237 abort "Group name '#{t.group}' already used for a Task"
240 self.groups[t.group] ||= []
241 self.groups[t.group] << t
248 if self.running && existing_watch
249 applog(t, :info, "#{t.name} Reloaded config")
251 applog(t, :info, "#{t.name} Loaded config")
255 def self.unwatch(watch)
257 watch.unmonitor unless watch.state == :unmonitored
262 # remove from watches
263 self.watches.delete(watch.name)
267 self.groups[watch.group].delete(watch)
271 def self.contact(kind)
274 # create the condition
276 c = Contact.generate(kind)
277 rescue NoSuchContactError => e
281 # send to block so config can set attributes
282 yield(c) if block_given?
284 # call prepare on the contact
287 # remove existing contacts of same name
288 existing_contact = self.contacts[c.name]
289 if self.running && existing_contact
290 self.uncontact(existing_contact)
293 # ensure the new contact has a unique name
294 if self.contacts[c.name] || self.contact_groups[c.name]
295 abort "Contact name '#{c.name}' already used for a Contact or Contact Group"
298 # abort if the Contact is invalid, the Contact will have printed
299 # out its own error messages by now
300 unless Contact.valid?(c) && c.valid?
301 abort "Exiting on invalid contact"
304 # add to list of contacts
305 self.contacts[c.name] = c
307 # add to contact group if specified
309 # ensure group name hasn't been used for a contact already
310 if self.contacts[c.group]
311 abort "Contact Group name '#{c.group}' already used for a Contact"
314 self.contact_groups[c.group] ||= []
315 self.contact_groups[c.group] << c
319 def self.uncontact(contact)
320 self.contacts.delete(contact.name)
322 self.contact_groups[contact.group].delete(contact)
326 def self.control(name, command)
327 # get the list of watches
328 watches = Array(self.watches[name] || self.groups[name])
334 when "start", "monitor"
335 watches.each { |w| jobs << Thread.new { w.monitor if w.state != :up } }
337 watches.each { |w| jobs << Thread.new { w.move(:restart) } }
339 watches.each { |w| jobs << Thread.new { w.unmonitor.action(:stop) if w.state != :unmonitored } }
341 watches.each { |w| jobs << Thread.new { w.unmonitor if w.state != :unmonitored } }
343 raise InvalidCommandError.new
346 jobs.each { |j| j.join }
348 watches.map { |x| x.name }
352 self.watches.sort.each do |name, w|
354 w.unmonitor if w.state != :unmonitored
355 w.action(:stop) if w.alive?
360 return true unless self.watches.map { |name, w| w.alive? }.any?
367 # Force the termination of god.
368 # * Clean up pid file if one exists
370 # * Hard exit using exit!
372 # Never returns because the process will no longer exist!
374 FileUtils.rm_f(self.pid) if self.pid
375 self.server.stop if self.server
381 self.watches.map do |name, w|
382 info[name] = {:state => w.state}
387 def self.running_log(watch_name, since)
388 unless self.watches[watch_name]
389 raise NoSuchWatchError.new
392 LOG.watch_log_since(watch_name, since)
395 def self.running_load(code, filename)
402 eval(code, root_binding, filename)
403 self.pending_watches.each do |w|
404 if previous_state = self.pending_watch_states[w.name]
405 w.monitor unless previous_state == :unmonitored
407 w.monitor if w.autostart?
410 watches = self.pending_watches.dup
411 self.pending_watches.clear
412 self.pending_watch_states.clear
413 rescue Exception => e
414 # don't ever let running_load take down god
415 errors << LOG.finish_capture
417 unless e.instance_of?(SystemExit)
418 errors << e.message << "\n"
419 errors << e.backtrace.join("\n")
423 names = watches.map { |x| x.name }
428 Dir[glob].each do |f|
435 unless test(?d, self.pid_file_directory)
437 FileUtils.mkdir_p(self.pid_file_directory)
438 rescue Errno::EACCES => e
439 abort "Failed to create pid file directory: #{e.message}"
445 unless test(?w, self.pid_file_directory)
446 abort "The pid file directory (#{self.pid_file_directory}) is not writable by #{Etc.getlogin}"
456 self.server = Socket.new(self.port)
458 # start event handler system
459 EventHandler.start if EventHandler.loaded?
461 # start the timer system
464 # start monitoring any watches set to autostart
465 self.watches.values.each { |w| w.monitor if w.autostart? }
467 # clear pending watches
468 self.pending_watches.clear
473 # join the timer thread so we don't exit