| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import select |
| 5 |
import sys |
| 6 |
from contextlib import contextmanager |
| 7 |
from typing import TYPE_CHECKING, Literal, TypeAlias |
| 8 |
|
| 9 |
import attrs |
| 10 |
import outcome |
| 11 |
|
| 12 |
from .. import _core |
| 13 |
from ._run import _public |
| 14 |
from ._wakeup_socketpair import WakeupSocketpair |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from collections.abc import Callable, Iterator |
| 18 |
|
| 19 |
from .._core import Abort, RaiseCancelT, Task, UnboundedQueue |
| 20 |
from .._file_io import _HasFileNo |
| 21 |
|
| 22 |
assert not TYPE_CHECKING or (sys.platform != "linux" and sys.platform != "win32") |
| 23 |
|
| 24 |
EventResult: TypeAlias = "list[select.kevent]" |
| 25 |
|
| 26 |
|
| 27 |
@attrs.frozen(eq=False) |
| 28 |
class _KqueueStatistics: |
| 29 |
tasks_waiting: int |
| 30 |
monitors: int |
| 31 |
backend: Literal["kqueue"] = attrs.field(init=False, default="kqueue") |
| 32 |
|
| 33 |
|
| 34 |
@attrs.define(eq=False) |
| 35 |
class KqueueIOManager: |
| 36 |
_kqueue: select.kqueue = attrs.Factory(select.kqueue) |
| 37 |
# {(ident, filter): Task or UnboundedQueue} |
| 38 |
_registered: dict[tuple[int, int], Task | UnboundedQueue[select.kevent]] = ( |
| 39 |
attrs.Factory(dict) |
| 40 |
) |
| 41 |
_force_wakeup: WakeupSocketpair = attrs.Factory(WakeupSocketpair) |
| 42 |
_force_wakeup_fd: int | None = None |
| 43 |
|
| 44 |
def __attrs_post_init__(self) -> None: |
| 45 |
force_wakeup_event = select.kevent( |
| 46 |
self._force_wakeup.wakeup_sock, |
| 47 |
select.KQ_FILTER_READ, |
| 48 |
select.KQ_EV_ADD, |
| 49 |
) |
| 50 |
self._kqueue.control([force_wakeup_event], 0) |
| 51 |
self._force_wakeup_fd = self._force_wakeup.wakeup_sock.fileno() |
| 52 |
|
| 53 |
def statistics(self) -> _KqueueStatistics: |
| 54 |
tasks_waiting = 0 |
| 55 |
monitors = 0 |
| 56 |
for receiver in self._registered.values(): |
| 57 |
if type(receiver) is _core.Task: |
| 58 |
tasks_waiting += 1 |
| 59 |
else: |
| 60 |
monitors += 1 |
| 61 |
return _KqueueStatistics(tasks_waiting=tasks_waiting, monitors=monitors) |
| 62 |
|
| 63 |
def close(self) -> None: |
| 64 |
self._kqueue.close() |
| 65 |
self._force_wakeup.close() |
| 66 |
|
| 67 |
def force_wakeup(self) -> None: |
| 68 |
self._force_wakeup.wakeup_thread_and_signal_safe() |
| 69 |
|
| 70 |
def get_events(self, timeout: float) -> EventResult: |
| 71 |
# max_events must be > 0 or kqueue gets cranky |
| 72 |
# and we generally want this to be strictly larger than the actual |
| 73 |
# number of events we get, so that we can tell that we've gotten |
| 74 |
# all the events in just 1 call. |
| 75 |
max_events = len(self._registered) + 1 |
| 76 |
events = [] |
| 77 |
while True: |
| 78 |
batch = self._kqueue.control([], max_events, timeout) |
| 79 |
events += batch |
| 80 |
if len(batch) < max_events: |
| 81 |
break |
| 82 |
else: # TODO: test this line |
| 83 |
timeout = 0 |
| 84 |
# and loop back to the start |
| 85 |
return events |
| 86 |
|
| 87 |
def process_events(self, events: EventResult) -> None: |
| 88 |
for event in events: |
| 89 |
key = (event.ident, event.filter) |
| 90 |
if event.ident == self._force_wakeup_fd: |
| 91 |
self._force_wakeup.drain() |
| 92 |
continue |
| 93 |
receiver = self._registered[key] |
| 94 |
if event.flags & select.KQ_EV_ONESHOT: # TODO: test this branch |
| 95 |
del self._registered[key] |
| 96 |
if isinstance(receiver, _core.Task): |
| 97 |
_core.reschedule(receiver, outcome.Value(event)) |
| 98 |
else: |
| 99 |
receiver.put_nowait(event) # TODO: test this line |
| 100 |
|
| 101 |
# kevent registration is complicated -- e.g. aio submission can |
| 102 |
# implicitly perform a EV_ADD, and EVFILT_PROC with NOTE_TRACK will |
| 103 |
# automatically register filters for child processes. So our lowlevel |
| 104 |
# API is *very* low-level: we expose the kqueue itself for adding |
| 105 |
# events or sticking into AIO submission structs, and split waiting |
| 106 |
# off into separate methods. It's your responsibility to make sure |
| 107 |
# that handle_io never receives an event without a corresponding |
| 108 |
# registration! This may be challenging if you want to be careful |
| 109 |
# about e.g. KeyboardInterrupt. Possibly this API could be improved to |
| 110 |
# be more ergonomic... |
| 111 |
|
| 112 |
@_public |
| 113 |
def current_kqueue(self) -> select.kqueue: |
| 114 |
"""TODO: these are implemented, but are currently more of a sketch than |
| 115 |
anything real. See `#26 |
| 116 |
<https://github.com/python-trio/trio/issues/26>`__. |
| 117 |
""" |
| 118 |
return self._kqueue |
| 119 |
|
| 120 |
@contextmanager |
| 121 |
@_public |
| 122 |
def monitor_kevent( |
| 123 |
self, |
| 124 |
ident: int, |
| 125 |
filter: int, |
| 126 |
) -> Iterator[_core.UnboundedQueue[select.kevent]]: |
| 127 |
"""TODO: these are implemented, but are currently more of a sketch than |
| 128 |
anything real. See `#26 |
| 129 |
<https://github.com/python-trio/trio/issues/26>`__. |
| 130 |
""" |
| 131 |
key = (ident, filter) |
| 132 |
if key in self._registered: |
| 133 |
raise _core.BusyResourceError( |
| 134 |
"attempt to register multiple listeners for same ident/filter pair", |
| 135 |
) |
| 136 |
q = _core.UnboundedQueue[select.kevent]() |
| 137 |
self._registered[key] = q |
| 138 |
try: |
| 139 |
yield q |
| 140 |
finally: |
| 141 |
del self._registered[key] |
| 142 |
|
| 143 |
@_public |
| 144 |
async def wait_kevent( |
| 145 |
self, |
| 146 |
ident: int, |
| 147 |
filter: int, |
| 148 |
abort_func: Callable[[RaiseCancelT], Abort], |
| 149 |
) -> Abort: |
| 150 |
"""TODO: these are implemented, but are currently more of a sketch than |
| 151 |
anything real. See `#26 |
| 152 |
<https://github.com/python-trio/trio/issues/26>`__. |
| 153 |
""" |
| 154 |
key = (ident, filter) |
| 155 |
if key in self._registered: |
| 156 |
raise _core.BusyResourceError( |
| 157 |
"attempt to register multiple listeners for same ident/filter pair", |
| 158 |
) |
| 159 |
self._registered[key] = _core.current_task() |
| 160 |
|
| 161 |
def abort(raise_cancel: RaiseCancelT) -> Abort: |
| 162 |
r = abort_func(raise_cancel) |
| 163 |
if r is _core.Abort.SUCCEEDED: # TODO: test this branch |
| 164 |
del self._registered[key] |
| 165 |
return r |
| 166 |
|
| 167 |
# wait_task_rescheduled does not have its return type typed |
| 168 |
return await _core.wait_task_rescheduled(abort) # type: ignore[no-any-return] |
| 169 |
|
| 170 |
async def _wait_common( |
| 171 |
self, |
| 172 |
fd: int | _HasFileNo, |
| 173 |
filter: int, |
| 174 |
) -> None: |
| 175 |
if not isinstance(fd, int): |
| 176 |
fd = fd.fileno() |
| 177 |
flags = select.KQ_EV_ADD | select.KQ_EV_ONESHOT |
| 178 |
event = select.kevent(fd, filter, flags) |
| 179 |
self._kqueue.control([event], 0) |
| 180 |
|
| 181 |
def abort(_: RaiseCancelT) -> Abort: |
| 182 |
event = select.kevent(fd, filter, select.KQ_EV_DELETE) |
| 183 |
try: |
| 184 |
self._kqueue.control([event], 0) |
| 185 |
except OSError as exc: |
| 186 |
# kqueue tracks individual fds (*not* the underlying file |
| 187 |
# object, see _io_epoll.py for a long discussion of why this |
| 188 |
# distinction matters), and automatically deregisters an event |
| 189 |
# if the fd is closed. So if kqueue.control says that it |
| 190 |
# doesn't know about this event, then probably it's because |
| 191 |
# the fd was closed behind our backs. (Too bad we can't ask it |
| 192 |
# to wake us up when this happens, versus discovering it after |
| 193 |
# the fact... oh well, you can't have everything.) |
| 194 |
# |
| 195 |
# FreeBSD reports this using EBADF. macOS uses ENOENT. |
| 196 |
if exc.errno in (errno.EBADF, errno.ENOENT): # pragma: no branch |
| 197 |
pass |
| 198 |
else: # pragma: no cover |
| 199 |
# As far as we know, this branch can't happen. |
| 200 |
raise |
| 201 |
return _core.Abort.SUCCEEDED |
| 202 |
|
| 203 |
await self.wait_kevent(fd, filter, abort) |
| 204 |
|
| 205 |
@_public |
| 206 |
async def wait_readable(self, fd: int | _HasFileNo) -> None: |
| 207 |
"""Block until the kernel reports that the given object is readable. |
| 208 |
|
| 209 |
On Unix systems, ``fd`` must either be an integer file descriptor, |
| 210 |
or else an object with a ``.fileno()`` method which returns an |
| 211 |
integer file descriptor. Any kind of file descriptor can be passed, |
| 212 |
though the exact semantics will depend on your kernel. For example, |
| 213 |
this probably won't do anything useful for on-disk files. |
| 214 |
|
| 215 |
On Windows systems, ``fd`` must either be an integer ``SOCKET`` |
| 216 |
handle, or else an object with a ``.fileno()`` method which returns |
| 217 |
an integer ``SOCKET`` handle. File descriptors aren't supported, |
| 218 |
and neither are handles that refer to anything besides a |
| 219 |
``SOCKET``. |
| 220 |
|
| 221 |
:raises trio.BusyResourceError: |
| 222 |
if another task is already waiting for the given socket to |
| 223 |
become readable. |
| 224 |
:raises trio.ClosedResourceError: |
| 225 |
if another task calls :func:`notify_closing` while this |
| 226 |
function is still working. |
| 227 |
""" |
| 228 |
await self._wait_common(fd, select.KQ_FILTER_READ) |
| 229 |
|
| 230 |
@_public |
| 231 |
async def wait_writable(self, fd: int | _HasFileNo) -> None: |
| 232 |
"""Block until the kernel reports that the given object is writable. |
| 233 |
|
| 234 |
See `wait_readable` for the definition of ``fd``. |
| 235 |
|
| 236 |
:raises trio.BusyResourceError: |
| 237 |
if another task is already waiting for the given socket to |
| 238 |
become writable. |
| 239 |
:raises trio.ClosedResourceError: |
| 240 |
if another task calls :func:`notify_closing` while this |
| 241 |
function is still working. |
| 242 |
""" |
| 243 |
await self._wait_common(fd, select.KQ_FILTER_WRITE) |
| 244 |
|
| 245 |
@_public |
| 246 |
def notify_closing(self, fd: int | _HasFileNo) -> None: |
| 247 |
"""Notify waiters of the given object that it will be closed. |
| 248 |
|
| 249 |
Call this before closing a file descriptor (on Unix) or socket (on |
| 250 |
Windows). This will cause any `wait_readable` or `wait_writable` |
| 251 |
calls on the given object to immediately wake up and raise |
| 252 |
`~trio.ClosedResourceError`. |
| 253 |
|
| 254 |
This doesn't actually close the object – you still have to do that |
| 255 |
yourself afterwards. Also, you want to be careful to make sure no |
| 256 |
new tasks start waiting on the object in between when you call this |
| 257 |
and when it's actually closed. So to close something properly, you |
| 258 |
usually want to do these steps in order: |
| 259 |
|
| 260 |
1. Explicitly mark the object as closed, so that any new attempts |
| 261 |
to use it will abort before they start. |
| 262 |
2. Call `notify_closing` to wake up any already-existing users. |
| 263 |
3. Actually close the object. |
| 264 |
|
| 265 |
It's also possible to do them in a different order if that's more |
| 266 |
convenient, *but only if* you make sure not to have any checkpoints in |
| 267 |
between the steps. This way they all happen in a single atomic |
| 268 |
step, so other tasks won't be able to tell what order they happened |
| 269 |
in anyway. |
| 270 |
""" |
| 271 |
if not isinstance(fd, int): |
| 272 |
fd = fd.fileno() |
| 273 |
|
| 274 |
for filter_ in [select.KQ_FILTER_READ, select.KQ_FILTER_WRITE]: |
| 275 |
key = (fd, filter_) |
| 276 |
receiver = self._registered.get(key) |
| 277 |
|
| 278 |
if receiver is None: |
| 279 |
continue |
| 280 |
|
| 281 |
if type(receiver) is _core.Task: |
| 282 |
event = select.kevent(fd, filter_, select.KQ_EV_DELETE) |
| 283 |
self._kqueue.control([event], 0) |
| 284 |
exc = _core.ClosedResourceError("another task closed this fd") |
| 285 |
_core.reschedule(receiver, outcome.Error(exc)) |
| 286 |
del self._registered[key] |
| 287 |
else: |
| 288 |
# XX this is an interesting example of a case where being able |
| 289 |
# to close a queue would be useful... |
| 290 |
raise NotImplementedError( |
| 291 |
"can't close an fd that monitor_kevent is using", |
| 292 |
) |