2014-10-13 15:16:28 +00:00
|
|
|
"""
|
|
|
|
handlers.heartbeat
|
|
|
|
|
|
|
|
A callback-based heartbeat handler
|
|
|
|
|
|
|
|
"""
|
2014-10-13 17:36:19 +00:00
|
|
|
import logging
|
|
|
|
|
|
|
|
from tornado.web import RequestHandler
|
|
|
|
|
2014-11-06 20:01:46 +00:00
|
|
|
version_info = (0, 1, 1)
|
2014-10-13 17:36:19 +00:00
|
|
|
__version__ = '.'.join(str(v) for v in version_info)
|
|
|
|
|
2014-10-14 15:48:28 +00:00
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2014-10-13 17:36:19 +00:00
|
|
|
callbacks = []
|
|
|
|
|
|
|
|
|
|
|
|
class HeartbeatHandler(RequestHandler):
|
|
|
|
"""Heartbeat handler to determine if a service is healthy."""
|
|
|
|
|
|
|
|
def get(self):
|
|
|
|
"""Respond with the health of our service."""
|
|
|
|
if not all(callback() for callback in callbacks):
|
|
|
|
self.set_status(500)
|
2014-11-06 20:01:46 +00:00
|
|
|
return
|
2014-10-13 17:36:19 +00:00
|
|
|
|
|
|
|
self.set_status(204)
|
|
|
|
|
|
|
|
def _log(self):
|
|
|
|
"""Override Tornado to not log 204's from heartbeat."""
|
|
|
|
if self.get_status() != 204:
|
|
|
|
super(HeartbeatHandler, self)._log()
|
|
|
|
|
|
|
|
|
|
|
|
def register_callback(callable_):
|
|
|
|
"""Register a callable to be checked during heartbeat.
|
|
|
|
|
|
|
|
This function adds a new heartbeat callback, which can be any
|
|
|
|
callable that returns ``True`` if healthy, and ``False`` if
|
|
|
|
it detects a problem. Any ``False`` return value will cause
|
|
|
|
a call to the ``HeartbeatHandler`` to return a ``500``.
|
|
|
|
|
|
|
|
"""
|
|
|
|
callbacks.append(callable_)
|
2014-10-14 15:48:28 +00:00
|
|
|
LOGGER.info('Callback %s registered', callable_.__name__)
|