Skip to content

Instantly share code, notes, and snippets.

@fadhlirahim
Created May 18, 2016 03:48
Show Gist options
  • Save fadhlirahim/dab759f2ad85027e92970219775b481d to your computer and use it in GitHub Desktop.
Save fadhlirahim/dab759f2ad85027e92970219775b481d to your computer and use it in GitHub Desktop.
A rails rack middleware to check the heartbeat, redis & database connection of your rails app
# Rack middleware to return 200 if service is up
#
# Usage:
#
# GET /hb
#
# GET /db
#
class HeartBeat
OK = [200, {"Content-Type" => "text/plain"}, []].freeze
KO = [500, {"Content-Type" => "text/plain"}, []].freeze
HB_PATH = "/hb".freeze
DB_PATH = "/db".freeze
PONG = "PONG".freeze
def initialize(app)
@app = app
end
def call(env)
case env['PATH_INFO']
when HB_PATH
return all_services_up? ? OK : KO
when DB_PATH
return database_up? ? OK : KO
end
@app.call(env)
end
private
def all_services_up?
redis_up?
end
def redis_up?
$redis_writer.ping == PONG rescue false
end
def database_up?
ActiveRecord::Base.connection_pool.with_connection { |con| con.active? } rescue false
end
end
@dharshan
Copy link

Nice gist. Is there any importance for line number 27?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment