|
| 1 | +import logging |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from redis import exceptions, Sentinel |
| 5 | + |
| 6 | +from health_check.backends import BaseHealthCheckBackend |
| 7 | +from health_check.exceptions import ServiceUnavailable |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class RedisSentinelHealthCheck(BaseHealthCheckBackend): |
| 13 | + """Health check for Redis Sentinel.""" |
| 14 | + |
| 15 | + redis_sentinels = getattr(settings, 'REDIS_SENTINELS', ()) |
| 16 | + redis_master_name = getattr(settings, 'REDIS_MASTER_NAME', 'mymaster') |
| 17 | + redis_sentinels_healthcheck_socket_timeout = getattr( |
| 18 | + settings, 'REDIS_SENTINELS_HEALTHCHECK_SOCKET_TIMEOUT', 1000 |
| 19 | + ) |
| 20 | + |
| 21 | + def check_status(self, subset=None): |
| 22 | + """Check Redis service by pinging the redis instance with a redis connection.""" |
| 23 | + logger.debug( |
| 24 | + 'Got %s as the redis_sentinels. Connecting to redis...', |
| 25 | + self.redis_sentinels, |
| 26 | + ) |
| 27 | + |
| 28 | + logger.debug('Attempting to connect to redis...') |
| 29 | + try: |
| 30 | + client = self._get_redis_client( |
| 31 | + sentinels=self.redis_sentinels, |
| 32 | + master_name=self.redis_master_name, |
| 33 | + timeout=self.redis_sentinels_healthcheck_socket_timeout, |
| 34 | + ) |
| 35 | + client.ping() |
| 36 | + except ConnectionRefusedError as e: |
| 37 | + self.add_error( |
| 38 | + ServiceUnavailable( |
| 39 | + 'Unable to connect to Redis: Connection was refused.' |
| 40 | + ), |
| 41 | + e, |
| 42 | + ) |
| 43 | + except exceptions.TimeoutError as e: |
| 44 | + self.add_error( |
| 45 | + ServiceUnavailable('Unable to connect to Redis: Timeout.'), e |
| 46 | + ) |
| 47 | + except exceptions.ConnectionError as e: |
| 48 | + self.add_error( |
| 49 | + ServiceUnavailable( |
| 50 | + 'Unable to connect to Redis: Connection Error' |
| 51 | + ), |
| 52 | + e, |
| 53 | + ) |
| 54 | + except BaseException as e: |
| 55 | + self.add_error(ServiceUnavailable('Unknown error'), e) |
| 56 | + else: |
| 57 | + logger.debug('Connection established. Redis is healthy.') |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def _get_redis_client(sentinels, master_name, timeout): |
| 61 | + sentinel = Sentinel(sentinels, socket_timeout=timeout) |
| 62 | + return sentinel.master_for(master_name, socket_timeout=timeout) |
0 commit comments