| 1 | """Signal handlers for con-duct.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | import logging |
| 5 | import os |
| 6 | import signal |
| 7 | from types import FrameType |
| 8 | from typing import Optional |
| 9 | |
| 10 | lgr = logging.getLogger("con-duct") |
| 11 | |
| 12 | |
| 13 | class SigIntHandler: |
| 14 | """ |
| 15 | Handler of SIGINT signals received by the process running duct. |
| 16 | """ |
| 17 | |
| 18 | def __init__(self, pid: int) -> None: |
| 19 | """ |
| 20 | Parameters |
| 21 | ---------- |
| 22 | pid : int |
| 23 | The PID of the process monitored by duct |
| 24 | """ |
| 25 | self.pid: int = pid |
| 26 | self.sigcount: int = 0 |
| 27 | |
| 28 | def __call__(self, _sig: int, _frame: Optional[FrameType]) -> None: |
| 29 | self.sigcount += 1 |
| 30 | if self.sigcount == 1: |
| 31 | lgr.info("Received SIGINT, passing to command") |
| 32 | os.kill(self.pid, signal.SIGINT) |
| 33 | elif self.sigcount == 2: |
| 34 | lgr.info("Received second SIGINT, again passing to command") |
| 35 | os.kill(self.pid, signal.SIGINT) |
| 36 | elif self.sigcount == 3: |
| 37 | lgr.warning("Received third SIGINT, forcefully killing command process") |
| 38 | os.kill(self.pid, signal.SIGKILL) |
| 39 | elif self.sigcount >= 4: |
| 40 | lgr.critical("Exiting duct, skipping cleanup") |
| 41 | os._exit(1) |