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'
37 require 'god/contacts/email'
47 require 'god/event_handler'
48 require 'god/registry'
53 $:.unshift File.join(File.dirname(__FILE__), *%w[.. ext god])
55 # App wide logging system
57 LOG.datetime_format = "%Y-%m-%d %H:%M:%S "
59 def applog(watch, level, text)
60 LOG.log(watch, level, text)
63 # The $run global determines whether god should be started when the
64 # program would normally end. This should be set to true if when god
65 # should be started (e.g. `god -c <config file>`) and false otherwise
69 GOD_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
71 # Ensure that Syslog is open
78 # Return the binding of god's root level
83 # Load the event handler system
84 God::EventHandler.load
87 alias_method :abort_orig, :abort
91 applog(nil, :error, text) if text
92 # text ? abort_orig(text) : exit(1)
96 alias_method :exit_orig, :exit
105 def safe_attr_accessor(*args)
107 define_method((arg.to_s + "=").intern) do |other|
108 if !self.running && self.inited
109 abort "God.#{arg} must be set before any Tasks are defined"
112 if self.running && self.inited
113 applog(nil, :warn, "God.#{arg} can't be set while god is running")
117 instance_variable_set(('@' + arg.to_s).intern, other)
120 define_method(arg) do
121 instance_variable_get(('@' + arg.to_s).intern)
130 LOG_BUFFER_SIZE_DEFAULT = 1000
131 PID_FILE_DIRECTORY_DEFAULT = '/var/run/god'
132 DRB_PORT_DEFAULT = 17165
133 DRB_ALLOW_DEFAULT = ['127.0.0.1']
137 safe_attr_accessor :host,
144 attr_accessor :inited,
147 :pending_watch_states,
155 # initialize class instance variables
159 self.log_buffer_size = nil
160 self.pid_file_directory = nil
162 def self.internal_init
164 return if self.inited
169 self.pending_watches = []
170 self.pending_watch_states = {}
172 self.contact_groups = {}
175 self.log_buffer_size ||= LOG_BUFFER_SIZE_DEFAULT
176 self.pid_file_directory ||= PID_FILE_DIRECTORY_DEFAULT
177 self.port ||= DRB_PORT_DEFAULT
178 self.allow ||= DRB_ALLOW_DEFAULT
179 LOG.level = Logger::INFO
181 # init has been executed
188 # Instantiate a new, empty Watch object and pass it to the mandatory
189 # block. The attributes of the watch will be set by the configuration
191 def self.watch(&block)
192 self.task(Watch, &block)
195 # Instantiate a new, empty Task object and pass it to the mandatory
196 # block. The attributes of the task will be set by the configuration
198 def self.task(klass = Task)
204 # do the post-configuration
207 # if running, completely remove the watch (if necessary) to
208 # prepare for the reload
209 existing_watch = self.watches[t.name]
210 if self.running && existing_watch
211 self.pending_watch_states[existing_watch.name] = existing_watch.state
212 self.unwatch(existing_watch)
215 # ensure the new watch has a unique name
216 if self.watches[t.name] || self.groups[t.name]
217 abort "Task name '#{t.name}' already used for a Task or Group"
220 # ensure watch is internally valid
221 t.valid? || abort("Task '#{t.name}' is not valid (see above)")
223 # add to list of watches
224 self.watches[t.name] = t
226 # add to pending watches
227 self.pending_watches << t
229 # add to group if specified
231 # ensure group name hasn't been used for a watch already
232 if self.watches[t.group]
233 abort "Group name '#{t.group}' already used for a Task"
236 self.groups[t.group] ||= []
237 self.groups[t.group] << t
244 if self.running && existing_watch
245 applog(t, :info, "#{t.name} Reloaded config")
247 applog(t, :info, "#{t.name} Loaded config")
251 def self.unwatch(watch)
253 watch.unmonitor unless watch.state == :unmonitored
258 # remove from watches
259 self.watches.delete(watch.name)
263 self.groups[watch.group].delete(watch)
267 def self.contact(kind)
270 # create the condition
272 c = Contact.generate(kind)
273 rescue NoSuchContactError => e
277 # send to block so config can set attributes
278 yield(c) if block_given?
280 # call prepare on the contact
283 # remove existing contacts of same name
284 existing_contact = self.contacts[c.name]
285 if self.running && existing_contact
286 self.uncontact(existing_contact)
289 # ensure the new contact has a unique name
290 if self.contacts[c.name] || self.contact_groups[c.name]
291 abort "Contact name '#{c.name}' already used for a Contact or Contact Group"
294 # abort if the Contact is invalid, the Contact will have printed
295 # out its own error messages by now
296 unless Contact.valid?(c) && c.valid?
297 abort "Exiting on invalid contact"
300 # add to list of contacts
301 self.contacts[c.name] = c
303 # add to contact group if specified
305 # ensure group name hasn't been used for a contact already
306 if self.contacts[c.group]
307 abort "Contact Group name '#{c.group}' already used for a Contact"
310 self.contact_groups[c.group] ||= []
311 self.contact_groups[c.group] << c
315 def self.uncontact(contact)
316 self.contacts.delete(contact.name)
318 self.contact_groups[contact.group].delete(contact)
322 def self.control(name, command)
323 # get the list of watches
324 watches = Array(self.watches[name] || self.groups[name])
330 when "start", "monitor"
331 watches.each { |w| jobs << Thread.new { w.monitor if w.state != :up } }
333 watches.each { |w| jobs << Thread.new { w.move(:restart) } }
335 watches.each { |w| jobs << Thread.new { w.unmonitor.action(:stop) if w.state != :unmonitored } }
337 watches.each { |w| jobs << Thread.new { w.unmonitor if w.state != :unmonitored } }
339 raise InvalidCommandError.new
342 jobs.each { |j| j.join }
344 watches.map { |x| x.name }
348 self.watches.sort.each do |name, w|
350 w.unmonitor if w.state != :unmonitored
351 w.action(:stop) if w.alive?
356 return true unless self.watches.map { |name, w| w.alive? }.any?
369 self.watches.map do |name, w|
370 info[name] = {:state => w.state}
375 def self.running_log(watch_name, since)
376 unless self.watches[watch_name]
377 raise NoSuchWatchError.new
380 LOG.watch_log_since(watch_name, since)
383 def self.running_load(code, filename)
390 eval(code, root_binding, filename)
391 self.pending_watches.each do |w|
392 if previous_state = self.pending_watch_states[w.name]
393 w.monitor unless previous_state == :unmonitored
395 w.monitor if w.autostart?
398 watches = self.pending_watches.dup
399 self.pending_watches.clear
400 self.pending_watch_states.clear
401 rescue Exception => e
402 # don't ever let running_load take down god
403 errors << LOG.finish_capture
405 unless e.instance_of?(SystemExit)
406 errors << e.message << "\n"
407 errors << e.backtrace.join("\n")
411 names = watches.map { |x| x.name }
416 Dir[glob].each do |f|
423 unless test(?d, self.pid_file_directory)
425 FileUtils.mkdir_p(self.pid_file_directory)
426 rescue Errno::EACCES => e
427 abort "Failed to create pid file directory: #{e.message}"
433 unless test(?w, self.pid_file_directory)
434 abort "The pid file directory (#{self.pid_file_directory}) is not writable by #{Etc.getlogin}"
444 self.server = Socket.new(self.port)
446 # start event handler system
447 EventHandler.start if EventHandler.loaded?
449 # start the timer system
452 # start monitoring any watches set to autostart
453 self.watches.values.each { |w| w.monitor if w.autostart? }
455 # clear pending watches
456 self.pending_watches.clear
461 # join the timer thread so we don't exit