Module: NdrDevSupport::Daemon::Stoppable

Extended by:
ActiveSupport::Concern
Included in:
CIServer
Defined in:
lib/ndr_dev_support/daemon/stoppable.rb

Overview

Behaviour that allows daemons to be restarted, and stopped by god. To use, you need to call ‘super` in the initialize method, if defined.

Constant Summary collapse

RESTART_FILENAME =

touch this file to trigger graceful exit

defined?(Rails) ? Rails.root.join('tmp', 'restart.txt') : 'restart.txt'
MAX_MEMORY =

restart between jobs if memory consumption exceeds this

3.gigabytes
MAX_UPTIME =

restart between jobs if have been up this long

2.hours
BIG_SLEEP =

how long the daemon waits when it runs out of things to do:

1.minute
LITTLE_SLEEP =

when idle, how long the daemon between making restart checks?

5.seconds

Instance Method Summary collapse

Instance Method Details

#initializeObject



29
30
31
32
33
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 29

def initialize(*)
  setup_signals

  @start_time = Time.current
end

#log(message, level = :info) ⇒ Object



70
71
72
73
74
75
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 70

def log(message, level = :info)
  tags    = "[#{Time.current.to_s(:db)}] [#{level.upcase}] [daemon: #{name} (#{Process.pid})]"
  message = "#{tags} #{message}"

  logger.send(level, message)
end

#loggerObject



66
67
68
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 66

def logger
  @logger ||= defined?(Rails) && Rails.logger ? Rails.logger : Logger.new($stdout)
end

#run(exit_when_done: false) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 43

def run(exit_when_done: false)
  loop do
    run_once

    # we've done all we can for the time being; either exit now, or
    # have a sleep and loop round for another go:
    break if exit_when_done
    snooze(BIG_SLEEP)
    # Our snooze may have come to an abrupt end:
    break if should_stop?
  end

  if should_stop?
    # An instruction to stop has been received:
    log('Stopping')
    return :stopped
  else
    # Processing has come to a natural end:
    log('Done, exiting')
    return :exiting
  end
end

#should_stop?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 39

def should_stop?
  @should_stop ||= restart_file_touched? || excessive_memory? || been_up_a_while?
end

#stopObject



35
36
37
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 35

def stop
  @should_stop = true
end