Skip to content

Instantly share code, notes, and snippets.

@samuraisam
Created June 19, 2015 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuraisam/692036c83dd8bd43a186 to your computer and use it in GitHub Desktop.
Save samuraisam/692036c83dd8bd43a186 to your computer and use it in GitHub Desktop.
require 'webrick'
require 'json'
require_relative 'health_reporter'
module Geronimo
# Geronimo::HealthServer is a HTTP server which is intended to run alongside
# services which do not have an HTTP server.
#
# For example, a service like Sidekiq might extend the class to offer
# health checks related to Sidekiq functions
#
# class SidekiqHealthServer < Geronimo::HealthServer
# define_check('redis') do |reporter|
# reporter.report_redis
# end
# end
class HealthServer
def initialize(options)
@port = ENV['HEALTHCHECK_SERVER_PORT'].to_i
@health_reporter = Geronimo::HealthReporter.new
@logger = options[:logger]
@server = WEBrick::HTTPServer.new(:Port => @port, :Logger => @logger)
@server.mount_proc '/' do |req, res|
j = handle_web(req, res)
res.status = 200
res['Content-Type'] = 'application/json'
res.body = JSON.generate(j)
end
end
def self.checks
@@checks ||= []
end
def self.define_check(name, &block)
checks.push(block)
end
# return some some data structure which will be marshaled as JSON
def handle_web(req, res)
@@checks.map do |checker|
checker.call(@health_reporter)
end
end
# starts an http server in a thread
def start_server_thread
Thread.start do
@logger.info "Starting health check server on #{@port}"
begin
@server.start
rescue Interrupt
@logger.info "Health check server shut down"
end
end
end
end
end
require 'logger'
class SidekiqHealthServer < Geronimo::HealthServer
define_check('redis') do |reporter|
reporter.report_redis 'sidekiq'
end
end
l = Logger.new(STDOUT)
sq = SidekiqHealthServer.new(logger: l)
sq.start_server_thread.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment