signals.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import logging
  2. import os
  3. import signal
  4. import sys
  5. logger = logging.getLogger(__name__)
  6. EXIT_CODE_FROM_SIGNAL = 128
  7. def handle_signal(signal_number, frame):
  8. '''
  9. Send the signal to all processes in borgmatic's process group, which includes child processes.
  10. '''
  11. # Prevent infinite signal handler recursion. If the parent frame is this very same handler
  12. # function, we know we're recursing.
  13. if frame.f_back.f_code.co_name == handle_signal.__name__:
  14. return
  15. os.killpg(os.getpgrp(), signal_number)
  16. if signal_number == signal.SIGTERM:
  17. logger.critical('Exiting due to TERM signal')
  18. sys.exit(EXIT_CODE_FROM_SIGNAL + signal.SIGTERM)
  19. def configure_signals():
  20. '''
  21. Configure borgmatic's signal handlers to pass relevant signals through to any child processes
  22. like Borg. Note that SIGINT gets passed through even without these changes.
  23. '''
  24. for signal_number in (signal.SIGHUP, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2):
  25. signal.signal(signal_number, handle_signal)