Debian Codegraph @

src/trio/_signals.py

raw
1 from __future__ import annotations
2
3 import signal
4 from collections import OrderedDict
5 from contextlib import contextmanager
6 from typing import TYPE_CHECKING
7
8 import trio
9
10 from ._util import ConflictDetector, is_main_thread
11
12 if TYPE_CHECKING:
13 from collections.abc import AsyncIterator, Callable, Generator, Iterable
14 from types import FrameType
15
16 from typing_extensions import Self
17
18 # Discussion of signal handling strategies:
19 #
20 # - On Windows signals barely exist. There are no options; signal handlers are
21 # the only available API.
22 #
23 # - On Linux signalfd is arguably the natural way. Semantics: signalfd acts as
24 # an *alternative* signal delivery mechanism. The way you use it is to mask
25 # out the relevant signals process-wide (so that they don't get delivered
26 # the normal way), and then when you read from signalfd that actually counts
27 # as delivering it (despite the mask). The problem with this is that we
28 # don't have any reliable way to mask out signals process-wide -- the only
29 # way to do that in Python is to call pthread_sigmask from the main thread
30 # *before starting any other threads*, and as a library we can't really
31 # impose that, and the failure mode is annoying (signals get delivered via
32 # signal handlers whether we want them to or not).
33 #
34 # - on macOS/*BSD, kqueue is the natural way. Semantics: kqueue acts as an
35 # *extra* signal delivery mechanism. Signals are delivered the normal
36 # way, *and* are delivered to kqueue. So you want to set them to SIG_IGN so
37 # that they don't end up pending forever (I guess?). I can't find any actual
38 # docs on how masking and EVFILT_SIGNAL interact. I did see someone note
39 # that if a signal is pending when the kqueue filter is added then you
40 # *don't* get notified of that, which makes sense. But still, we have to
41 # manipulate signal state (e.g. setting SIG_IGN) which as far as Python is
42 # concerned means we have to do this from the main thread.
43 #
44 # So in summary, there don't seem to be any compelling advantages to using the
45 # platform-native signal notification systems; they're kinda nice, but it's
46 # simpler to implement the naive signal-handler-based system once and be
47 # done. (The big advantage would be if there were a reliable way to monitor
48 # for SIGCHLD from outside the main thread and without interfering with other
49 # libraries that also want to monitor for SIGCHLD. But there isn't. I guess
50 # kqueue might give us that, but in kqueue we don't need it, because kqueue
51 # can directly monitor for child process state changes.)
52
53
54 @contextmanager
55 def _signal_handler(
56 signals: Iterable[int],
57 handler: Callable[[int, FrameType | None], object] | int | signal.Handlers | None,
58 ) -> Generator[None, None, None]:
59 original_handlers = {}
60 try:
61 for signum in set(signals):
62 original_handlers[signum] = signal.signal(signum, handler)
63 yield
64 finally:
65 for signum, original_handler in original_handlers.items():
66 signal.signal(signum, original_handler)
67
68
69 class SignalReceiver:
70 def __init__(self) -> None:
71 # {signal num: None}
72 self._pending: OrderedDict[int, None] = OrderedDict()
73 self._lot = trio.lowlevel.ParkingLot()
74 self._conflict_detector = ConflictDetector(
75 "only one task can iterate on a signal receiver at a time",
76 )
77 self._closed = False
78
79 def _add(self, signum: int) -> None:
80 if self._closed:
81 signal.raise_signal(signum)
82 else:
83 self._pending[signum] = None
84 self._lot.unpark()
85
86 def _redeliver_remaining(self) -> None:
87 # First make sure that any signals still in the delivery pipeline will
88 # get redelivered
89 self._closed = True
90
91 # And then redeliver any that are sitting in pending. This is done
92 # using a weird recursive construct to make sure we process everything
93 # even if some of the handlers raise exceptions.
94 def deliver_next() -> None:
95 if self._pending:
96 signum, _ = self._pending.popitem(last=False)
97 try:
98 signal.raise_signal(signum)
99 finally:
100 deliver_next()
101
102 deliver_next()
103
104 def __aiter__(self) -> Self:
105 return self
106
107 async def __anext__(self) -> int:
108 if self._closed:
109 raise RuntimeError("open_signal_receiver block already exited")
110 # In principle it would be possible to support multiple concurrent
111 # calls to __anext__, but doing it without race conditions is quite
112 # tricky, and there doesn't seem to be any point in trying.
113 with self._conflict_detector:
114 if not self._pending:
115 await self._lot.park()
116 else:
117 await trio.lowlevel.checkpoint()
118 signum, _ = self._pending.popitem(last=False)
119 return signum
120
121
122 def get_pending_signal_count(rec: AsyncIterator[int]) -> int:
123 """Helper for tests, not public or otherwise used."""
124 # open_signal_receiver() always produces SignalReceiver, this should not fail.
125 assert isinstance(rec, SignalReceiver)
126 return len(rec._pending)
127
128
129 @contextmanager
130 def open_signal_receiver(
131 *signals: signal.Signals | int,
132 ) -> Generator[AsyncIterator[int], None, None]:
133 """A context manager for catching signals.
134
135 Entering this context manager starts listening for the given signals and
136 returns an async iterator; exiting the context manager stops listening.
137
138 The async iterator blocks until a signal arrives, and then yields it.
139
140 Note that if you leave the ``with`` block while the iterator has
141 unextracted signals still pending inside it, then they will be
142 re-delivered using Python's regular signal handling logic. This avoids a
143 race condition when signals arrives just before we exit the ``with``
144 block.
145
146 Args:
147 signals: the signals to listen for.
148
149 Raises:
150 TypeError: if no signals were provided.
151
152 RuntimeError: if you try to use this anywhere except Python's main
153 thread. (This is a Python limitation.)
154
155 Example:
156
157 A common convention for Unix daemons is that they should reload their
158 configuration when they receive a ``SIGHUP``. Here's a sketch of what
159 that might look like using :func:`open_signal_receiver`::
160
161 with trio.open_signal_receiver(signal.SIGHUP) as signal_aiter:
162 async for signum in signal_aiter:
163 assert signum == signal.SIGHUP
164 reload_configuration()
165
166 """
167 if not signals:
168 raise TypeError("No signals were provided")
169
170 if not is_main_thread():
171 raise RuntimeError(
172 "Sorry, open_signal_receiver is only possible when running in "
173 "Python interpreter's main thread",
174 )
175 token = trio.lowlevel.current_trio_token()
176 queue = SignalReceiver()
177
178 def handler(signum: int, frame: FrameType | None) -> None:
179 token.run_sync_soon(queue._add, signum, idempotent=True)
180
181 try:
182 with _signal_handler(signals, handler):
183 yield queue
184 finally:
185 queue._redeliver_remaining()