| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import signal |
| 4 |
import sys |
| 5 |
import weakref |
| 6 |
from typing import TYPE_CHECKING, Generic, Protocol, TypeGuard, TypeVar |
| 7 |
|
| 8 |
import attrs |
| 9 |
|
| 10 |
from .._util import is_main_thread |
| 11 |
from ._run_context import GLOBAL_RUN_CONTEXT |
| 12 |
|
| 13 |
if TYPE_CHECKING: |
| 14 |
import types |
| 15 |
from collections.abc import Callable |
| 16 |
|
| 17 |
from typing_extensions import Self |
| 18 |
# In ordinary single-threaded Python code, when you hit control-C, it raises |
| 19 |
# an exception and automatically does all the regular unwinding stuff. |
| 20 |
# |
| 21 |
# In Trio code, we would like hitting control-C to raise an exception and |
| 22 |
# automatically do all the regular unwinding stuff. In particular, we would |
| 23 |
# like to maintain our invariant that all tasks always run to completion (one |
| 24 |
# way or another), by unwinding all of them. |
| 25 |
# |
| 26 |
# But it's basically impossible to write the core task running code in such a |
| 27 |
# way that it can maintain this invariant in the face of KeyboardInterrupt |
| 28 |
# exceptions arising at arbitrary bytecode positions. Similarly, if a |
| 29 |
# KeyboardInterrupt happened at the wrong moment inside pretty much any of our |
| 30 |
# inter-task synchronization or I/O primitives, then the system state could |
| 31 |
# get corrupted and prevent our being able to clean up properly. |
| 32 |
# |
| 33 |
# So, we need a way to defer KeyboardInterrupt processing from these critical |
| 34 |
# sections. |
| 35 |
# |
| 36 |
# Things that don't work: |
| 37 |
# |
| 38 |
# - Listen for SIGINT and process it in a system task: works fine for |
| 39 |
# well-behaved programs that regularly pass through the event loop, but if |
| 40 |
# user-code goes into an infinite loop then it can't be interrupted. Which |
| 41 |
# is unfortunate, since dealing with infinite loops is what |
| 42 |
# KeyboardInterrupt is for! |
| 43 |
# |
| 44 |
# - Use pthread_sigmask to disable signal delivery during critical section: |
| 45 |
# (a) windows has no pthread_sigmask, (b) python threads start with all |
| 46 |
# signals unblocked, so if there are any threads around they'll receive the |
| 47 |
# signal and then tell the main thread to run the handler, even if the main |
| 48 |
# thread has that signal blocked. |
| 49 |
# |
| 50 |
# - Install a signal handler which checks a global variable to decide whether |
| 51 |
# to raise the exception immediately (if we're in a non-critical section), |
| 52 |
# or to schedule it on the event loop (if we're in a critical section). The |
| 53 |
# problem here is that it's impossible to transition safely out of user code: |
| 54 |
# |
| 55 |
# with keyboard_interrupt_enabled: |
| 56 |
# msg = coro.send(value) |
| 57 |
# |
| 58 |
# If this raises a KeyboardInterrupt, it might be because the coroutine got |
| 59 |
# interrupted and has unwound... or it might be the KeyboardInterrupt |
| 60 |
# arrived just *after* 'send' returned, so the coroutine is still running, |
| 61 |
# but we just lost the message it sent. (And worse, in our actual task |
| 62 |
# runner, the send is hidden inside a utility function etc.) |
| 63 |
# |
| 64 |
# Solution: |
| 65 |
# |
| 66 |
# Mark *stack frames* as being interrupt-safe or interrupt-unsafe, and from |
| 67 |
# the signal handler check which kind of frame we're currently in when |
| 68 |
# deciding whether to raise or schedule the exception. |
| 69 |
# |
| 70 |
# There are still some cases where this can fail, like if someone hits |
| 71 |
# control-C while the process is in the event loop, and then it immediately |
| 72 |
# enters an infinite loop in user code. In this case the user has to hit |
| 73 |
# control-C a second time. And of course if the user code is written so that |
| 74 |
# it doesn't actually exit after a task crashes and everything gets cancelled, |
| 75 |
# then there's not much to be done. (Hitting control-C repeatedly might help, |
| 76 |
# but in general the solution is to kill the process some other way, just like |
| 77 |
# for any Python program that's written to catch and ignore |
| 78 |
# KeyboardInterrupt.) |
| 79 |
|
| 80 |
_T = TypeVar("_T") |
| 81 |
|
| 82 |
|
| 83 |
class _IdRef(weakref.ref[_T]): |
| 84 |
__slots__ = ("_hash",) |
| 85 |
_hash: int |
| 86 |
|
| 87 |
def __new__( |
| 88 |
cls, |
| 89 |
ob: _T, |
| 90 |
callback: Callable[[Self], object] | None = None, |
| 91 |
/, |
| 92 |
) -> Self: |
| 93 |
self: Self = weakref.ref.__new__(cls, ob, callback) |
| 94 |
self._hash = object.__hash__(ob) |
| 95 |
return self |
| 96 |
|
| 97 |
def __eq__(self, other: object) -> bool: |
| 98 |
if self is other: |
| 99 |
return True |
| 100 |
|
| 101 |
if not isinstance(other, _IdRef): |
| 102 |
return NotImplemented |
| 103 |
|
| 104 |
my_obj = None |
| 105 |
try: |
| 106 |
my_obj = self() |
| 107 |
return my_obj is not None and my_obj is other() |
| 108 |
finally: |
| 109 |
del my_obj |
| 110 |
|
| 111 |
# we're overriding a builtin so we do need this |
| 112 |
def __ne__(self, other: object) -> bool: |
| 113 |
return not self == other |
| 114 |
|
| 115 |
def __hash__(self) -> int: |
| 116 |
return self._hash |
| 117 |
|
| 118 |
|
| 119 |
_KT = TypeVar("_KT") |
| 120 |
_VT = TypeVar("_VT") |
| 121 |
|
| 122 |
|
| 123 |
# see also: https://github.com/python/cpython/issues/88306 |
| 124 |
class WeakKeyIdentityDictionary(Generic[_KT, _VT]): |
| 125 |
def __init__(self) -> None: |
| 126 |
self._data: dict[_IdRef[_KT], _VT] = {} |
| 127 |
|
| 128 |
def remove( |
| 129 |
k: _IdRef[_KT], |
| 130 |
selfref: weakref.ref[ |
| 131 |
WeakKeyIdentityDictionary[_KT, _VT] |
| 132 |
] = weakref.ref( # noqa: B008 # function-call-in-default-argument |
| 133 |
self, |
| 134 |
), |
| 135 |
) -> None: |
| 136 |
self = selfref() |
| 137 |
if self is not None: |
| 138 |
try: # noqa: SIM105 # suppressible-exception |
| 139 |
del self._data[k] |
| 140 |
except KeyError: |
| 141 |
pass |
| 142 |
|
| 143 |
self._remove = remove |
| 144 |
|
| 145 |
def __getitem__(self, k: _KT) -> _VT: |
| 146 |
return self._data[_IdRef(k)] |
| 147 |
|
| 148 |
def __setitem__(self, k: _KT, v: _VT) -> None: |
| 149 |
self._data[_IdRef(k, self._remove)] = v |
| 150 |
|
| 151 |
|
| 152 |
_CODE_KI_PROTECTION_STATUS_WMAP: WeakKeyIdentityDictionary[ |
| 153 |
types.CodeType, |
| 154 |
bool, |
| 155 |
] = WeakKeyIdentityDictionary() |
| 156 |
|
| 157 |
|
| 158 |
# This is to support the async_generator package necessary for aclosing on <3.10 |
| 159 |
# functions decorated @async_generator are given this magic property that's a |
| 160 |
# reference to the object itself |
| 161 |
# see python-trio/async_generator/async_generator/_impl.py |
| 162 |
def legacy_isasyncgenfunction( |
| 163 |
obj: object, |
| 164 |
) -> TypeGuard[Callable[..., types.AsyncGeneratorType[object, object]]]: |
| 165 |
return getattr(obj, "_async_gen_function", None) == id(obj) |
| 166 |
|
| 167 |
|
| 168 |
# NB: according to the signal.signal docs, 'frame' can be None on entry to |
| 169 |
# this function: |
| 170 |
def ki_protection_enabled(frame: types.FrameType | None) -> bool: |
| 171 |
try: |
| 172 |
task = GLOBAL_RUN_CONTEXT.task |
| 173 |
except AttributeError: |
| 174 |
task_ki_protected = False |
| 175 |
task_frame = None |
| 176 |
else: |
| 177 |
task_ki_protected = task._ki_protected |
| 178 |
task_frame = task.coro.cr_frame |
| 179 |
|
| 180 |
while frame is not None: |
| 181 |
try: |
| 182 |
v = _CODE_KI_PROTECTION_STATUS_WMAP[frame.f_code] |
| 183 |
except KeyError: |
| 184 |
pass |
| 185 |
else: |
| 186 |
return bool(v) |
| 187 |
if frame.f_code.co_name == "__del__": |
| 188 |
return True |
| 189 |
if frame is task_frame: |
| 190 |
return task_ki_protected |
| 191 |
frame = frame.f_back |
| 192 |
return True |
| 193 |
|
| 194 |
|
| 195 |
def currently_ki_protected() -> bool: |
| 196 |
r"""Check whether the calling code has :exc:`KeyboardInterrupt` protection |
| 197 |
enabled. |
| 198 |
|
| 199 |
It's surprisingly easy to think that one's :exc:`KeyboardInterrupt` |
| 200 |
protection is enabled when it isn't, or vice-versa. This function tells |
| 201 |
you what Trio thinks of the matter, which makes it useful for ``assert``\s |
| 202 |
and unit tests. |
| 203 |
|
| 204 |
Returns: |
| 205 |
bool: True if protection is enabled, and False otherwise. |
| 206 |
|
| 207 |
""" |
| 208 |
return ki_protection_enabled(sys._getframe()) |
| 209 |
|
| 210 |
|
| 211 |
class _SupportsCode(Protocol): |
| 212 |
__code__: types.CodeType |
| 213 |
|
| 214 |
|
| 215 |
_T_supports_code = TypeVar("_T_supports_code", bound=_SupportsCode) |
| 216 |
|
| 217 |
|
| 218 |
def enable_ki_protection(f: _T_supports_code, /) -> _T_supports_code: |
| 219 |
"""Decorator to enable KI protection.""" |
| 220 |
orig = f |
| 221 |
|
| 222 |
if legacy_isasyncgenfunction(f): |
| 223 |
f = f.__wrapped__ # type: ignore |
| 224 |
|
| 225 |
_CODE_KI_PROTECTION_STATUS_WMAP[f.__code__] = True |
| 226 |
return orig |
| 227 |
|
| 228 |
|
| 229 |
def disable_ki_protection(f: _T_supports_code, /) -> _T_supports_code: |
| 230 |
"""Decorator to disable KI protection.""" |
| 231 |
orig = f |
| 232 |
|
| 233 |
if legacy_isasyncgenfunction(f): |
| 234 |
f = f.__wrapped__ # type: ignore |
| 235 |
|
| 236 |
_CODE_KI_PROTECTION_STATUS_WMAP[f.__code__] = False |
| 237 |
return orig |
| 238 |
|
| 239 |
|
| 240 |
@attrs.define(slots=False) |
| 241 |
class KIManager: |
| 242 |
handler: Callable[[int, types.FrameType | None], None] | None = None |
| 243 |
|
| 244 |
def install( |
| 245 |
self, |
| 246 |
deliver_cb: Callable[[], object], |
| 247 |
restrict_keyboard_interrupt_to_checkpoints: bool, |
| 248 |
) -> None: |
| 249 |
assert self.handler is None |
| 250 |
if ( |
| 251 |
not is_main_thread() |
| 252 |
or signal.getsignal(signal.SIGINT) != signal.default_int_handler |
| 253 |
): |
| 254 |
return |
| 255 |
|
| 256 |
def handler(signum: int, frame: types.FrameType | None) -> None: |
| 257 |
assert signum == signal.SIGINT |
| 258 |
protection_enabled = ki_protection_enabled(frame) |
| 259 |
if protection_enabled or restrict_keyboard_interrupt_to_checkpoints: |
| 260 |
deliver_cb() |
| 261 |
else: |
| 262 |
raise KeyboardInterrupt |
| 263 |
|
| 264 |
self.handler = handler |
| 265 |
signal.signal(signal.SIGINT, handler) |
| 266 |
|
| 267 |
def close(self) -> None: |
| 268 |
if self.handler is not None: |
| 269 |
if signal.getsignal(signal.SIGINT) is self.handler: |
| 270 |
signal.signal(signal.SIGINT, signal.default_int_handler) |
| 271 |
self.handler = None |