healthchecks.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import logging
  2. import requests
  3. from borgmatic.hooks import monitor
  4. logger = logging.getLogger(__name__)
  5. MONITOR_STATE_TO_HEALTHCHECKS = {
  6. monitor.State.START: 'start',
  7. monitor.State.FINISH: None, # Healthchecks doesn't append to the URL for the finished state.
  8. monitor.State.FAIL: 'fail',
  9. }
  10. PAYLOAD_TRUNCATION_INDICATOR = '...\n'
  11. DEFAULT_PING_BODY_LIMIT_BYTES = 100000
  12. class Forgetful_buffering_handler(logging.Handler):
  13. '''
  14. A buffering log handler that stores log messages in memory, and throws away messages (oldest
  15. first) once a particular capacity in bytes is reached. But if the given byte capacity is zero,
  16. don't throw away any messages.
  17. '''
  18. def __init__(self, byte_capacity, log_level):
  19. super().__init__()
  20. self.byte_capacity = byte_capacity
  21. self.byte_count = 0
  22. self.buffer = []
  23. self.forgot = False
  24. self.setLevel(log_level)
  25. def emit(self, record):
  26. message = record.getMessage() + '\n'
  27. self.byte_count += len(message)
  28. self.buffer.append(message)
  29. if not self.byte_capacity:
  30. return
  31. while self.byte_count > self.byte_capacity and self.buffer:
  32. self.byte_count -= len(self.buffer[0])
  33. self.buffer.pop(0)
  34. self.forgot = True
  35. def format_buffered_logs_for_payload():
  36. '''
  37. Get the handler previously added to the root logger, and slurp buffered logs out of it to
  38. send to Healthchecks.
  39. '''
  40. try:
  41. buffering_handler = next(
  42. handler
  43. for handler in logging.getLogger().handlers
  44. if isinstance(handler, Forgetful_buffering_handler)
  45. )
  46. except StopIteration:
  47. # No handler means no payload.
  48. return ''
  49. payload = ''.join(message for message in buffering_handler.buffer)
  50. if buffering_handler.forgot:
  51. return PAYLOAD_TRUNCATION_INDICATOR + payload
  52. return payload
  53. def initialize_monitor(hook_config, config_filename, monitoring_log_level, dry_run):
  54. '''
  55. Add a handler to the root logger that stores in memory the most recent logs emitted. That
  56. way, we can send them all to Healthchecks upon a finish or failure state.
  57. '''
  58. ping_body_limit = max(
  59. hook_config.get('ping_body_limit', DEFAULT_PING_BODY_LIMIT_BYTES)
  60. - len(PAYLOAD_TRUNCATION_INDICATOR),
  61. 0,
  62. )
  63. logging.getLogger().addHandler(
  64. Forgetful_buffering_handler(ping_body_limit, monitoring_log_level)
  65. )
  66. def ping_monitor(hook_config, config_filename, state, monitoring_log_level, dry_run):
  67. '''
  68. Ping the configured Healthchecks URL or UUID, modified with the monitor.State. Use the given
  69. configuration filename in any log entries, and log to Healthchecks with the giving log level.
  70. If this is a dry run, then don't actually ping anything.
  71. '''
  72. ping_url = (
  73. hook_config['ping_url']
  74. if hook_config['ping_url'].startswith('http')
  75. else 'https://hc-ping.com/{}'.format(hook_config['ping_url'])
  76. )
  77. dry_run_label = ' (dry run; not actually pinging)' if dry_run else ''
  78. if 'states' in hook_config and state.name.lower() not in hook_config['states']:
  79. logger.info(
  80. f'{config_filename}: Skipping Healthchecks {state.name.lower()} ping due to configured states'
  81. )
  82. return
  83. healthchecks_state = MONITOR_STATE_TO_HEALTHCHECKS.get(state)
  84. if healthchecks_state:
  85. ping_url = '{}/{}'.format(ping_url, healthchecks_state)
  86. logger.info(
  87. '{}: Pinging Healthchecks {}{}'.format(config_filename, state.name.lower(), dry_run_label)
  88. )
  89. logger.debug('{}: Using Healthchecks ping URL {}'.format(config_filename, ping_url))
  90. if state in (monitor.State.FINISH, monitor.State.FAIL):
  91. payload = format_buffered_logs_for_payload()
  92. else:
  93. payload = ''
  94. if not dry_run:
  95. logging.getLogger('urllib3').setLevel(logging.ERROR)
  96. requests.post(ping_url, data=payload.encode('utf-8'))
  97. def destroy_monitor(hook_config, config_filename, monitoring_log_level, dry_run):
  98. '''
  99. Remove the monitor handler that was added to the root logger. This prevents the handler from
  100. getting reused by other instances of this monitor.
  101. '''
  102. logger = logging.getLogger()
  103. for handler in tuple(logger.handlers):
  104. if isinstance(handler, Forgetful_buffering_handler):
  105. logger.removeHandler(handler)