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 TODO: Consider supporting Rails RESTART_FILENAME = 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: BIG_SLEEP = Rails.env.development? ? 10.seconds : 1.minute

1.minute
LITTLE_SLEEP =

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

5.seconds

Instance Method Summary collapse

Instance Method Details

#initializeObject



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

def initialize(*)
  setup_signals

  @start_time = Time.current
end

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



67
68
69
70
71
72
73
# File 'lib/ndr_dev_support/daemon/stoppable.rb', line 67

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

  $stdout.puts(message) unless Rails.env.test? || !$stdout.isatty
  Rails.logger.send(level, message)
end

#run(exit_when_done: false) ⇒ Object



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

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)


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

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

#stopObject



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

def stop
  @should_stop = true
end