Debian Codegraph @

src/trio/_core/_io_epoll.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import select
5 import sys
6 from collections import defaultdict
7 from typing import TYPE_CHECKING, Literal, TypeAlias
8
9 import attrs
10
11 from .. import _core
12 from ._io_common import wake_all
13 from ._run import Task, _public
14 from ._wakeup_socketpair import WakeupSocketpair
15
16 if TYPE_CHECKING:
17 from .._core import Abort, RaiseCancelT
18 from .._file_io import _HasFileNo
19
20
21 @attrs.define(eq=False)
22 class EpollWaiters:
23 read_task: Task | None = None
24 write_task: Task | None = None
25 current_flags: int = 0
26
27
28 assert not TYPE_CHECKING or sys.platform == "linux"
29
30
31 EventResult: TypeAlias = "list[tuple[int, int]]"
32
33
34 @attrs.frozen(eq=False)
35 class _EpollStatistics:
36 tasks_waiting_read: int
37 tasks_waiting_write: int
38 backend: Literal["epoll"] = attrs.field(init=False, default="epoll")
39
40
41 # Some facts about epoll
42 # ----------------------
43 #
44 # Internally, an epoll object is sort of like a WeakKeyDictionary where the
45 # keys are tuples of (fd number, file object). When you call epoll_ctl, you
46 # pass in an fd; that gets converted to an (fd number, file object) tuple by
47 # looking up the fd in the process's fd table at the time of the call. When an
48 # event happens on the file object, epoll_wait drops the file object part, and
49 # just returns the fd number in its event. So from the outside it looks like
50 # it's keeping a table of fds, but really it's a bit more complicated. This
51 # has some subtle consequences.
52 #
53 # In general, file objects inside the kernel are reference counted. Each entry
54 # in a process's fd table holds a strong reference to the corresponding file
55 # object, and most operations that use file objects take a temporary strong
56 # reference while they're working. So when you call close() on an fd, that
57 # might or might not cause the file object to be deallocated -- it depends on
58 # whether there are any other references to that file object. Some common ways
59 # this can happen:
60 #
61 # - after calling dup(), you have two fds in the same process referring to the
62 # same file object. Even if you close one fd (= remove that entry from the
63 # fd table), the file object will be kept alive by the other fd.
64 # - when calling fork(), the child inherits a copy of the parent's fd table,
65 # so all the file objects get another reference. (But if the fork() is
66 # followed by exec(), then all of the child's fds that have the CLOEXEC flag
67 # set will be closed at that point.)
68 # - most syscalls that work on fds take a strong reference to the underlying
69 # file object while they're using it. So there's one thread blocked in
70 # read(fd), and then another thread calls close() on the last fd referring
71 # to that object, the underlying file won't actually be closed until
72 # after read() returns.
73 #
74 # However, epoll does *not* take a reference to any of the file objects in its
75 # interest set (that's what makes it similar to a WeakKeyDictionary). File
76 # objects inside an epoll interest set will be deallocated if all *other*
77 # references to them are closed. And when that happens, the epoll object will
78 # automatically deregister that file object and stop reporting events on it.
79 # So that's quite handy.
80 #
81 # But, what happens if we do this?
82 #
83 # fd1 = open(...)
84 # epoll_ctl(EPOLL_CTL_ADD, fd1, ...)
85 # fd2 = dup(fd1)
86 # close(fd1)
87 #
88 # In this case, the dup() keeps the underlying file object alive, so it
89 # remains registered in the epoll object's interest set, as the tuple (fd1,
90 # file object). But, fd1 no longer refers to this file object! You might think
91 # there was some magic to handle this, but unfortunately no; the consequences
92 # are totally predictable from what I said above:
93 #
94 # If any events occur on the file object, then epoll will report them as
95 # happening on fd1, even though that doesn't make sense.
96 #
97 # Perhaps we would like to deregister fd1 to stop getting nonsensical events.
98 # But how? When we call epoll_ctl, we have to pass an fd number, which will
99 # get expanded to an (fd number, file object) tuple. We can't pass fd1,
100 # because when epoll_ctl tries to look it up, it won't find our file object.
101 # And we can't pass fd2, because that will get expanded to (fd2, file object),
102 # which is a different lookup key. In fact, it's *impossible* to de-register
103 # this fd!
104 #
105 # We could even have fd1 get assigned to another file object, and then we can
106 # have multiple keys registered simultaneously using the same fd number, like:
107 # (fd1, file object 1), (fd1, file object 2). And if events happen on either
108 # file object, then epoll will happily report that something happened to
109 # "fd1".
110 #
111 # Now here's what makes this especially nasty: suppose the old file object
112 # becomes, say, readable. That means that every time we call epoll_wait, it
113 # will return immediately to tell us that "fd1" is readable. Normally, we
114 # would handle this by de-registering fd1, waking up the corresponding call to
115 # wait_readable, then the user will call read() or recv() or something, and
116 # we're fine. But if this happens on a stale fd where we can't remove the
117 # registration, then we might get stuck in a state where epoll_wait *always*
118 # returns immediately, so our event loop becomes unable to sleep, and now our
119 # program is burning 100% of the CPU doing nothing, with no way out.
120 #
121 #
122 # What does this mean for Trio?
123 # -----------------------------
124 #
125 # Since we don't control the user's code, we have no way to guarantee that we
126 # don't get stuck with stale fd's in our epoll interest set. For example, a
127 # user could call wait_readable(fd) in one task, and then while that's
128 # running, they might close(fd) from another task. In this situation, they're
129 # *supposed* to call notify_closing(fd) to let us know what's happening, so we
130 # can interrupt the wait_readable() call and avoid getting into this mess. And
131 # that's the only thing that can possibly work correctly in all cases. But
132 # sometimes user code has bugs. So if this does happen, we'd like to degrade
133 # gracefully, and survive without corrupting Trio's internal state or
134 # otherwise causing the whole program to explode messily.
135 #
136 # Our solution: we always use EPOLLONESHOT. This way, we might get *one*
137 # spurious event on a stale fd, but then epoll will automatically silence it
138 # until we explicitly say that we want more events... and if we have a stale
139 # fd, then we actually can't re-enable it! So we can't get stuck in an
140 # infinite busy-loop. If there's a stale fd hanging around, then it might
141 # cause a spurious `BusyResourceError`, or cause one wait_* call to return
142 # before it should have... but in general, the wait_* functions are allowed to
143 # have some spurious wakeups; the user code will just attempt the operation,
144 # get EWOULDBLOCK, and call wait_* again. And the program as a whole will
145 # survive, any exceptions will propagate, etc.
146 #
147 # As a bonus, EPOLLONESHOT also saves us having to explicitly deregister fds
148 # on the normal wakeup path, so it's a bit more efficient in general.
149 #
150 # However, EPOLLONESHOT has a few trade-offs to consider:
151 #
152 # First, you can't combine EPOLLONESHOT with EPOLLEXCLUSIVE. This is a bit sad
153 # in one somewhat rare case: if you have a multi-process server where a group
154 # of processes all share the same listening socket, then EPOLLEXCLUSIVE can be
155 # used to avoid "thundering herd" problems when a new connection comes in. But
156 # this isn't too bad. It's not clear if EPOLLEXCLUSIVE even works for us
157 # anyway:
158 #
159 # https://stackoverflow.com/questions/41582560/how-does-epolls-epollexclusive-mode-interact-with-level-triggering
160 #
161 # And it's not clear that EPOLLEXCLUSIVE is a great approach either:
162 #
163 # https://blog.cloudflare.com/the-sad-state-of-linux-socket-balancing/
164 #
165 # And if we do need to support this, we could always add support through some
166 # more-specialized API in the future. So this isn't a blocker to using
167 # EPOLLONESHOT.
168 #
169 # Second, EPOLLONESHOT does not actually *deregister* the fd after delivering
170 # an event (EPOLL_CTL_DEL). Instead, it keeps the fd registered, but
171 # effectively does an EPOLL_CTL_MOD to set the fd's interest flags to
172 # all-zeros. So we could still end up with an fd hanging around in the
173 # interest set for a long time, even if we're not using it.
174 #
175 # Fortunately, this isn't a problem, because it's only a weak reference – if
176 # we have a stale fd that's been silenced by EPOLLONESHOT, then it wastes a
177 # tiny bit of kernel memory remembering this fd that can never be revived, but
178 # when the underlying file object is eventually closed, that memory will be
179 # reclaimed. So that's OK.
180 #
181 # The other issue is that when someone calls wait_*, using EPOLLONESHOT means
182 # that if we have ever waited for this fd before, we have to use EPOLL_CTL_MOD
183 # to re-enable it; but if it's a new fd, we have to use EPOLL_CTL_ADD. How do
184 # we know which one to use? There's no reasonable way to track which fds are
185 # currently registered -- remember, we're assuming the user might have gone
186 # and rearranged their fds without telling us!
187 #
188 # Fortunately, this also has a simple solution: if we wait on a socket or
189 # other fd once, then we'll probably wait on it lots of times. And the epoll
190 # object itself knows which fds it already has registered. So when an fd comes
191 # in, we optimistically assume that it's been waited on before, and try doing
192 # EPOLL_CTL_MOD. And if that fails with an ENOENT error, then we try again
193 # with EPOLL_CTL_ADD.
194 #
195 # So that's why this code is the way it is. And now you know more than you
196 # wanted to about how epoll works.
197
198
199 @attrs.define(eq=False)
200 class EpollIOManager:
201 # Using lambda here because otherwise crash on import with gevent monkey patching
202 # See https://github.com/python-trio/trio/issues/2848
203 _epoll: select.epoll = attrs.Factory(lambda: select.epoll())
204 # {fd: EpollWaiters}
205 _registered: defaultdict[int, EpollWaiters] = attrs.Factory(
206 lambda: defaultdict(EpollWaiters),
207 )
208 _force_wakeup: WakeupSocketpair = attrs.Factory(WakeupSocketpair)
209 _force_wakeup_fd: int | None = None
210
211 def __attrs_post_init__(self) -> None:
212 self._epoll.register(self._force_wakeup.wakeup_sock, select.EPOLLIN)
213 self._force_wakeup_fd = self._force_wakeup.wakeup_sock.fileno()
214
215 def statistics(self) -> _EpollStatistics:
216 tasks_waiting_read = 0
217 tasks_waiting_write = 0
218 for waiter in self._registered.values():
219 if waiter.read_task is not None:
220 tasks_waiting_read += 1
221 if waiter.write_task is not None:
222 tasks_waiting_write += 1
223 return _EpollStatistics(
224 tasks_waiting_read=tasks_waiting_read,
225 tasks_waiting_write=tasks_waiting_write,
226 )
227
228 def close(self) -> None:
229 self._epoll.close()
230 self._force_wakeup.close()
231
232 def force_wakeup(self) -> None:
233 self._force_wakeup.wakeup_thread_and_signal_safe()
234
235 # Return value must be False-y IFF the timeout expired, NOT if any I/O
236 # happened or force_wakeup was called. Otherwise it can be anything; gets
237 # passed straight through to process_events.
238 def get_events(self, timeout: float) -> EventResult:
239 # max_events must be > 0 or epoll gets cranky
240 # accessing self._registered from a thread looks dangerous, but it's
241 # OK because it doesn't matter if our value is a little bit off.
242 max_events = max(1, len(self._registered))
243 return self._epoll.poll(timeout, max_events)
244
245 def process_events(self, events: EventResult) -> None:
246 for fd, flags in events:
247 if fd == self._force_wakeup_fd:
248 self._force_wakeup.drain()
249 continue
250 waiters = self._registered[fd]
251 # EPOLLONESHOT always clears the flags when an event is delivered
252 waiters.current_flags = 0
253 # Clever hack stolen from selectors.EpollSelector: an event
254 # with EPOLLHUP or EPOLLERR flags wakes both readers and
255 # writers.
256 if flags & ~select.EPOLLIN and waiters.write_task is not None:
257 _core.reschedule(waiters.write_task)
258 waiters.write_task = None
259 if flags & ~select.EPOLLOUT and waiters.read_task is not None:
260 _core.reschedule(waiters.read_task)
261 waiters.read_task = None
262 self._update_registrations(fd)
263
264 def _update_registrations(self, fd: int) -> None:
265 waiters = self._registered[fd]
266 wanted_flags = 0
267 if waiters.read_task is not None:
268 wanted_flags |= select.EPOLLIN
269 if waiters.write_task is not None:
270 wanted_flags |= select.EPOLLOUT
271 if wanted_flags != waiters.current_flags:
272 try:
273 try:
274 # First try EPOLL_CTL_MOD
275 self._epoll.modify(fd, wanted_flags | select.EPOLLONESHOT)
276 except OSError:
277 # If that fails, it might be a new fd; try EPOLL_CTL_ADD
278 self._epoll.register(fd, wanted_flags | select.EPOLLONESHOT)
279 waiters.current_flags = wanted_flags
280 except OSError as exc:
281 # If everything fails, probably it's a bad fd, e.g. because
282 # the fd was closed behind our back. In this case we don't
283 # want to try to unregister the fd, because that will probably
284 # fail too. Just clear our state and wake everyone up.
285 del self._registered[fd]
286 # This could raise (in case we're calling this inside one of
287 # the to-be-woken tasks), so we have to do it last.
288 wake_all(waiters, exc)
289 return
290 if not wanted_flags:
291 del self._registered[fd]
292
293 async def _epoll_wait(self, fd: int | _HasFileNo, attr_name: str) -> None:
294 if not isinstance(fd, int):
295 fd = fd.fileno()
296 waiters = self._registered[fd]
297 if getattr(waiters, attr_name) is not None:
298 raise _core.BusyResourceError(
299 "another task is already reading / writing this fd",
300 )
301 setattr(waiters, attr_name, _core.current_task())
302 self._update_registrations(fd)
303
304 def abort(_: RaiseCancelT) -> Abort:
305 setattr(waiters, attr_name, None)
306 self._update_registrations(fd)
307 return _core.Abort.SUCCEEDED
308
309 await _core.wait_task_rescheduled(abort)
310
311 @_public
312 async def wait_readable(self, fd: int | _HasFileNo) -> None:
313 """Block until the kernel reports that the given object is readable.
314
315 On Unix systems, ``fd`` must either be an integer file descriptor,
316 or else an object with a ``.fileno()`` method which returns an
317 integer file descriptor. Any kind of file descriptor can be passed,
318 though the exact semantics will depend on your kernel. For example,
319 this probably won't do anything useful for on-disk files.
320
321 On Windows systems, ``fd`` must either be an integer ``SOCKET``
322 handle, or else an object with a ``.fileno()`` method which returns
323 an integer ``SOCKET`` handle. File descriptors aren't supported,
324 and neither are handles that refer to anything besides a
325 ``SOCKET``.
326
327 :raises trio.BusyResourceError:
328 if another task is already waiting for the given socket to
329 become readable.
330 :raises trio.ClosedResourceError:
331 if another task calls :func:`notify_closing` while this
332 function is still working.
333 """
334 await self._epoll_wait(fd, "read_task")
335
336 @_public
337 async def wait_writable(self, fd: int | _HasFileNo) -> None:
338 """Block until the kernel reports that the given object is writable.
339
340 See `wait_readable` for the definition of ``fd``.
341
342 :raises trio.BusyResourceError:
343 if another task is already waiting for the given socket to
344 become writable.
345 :raises trio.ClosedResourceError:
346 if another task calls :func:`notify_closing` while this
347 function is still working.
348 """
349 await self._epoll_wait(fd, "write_task")
350
351 @_public
352 def notify_closing(self, fd: int | _HasFileNo) -> None:
353 """Notify waiters of the given object that it will be closed.
354
355 Call this before closing a file descriptor (on Unix) or socket (on
356 Windows). This will cause any `wait_readable` or `wait_writable`
357 calls on the given object to immediately wake up and raise
358 `~trio.ClosedResourceError`.
359
360 This doesn't actually close the object – you still have to do that
361 yourself afterwards. Also, you want to be careful to make sure no
362 new tasks start waiting on the object in between when you call this
363 and when it's actually closed. So to close something properly, you
364 usually want to do these steps in order:
365
366 1. Explicitly mark the object as closed, so that any new attempts
367 to use it will abort before they start.
368 2. Call `notify_closing` to wake up any already-existing users.
369 3. Actually close the object.
370
371 It's also possible to do them in a different order if that's more
372 convenient, *but only if* you make sure not to have any checkpoints in
373 between the steps. This way they all happen in a single atomic
374 step, so other tasks won't be able to tell what order they happened
375 in anyway.
376 """
377 if not isinstance(fd, int):
378 fd = fd.fileno()
379 wake_all(
380 self._registered[fd],
381 _core.ClosedResourceError("another task closed this fd"),
382 )
383 del self._registered[fd]
384 with contextlib.suppress(OSError, ValueError):
385 self._epoll.unregister(fd)