class SinatraHealthCheck::Checker

The application health check. Create an instance and use .health to repond to your health check requests.

Constants

DEFAULT_OPTS

Attributes

health[RW]
systems[R]

Public Class Methods

new(opts = {}) click to toggle source

Create a health checker. Params: aggrgator: an aggregator for substatuus, default: StrictAggregator exit: call exit at the end of graceful_stop +health+: initial health state logger: a logger signals: array of signals to register a graceful stop handler systems: a hash of subsystems responding to .status timeout: timeout for graceful stop in seconds wait: wait before setting health to unhealthy

# File lib/sinatra-health-check/checker.rb, line 31
def initialize(opts = {})
  @opts = DEFAULT_OPTS.merge(opts)
  @aggregator = SinatraHealthCheck::Status::OverwritingAggregator.new(@opts[:aggregator])
  @health = @opts[:health]
  @systems = @opts[:systems]
  trap(@opts[:signals])
end

Public Instance Methods

graceful_stop() click to toggle source

Set application to unhealthy state and stop it after wating for ++@timeout++.

# File lib/sinatra-health-check/checker.rb, line 40
def graceful_stop
  # set to unhealthy state
  unless @stopper
    # spawn a thread to stop application after a given time
    @stopper = Thread.new do
      if @opts[:wait] > 0
        logger.info "asked to stop application, waiting for #{@opts[:wait]}s before doing so" if logger
        sleep @opts[:wait]
      end
      logger.info "stopping application, waiting for #{@opts[:timeout]}s" if logger
      @health = false
      sleep @opts[:timeout]
      logger.info "exit application" if logger
      exit if @opts[:exit]
    end
  end
end
healthy?() click to toggle source
# File lib/sinatra-health-check/checker.rb, line 70
def healthy?
  status.level != :error
end
join() click to toggle source

Waits for the stopping thread to finish

# File lib/sinatra-health-check/checker.rb, line 59
def join
  @stopper.join if @stopper
end
status() click to toggle source

Returns a Status object

# File lib/sinatra-health-check/checker.rb, line 64
def status
  statuus = {}
  systems.each { |k,v| statuus[k] = v.status if v.respond_to?(:status) }
  @aggregator.aggregate(statuus, health ? nil : SinatraHealthCheck::Status.new(:error, 'app is unhealthy'))
end

Private Instance Methods

logger() click to toggle source
# File lib/sinatra-health-check/checker.rb, line 76
def logger
  @opts[:logger]
end
trap(signals) click to toggle source

Register signal handler to stop application gracefully. Params: signals: array of signal names

# File lib/sinatra-health-check/checker.rb, line 83
def trap(signals)
  if signals and signals.size > 0
    logger.info "register graceful stop handler for signals: #{signals.join(', ')}" if logger
    signals.each do |sig|
      Signal.trap(sig) { graceful_stop }
    end
  end
end