Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/modpoll/modpoll/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import signal
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
Expand Down Expand Up @@ -298,12 +299,22 @@ def _upload(args, report, *, confirm=True):
return True


def _signal_handler(signal_number, frame):
def _request_exit():
if logger:
logger.info(f"Exiting {sys.argv[0]}")
set_threading_event()


def _signal_handler(signal_number, frame):
# Python runs the handler between two bytecodes of the main thread, which may hold
# the exit event's internal (non-reentrant) lock inside delay_thread(); setting the
# event here would then wait for that lock forever. Another thread sets it as soon
# as the main thread lets the lock go.
thread = threading.Thread(target=_request_exit, name="modpoll-exit", daemon=True)
thread.start()
return thread


def setup_logging(level, format):
logging.basicConfig(level=level, format=format)

Expand Down
18 changes: 17 additions & 1 deletion packages/modpoll/tests/test_shutdown.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import signal
import subprocess
import sys

import pytest
Expand Down Expand Up @@ -76,6 +77,21 @@ def test_signal_handler_tolerates_uninitialized_logger(monkeypatch):
monkeypatch.setattr(main, "logger", None)
monkeypatch.setattr(main, "set_threading_event", lambda: called.append(True))

main._signal_handler(signal.SIGTERM, None)
main._signal_handler(signal.SIGTERM, None).join(timeout=5)

assert called == [True]


def test_signal_handler_does_not_wait_for_the_exit_event_lock():
# The signal can arrive while the main thread holds the event's lock in delay_thread().
script = """
from modpoll import main, utils
with utils._thread_event._cond:
thread = main._signal_handler(15, None)
thread.join(timeout=5)
assert utils.on_threading_event()
"""
result = subprocess.run(
[sys.executable, "-c", script], capture_output=True, text=True, timeout=10
)
assert result.returncode == 0, result.stderr
Loading