Module: God

Defined in:
lib/god.rb,
lib/god/task.rb,
lib/god/watch.rb,
lib/god/driver.rb,
lib/god/errors.rb,
lib/god/logger.rb,
lib/god/metric.rb,
lib/god/socket.rb,
lib/god/cli/run.rb,
lib/god/contact.rb,
lib/god/process.rb,
lib/god/trigger.rb,
lib/god/version.rb,
lib/god/behavior.rb,
lib/god/registry.rb,
lib/god/timeline.rb,
lib/god/condition.rb,
lib/god/cli/command.rb,
lib/god/cli/version.rb,
lib/god/configurable.rb,
lib/god/event_handler.rb,
lib/god/simple_logger.rb,
lib/god/contacts/email.rb,
lib/god/contacts/slack.rb,
lib/god/system/process.rb,
lib/god/conditions/tries.rb,
lib/god/contacts/webhook.rb,
lib/god/conditions/always.rb,
lib/god/conditions/lambda.rb,
lib/god/contacts/airbrake.rb,
lib/god/conditions/complex.rb,
lib/god/conditions/flapping.rb,
lib/god/conditions/cpu_usage.rb,
lib/god/conditions/disk_usage.rb,
lib/god/conditions/file_mtime.rb,
lib/god/system/portable_poller.rb,
lib/god/conditions/file_touched.rb,
lib/god/conditions/memory_usage.rb,
lib/god/behaviors/clean_pid_file.rb,
lib/god/conditions/process_exits.rb,
lib/god/system/slash_proc_poller.rb,
lib/god/conditions/process_running.rb,
lib/god/behaviors/clean_unix_socket.rb,
lib/god/conditions/degrading_lambda.rb,
lib/god/conditions/socket_responding.rb,
lib/god/event_handlers/dummy_handler.rb,
lib/god/conditions/http_response_code.rb,
lib/god/event_handlers/kqueue_handler.rb,
lib/god/behaviors/notify_when_flapping.rb,
lib/god/event_handlers/netlink_handler.rb

Defined Under Namespace

Modules: Behaviors, CLI, Conditions, Configurable, Contacts, System Classes: AbstractMethodNotOverriddenError, Behavior, Condition, Contact, Driver, DriverEvent, DriverEventQueue, DriverOperation, DummyHandler, EventCondition, EventHandler, EventRegistrationFailedError, InvalidCommandError, KQueueHandler, Logger, Metric, NetlinkHandler, NoSuchBehaviorError, NoSuchConditionError, NoSuchContactError, NoSuchWatchError, PollCondition, Process, Registry, SimpleLogger, Socket, Task, TimedEvent, Timeline, Trigger, TriggerCondition, Watch

Constant Summary collapse

LOG_BUFFER_SIZE_DEFAULT =

The Integer number of lines of backlog to keep for the logger.

100
PID_FILE_DIRECTORY_DEFAULTS =

An Array of directory paths to be used as the default PID file directory. This list will be searched in order and the first one that has write permissions will be used.

['/var/run/god', '~/.god/pids'].freeze
DRB_PORT_DEFAULT =

The default Integer port number for the DRb communications channel.

17165
DRB_ALLOW_DEFAULT =

The default Array of String IPs that will allow DRb communication access.

['127.0.0.1'].freeze
LOG_LEVEL_DEFAULT =

The default Symbol log level.

:info
TERMINATE_TIMEOUT_DEFAULT =

The default Integer number of seconds to wait for god to terminate when issued the quit command.

10
STOP_TIMEOUT_DEFAULT =

The default Integer number of seconds to wait for a process to terminate.

10
STOP_SIGNAL_DEFAULT =

The default String signal to send for the stop command.

'TERM'
VERSION =

The String version number for this package.

'1.1.1'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.contact_groupsObject

internal



190
191
192
# File 'lib/god.rb', line 190

def contact_groups
  @contact_groups
end

.contactsObject

internal



190
191
192
# File 'lib/god.rb', line 190

def contacts
  @contacts
end

.groupsObject

internal



190
191
192
# File 'lib/god.rb', line 190

def groups
  @groups
end

.initedObject

internal



190
191
192
# File 'lib/god.rb', line 190

def inited
  @inited
end

.mainObject

internal



190
191
192
# File 'lib/god.rb', line 190

def main
  @main
end

.pending_watch_statesObject

internal



190
191
192
# File 'lib/god.rb', line 190

def pending_watch_states
  @pending_watch_states
end

.pending_watchesObject

internal



190
191
192
# File 'lib/god.rb', line 190

def pending_watches
  @pending_watches
end

.runningObject

internal



190
191
192
# File 'lib/god.rb', line 190

def running
  @running
end

.serverObject

internal



190
191
192
# File 'lib/god.rb', line 190

def server
  @server
end

.watchesObject

internal



190
191
192
# File 'lib/god.rb', line 190

def watches
  @watches
end

Class Method Details

.at_exitObject

To be called on program exit to start god.

Returns nothing.



714
715
716
717
# File 'lib/god.rb', line 714

def self.at_exit
  start
  join
end

.contact(kind) {|c| ... } ⇒ Object

Instantiate a new Contact of the given kind and send it to the block. Then prepare, validate, and record the Contact. Aborts on invalid kind, duplicate contact name, invalid contact, or conflicting group name.

kind - The Symbol contact class specifier.

Returns nothing.

Yields:

  • (c)


347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/god.rb', line 347

def self.contact(kind)
  # Ensure internal init has run.
  internal_init

  # Verify contact has been loaded.
  if CONTACT_LOAD_SUCCESS[kind] == false
    applog(nil, :error, "A required dependency for the #{kind} contact is unavailable.")
    applog(nil, :error, 'Run the following commands to install the dependencies:')
    CONTACT_DEPS[kind].each do |d|
      applog(nil, :error, "  [sudo] gem install #{d}")
    end
    abort
  end

  # Create the contact.
  begin
    c = Contact.generate(kind)
  rescue NoSuchContactError => e
    abort e.message
  end

  # Send to block so config can set attributes.
  yield(c) if block_given?

  # Call prepare on the contact.
  c.prepare

  # Remove existing contacts of same name.
  existing_contact = contacts[c.name]
  uncontact(existing_contact) if running && existing_contact

  # Warn and noop if the contact has been defined before.
  if contacts[c.name] || contact_groups[c.name]
    applog(nil, :warn, "Contact name '#{c.name}' already used for a Contact or Contact Group")
    return
  end

  # Abort if the Contact is invalid, the Contact will have printed out its
  # own error messages by now.
  abort 'Exiting on invalid contact' unless Contact.valid?(c) && c.valid?

  # Add to list of contacts.
  contacts[c.name] = c

  # Add to contact group if specified.
  return unless c.group

  # Ensure group name hasn't been used for a contact already.
  abort "Contact Group name '#{c.group}' already used for a Contact" if contacts[c.group]

  contact_groups[c.group] ||= []
  contact_groups[c.group] << c
end

.control(name, command) ⇒ Object

Control the lifecycle of the given task(s).

name - The String name of a task/group. If empty, invokes command for all tasks. command - The String command to run. Valid commands are:

"start", "monitor", "restart", "stop", "unmonitor", "remove".

Returns an Array of String task names affected by the command.



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/god.rb', line 427

def self.control(name, command)
  # Get the list of items.
  items = watches_by_name(name)

  jobs = []

  # Do the command.
  case command
  when 'start', 'monitor'
    items.each { |w| jobs << Thread.new { w.monitor if w.state != :up } }
  when 'restart'
    items.each { |w| jobs << Thread.new { w.move(:restart) } }
  when 'stop'
    items.each do |w|
      jobs << Thread.new do
        w.action(:stop)
        w.unmonitor if w.state != :unmonitored
      end
    end
  when 'unmonitor'
    items.each { |w| jobs << Thread.new { w.unmonitor if w.state != :unmonitored } }
  when 'remove'
    items.each { |w| unwatch(w) }
  else
    raise InvalidCommandError
  end

  jobs.each(&:join)

  items.map(&:name)
end

.internal_initObject

Initialize internal data.

Returns nothing.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/god.rb', line 218

def self.internal_init
  # Only do this once.
  return if inited

  # Variable init.
  self.watches = {}
  self.groups = {}
  self.pending_watches = []
  self.pending_watch_states = {}
  self.contacts = {}
  self.contact_groups = {}

  # Set defaults.
  self.log_buffer_size ||= LOG_BUFFER_SIZE_DEFAULT
  self.port ||= DRB_PORT_DEFAULT
  self.allow ||= DRB_ALLOW_DEFAULT
  self.log_level ||= LOG_LEVEL_DEFAULT
  self.terminate_timeout ||= TERMINATE_TIMEOUT_DEFAULT

  # Additional setup.
  setup

  # Log level.
  log_level_map = { debug: Logger::DEBUG,
                    info: Logger::INFO,
                    warn: Logger::WARN,
                    error: Logger::ERROR,
                    fatal: Logger::FATAL }
  LOG.level = log_level_map[self.log_level]

  # Init has been executed.
  self.inited = true

  # Not yet running.
  self.running = false
end

.joinObject

Prevent god from exiting.

Returns nothing.



702
703
704
# File 'lib/god.rb', line 702

def self.join
  main&.join
end

.load(glob) ⇒ Object

Load the given file(s) according to the given glob.

glob - The glob-enabled String path to load.

Returns nothing.



619
620
621
622
623
# File 'lib/god.rb', line 619

def self.load(glob)
  Dir[glob].each do |f|
    Kernel.load f
  end
end

.pattern_match(pattern, list) ⇒ Object

Match a shortened pattern against a list of String candidates. The pattern is expanded into a regular expression by inserting .* between each character.

pattern - The String containing the abbreviation. list - The Array of Strings to match against.

Examples

list = %w{ foo bar bars }
pattern = 'br'
God.pattern_match(list, pattern)
# => ['bar', 'bars']

Returns the Array of matching name Strings.



736
737
738
739
740
# File 'lib/god.rb', line 736

def self.pattern_match(pattern, list)
  regex = pattern.chars.join('.*')

  list.grep(Regexp.new(regex)).sort_by(&:size)
end

.registryObject



4
5
6
# File 'lib/god/registry.rb', line 4

def self.registry
  @registry ||= Registry.new
end

.running_load(code, filename, action = nil) ⇒ Object

Load a config file into a running god instance. Rescues any exceptions that the config may raise and reports these back to the caller.

code - The String config file contents. filename - The filename of the config file. action - The optional String command specifying how to deal with

existing watches. Valid options are: 'stop', 'remove' or
'leave' (default).

Returns a three-tuple Array [loaded_names, errors, unloaded_names] where:

loaded_names   - The Array of String task names that were loaded.
errors         - The String of error messages produced during the
                 load phase. Will be a blank String if no errors
                 were encountered.
unloaded_names - The Array of String task names that were unloaded
                 from the system (if 'remove' or 'stop' was
                 specified as the action).


555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/god.rb', line 555

def self.running_load(code, filename, action = nil)
  error_message = +''
  loaded_watches = []
  unloaded_watches = []
  jobs = []

  begin
    LOG.start_capture

    Gem.clear_paths
    eval(code, root_binding, filename) # rubocop:disable Security/Eval
    pending_watches.each do |w|
      if (previous_state = pending_watch_states[w.name])
        w.monitor unless previous_state == :unmonitored
      elsif w.autostart?
        w.monitor
      end
    end
    loaded_watches = pending_watches.map(&:name)
    pending_watches.clear
    pending_watch_states.clear

    watches.each do |name, watch|
      next if loaded_watches.include?(name)

      case action
      when 'stop'
        jobs << Thread.new(watch) do |w|
          w.action(:stop)
          unwatch(w)
        end
        unloaded_watches << name
      when 'remove'
        jobs << Thread.new(watch) { |w| unwatch(w) }
        unloaded_watches << name
      when 'leave', '', nil
        # Do nothing
      else
        raise InvalidCommandError, "Unknown action: #{action}"
      end
    end

    # Make sure we quit capturing when we're done.
    LOG.finish_capture
  rescue Exception => e
    # Don't ever let running_load take down god.
    error_message << LOG.finish_capture

    unless e.instance_of?(SystemExit)
      error_message << e.message << "\n"
      error_message << e.backtrace.join("\n")
    end
  end

  jobs.each(&:join)

  [loaded_watches, error_message, unloaded_watches]
end

.running_log(watch_name, since) ⇒ Object

Log lines for the given task since the specified time.

watch_name - The String name of the task (may be abbreviated). since - The Time since which to report log lines.

Raises God::NoSuchWatchError if no tasks matched. Returns the String of newline separated log lines.

Raises:



530
531
532
533
534
535
536
# File 'lib/god.rb', line 530

def self.running_log(watch_name, since)
  matches = pattern_match(watch_name, watches.keys)

  raise NoSuchWatchError unless matches.first

  LOG.watch_log_since(matches.first, since)
end

.setupObject

Setup pid file directory and log system.

Returns nothing.



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/god.rb', line 628

def self.setup
  if pid_file_directory
    dir = File.expand_path(pid_file_directory)
    # Pid file dir was specified, ensure it is created and writable.
    unless File.exist?(dir)
      begin
        FileUtils.mkdir_p(dir)
      rescue Errno::EACCES => e # rubocop:disable Metrics/BlockNesting
        abort "Failed to create pid file directory: #{e.message}"
      end
    end
    abort "The pid file directory (#{dir}) is not writable by #{Etc.getlogin}" unless File.writable?(dir)

    self.pid_file_directory = dir
  else
    # No pid file dir specified, try defaults.
    PID_FILE_DIRECTORY_DEFAULTS.each do |idir|
      dir = File.expand_path(idir)
      begin
        FileUtils.mkdir_p(dir)
        if File.writable?(dir)
          self.pid_file_directory = dir
          break
        end
      rescue Errno::EACCES
        # Ignore errors on directory creation failure here.
      end
    end

    unless pid_file_directory
      dirs = PID_FILE_DIRECTORY_DEFAULTS.map { |x| File.expand_path(x) }
      abort "No pid file directory exists, could be created, or is writable at any of #{dirs.join(', ')}"
    end
  end

  if God::Logger.syslog
    LOG.info('Syslog enabled.')
  else
    LOG.info('Syslog disabled.')
  end

  applog(nil, :info, "Using pid file directory: #{pid_file_directory}")
end

.signal(name, signal) ⇒ Object

Send a signal to each task.

name - The String name of the task or group. signal - The String or integer signal to send. e.g. ‘HUP’, 9.

Returns an Array of String names of the tasks affected.



515
516
517
518
519
520
521
# File 'lib/god.rb', line 515

def self.signal(name, signal)
  items = watches_by_name(name)
  jobs = []
  items.each { |w| jobs << Thread.new { w.signal(signal) } }
  jobs.each(&:join)
  items.map(&:name)
end

.startObject

Initialize and startup the machinery that makes god work.

Returns nothing.



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# File 'lib/god.rb', line 675

def self.start
  internal_init

  # Instantiate server.
  self.server = Socket.new(self.port, socket_user, socket_group, socket_perms)

  # Start monitoring any watches set to autostart.
  watches.each_value { |w| w.monitor if w.autostart? }

  # Clear pending watches.
  pending_watches.clear

  # Mark as running.
  self.running = true

  # Don't exit.
  self.main =
    Thread.new do
      loop do
        sleep 60
      end
    end
end

.statusObject

Gather the status of each task.

Examples

God.status
# => { 'mongrel' => :up, 'nginx' => :up }

Returns a Hash where the key is the String task name and the value is the

Symbol status.


501
502
503
504
505
506
507
# File 'lib/god.rb', line 501

def self.status
  info = {}
  watches.map do |name, w|
    info[name] = { state: w.state, group: w.group }
  end
  info
end

.stop_allObject

Unmonitor and stop all tasks.

Returns true on success, false if all tasks could not be stopped within 10 seconds



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/god.rb', line 463

def self.stop_all
  watches.sort.each do |(_name, w)|
    Thread.new do
      w.action(:stop)
      w.unmonitor if w.state != :unmonitored
    end
  end

  terminate_timeout.times do
    return true if watches.none? { |_name, w| w.alive? }

    sleep 1
  end

  false
end

.task(klass = Task) {|t| ... } ⇒ Object

Instantiate a new, empty Task object and yield it to the mandatory block. The attributes of the task will be set by the configuration file. Aborts on duplicate task name, invalid task, or conflicting group name.

Returns nothing.

Yields:

  • (t)


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/god.rb', line 269

def self.task(klass = Task)
  # Ensure internal init has run.
  internal_init

  t = klass.new
  yield(t)

  # Do the post-configuration.
  t.prepare

  # If running, completely remove the watch (if necessary) to prepare for
  # the reload
  existing_watch = watches[t.name]
  if running && existing_watch
    pending_watch_states[existing_watch.name] = existing_watch.state
    unwatch(existing_watch)
  end

  # Ensure the new watch has a unique name.
  abort "Task name '#{t.name}' already used for a Task or Group" if watches[t.name] || groups[t.name]

  # Ensure watch is internally valid.
  t.valid? || abort("Task '#{t.name}' is not valid (see above)")

  # Add to list of watches.
  watches[t.name] = t

  # Add to pending watches.
  pending_watches << t

  # Add to group if specified.
  if t.group
    # Ensure group name hasn't been used for a watch already.
    abort "Group name '#{t.group}' already used for a Task" if watches[t.group]

    groups[t.group] ||= []
    groups[t.group] << t
  end

  # Register watch.
  t.register!

  # Log.
  if running && existing_watch
    applog(t, :info, "#{t.name} Reloaded config")
  elsif running
    applog(t, :info, "#{t.name} Loaded config")
  end
end

.terminateObject

Force the termination of god.

  • Clean up pid file if one exists

  • Stop DRb service

  • Hard exit using exit!

Never returns because the process will no longer exist!



486
487
488
489
490
# File 'lib/god.rb', line 486

def self.terminate
  FileUtils.rm_f(pid) if pid
  server&.stop
  exit!(0)
end

.uncontact(contact) ⇒ Object

Remove the given contact from god.

contact - The Contact to remove.

Returns nothing.



406
407
408
409
410
411
# File 'lib/god.rb', line 406

def self.uncontact(contact)
  contacts.delete(contact.name)
  return unless contact.group

  contact_groups[contact.group].delete(contact)
end

.unwatch(watch) ⇒ Object

Unmonitor and remove the given watch from god.

watch - The Watch to remove.

Returns nothing.



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/god.rb', line 324

def self.unwatch(watch)
  # Unmonitor.
  watch.unmonitor unless watch.state == :unmonitored

  # Unregister.
  watch.unregister!

  # Remove from watches.
  watches.delete(watch.name)

  # Remove from groups.
  groups[watch.group].delete(watch) if watch.group

  applog(watch, :info, "#{watch.name} unwatched")
end

.versionObject

Returns the version String.



707
708
709
# File 'lib/god.rb', line 707

def self.version
  God::VERSION
end

.watch(&block) ⇒ Object

Instantiate a new, empty Watch object and pass it to the mandatory block. The attributes of the watch will be set by the configuration file. Aborts on duplicate watch name, invalid watch, or conflicting group name.

Returns nothing.



260
261
262
# File 'lib/god.rb', line 260

def self.watch(&block)
  task(Watch, &block)
end

.watches_by_name(name) ⇒ Object



413
414
415
416
417
418
# File 'lib/god.rb', line 413

def self.watches_by_name(name)
  case name
  when '', nil then watches.values.dup
  else Array(watches[name] || groups[name]).dup
  end
end