cronhub.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import logging
  2. import requests
  3. from borgmatic.hooks.monitoring import monitor
  4. logger = logging.getLogger(__name__)
  5. MONITOR_STATE_TO_CRONHUB = {
  6. monitor.State.START: 'start',
  7. monitor.State.FINISH: 'finish',
  8. monitor.State.FAIL: 'fail',
  9. }
  10. TIMEOUT_SECONDS = 10
  11. def initialize_monitor(
  12. ping_url,
  13. config,
  14. config_filename,
  15. monitoring_log_level,
  16. dry_run,
  17. ): # pragma: no cover
  18. '''
  19. No initialization is necessary for this monitor.
  20. '''
  21. def ping_monitor(hook_config, config, config_filename, state, monitoring_log_level, dry_run):
  22. '''
  23. Ping the configured Cronhub URL, modified with the monitor.State. Use the given configuration
  24. filename in any log entries. If this is a dry run, then don't actually ping anything.
  25. '''
  26. if state not in MONITOR_STATE_TO_CRONHUB:
  27. logger.debug(f'Ignoring unsupported monitoring state {state.name.lower()} in Cronhub hook')
  28. return
  29. dry_run_label = ' (dry run; not actually pinging)' if dry_run else ''
  30. formatted_state = f'/{MONITOR_STATE_TO_CRONHUB[state]}/'
  31. ping_url = (
  32. hook_config['ping_url']
  33. .replace('/start/', formatted_state)
  34. .replace('/ping/', formatted_state)
  35. )
  36. logger.info(f'Pinging Cronhub {state.name.lower()}{dry_run_label}')
  37. logger.debug(f'Using Cronhub ping URL {ping_url}')
  38. if not dry_run:
  39. logging.getLogger('urllib3').setLevel(logging.ERROR)
  40. try:
  41. response = requests.get(
  42. ping_url,
  43. timeout=TIMEOUT_SECONDS,
  44. headers={'User-Agent': 'borgmatic'},
  45. )
  46. if not response.ok:
  47. response.raise_for_status()
  48. except requests.exceptions.RequestException as error:
  49. logger.warning(f'Cronhub error: {error}')
  50. def destroy_monitor(ping_url_or_uuid, config, monitoring_log_level, dry_run): # pragma: no cover
  51. '''
  52. No destruction is necessary for this monitor.
  53. '''