| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import os |
| 5 |
import sys |
| 6 |
from typing import TYPE_CHECKING, Final as FinalType |
| 7 |
|
| 8 |
import trio |
| 9 |
|
| 10 |
from ._abc import Stream |
| 11 |
from ._util import ConflictDetector, final |
| 12 |
|
| 13 |
assert not TYPE_CHECKING or sys.platform != "win32" |
| 14 |
|
| 15 |
# XX TODO: is this a good number? who knows... it does match the default Linux |
| 16 |
# pipe capacity though. |
| 17 |
DEFAULT_RECEIVE_SIZE: FinalType = 65536 |
| 18 |
|
| 19 |
|
| 20 |
class _FdHolder: |
| 21 |
# This class holds onto a raw file descriptor, in non-blocking mode, and |
| 22 |
# is responsible for managing its lifecycle. In particular, it's |
| 23 |
# responsible for making sure it gets closed, and also for tracking |
| 24 |
# whether it's been closed. |
| 25 |
# |
| 26 |
# The way we track closure is to set the .fd field to -1, discarding the |
| 27 |
# original value. You might think that this is a strange idea, since it |
| 28 |
# overloads the same field to do two different things. Wouldn't it be more |
| 29 |
# natural to have a dedicated .closed field? But that would be more |
| 30 |
# error-prone. Fds are represented by small integers, and once an fd is |
| 31 |
# closed, its integer value may be reused immediately. If we accidentally |
| 32 |
# used the old fd after being closed, we might end up doing something to |
| 33 |
# another unrelated fd that happened to get assigned the same integer |
| 34 |
# value. By throwing away the integer value immediately, it becomes |
| 35 |
# impossible to make this mistake – we'll just get an EBADF. |
| 36 |
# |
| 37 |
# (This trick was copied from the stdlib socket module.) |
| 38 |
fd: int |
| 39 |
|
| 40 |
def __init__(self, fd: int) -> None: |
| 41 |
# make sure self.fd is always initialized to *something*, because even |
| 42 |
# if we error out here then __del__ will run and access it. |
| 43 |
self.fd = -1 |
| 44 |
if not isinstance(fd, int): |
| 45 |
raise TypeError("file descriptor must be an int") |
| 46 |
self.fd = fd |
| 47 |
# Store original state, and ensure non-blocking mode is enabled |
| 48 |
self._original_is_blocking = os.get_blocking(fd) |
| 49 |
os.set_blocking(fd, False) |
| 50 |
|
| 51 |
@property |
| 52 |
def closed(self) -> bool: |
| 53 |
return self.fd == -1 |
| 54 |
|
| 55 |
def _raw_close(self) -> None: |
| 56 |
# This doesn't assume it's in a Trio context, so it can be called from |
| 57 |
# __del__. You should never call it from Trio context, because it |
| 58 |
# skips calling notify_fd_close. But from __del__, skipping that is |
| 59 |
# OK, because notify_fd_close just wakes up other tasks that are |
| 60 |
# waiting on this fd, and those tasks hold a reference to this object. |
| 61 |
# So if __del__ is being called, we know there aren't any tasks that |
| 62 |
# need to be woken. |
| 63 |
if self.closed: |
| 64 |
return |
| 65 |
fd = self.fd |
| 66 |
self.fd = -1 |
| 67 |
os.set_blocking(fd, self._original_is_blocking) |
| 68 |
os.close(fd) |
| 69 |
|
| 70 |
def __del__(self) -> None: |
| 71 |
self._raw_close() |
| 72 |
|
| 73 |
def close(self) -> None: |
| 74 |
if not self.closed: |
| 75 |
trio.lowlevel.notify_closing(self.fd) |
| 76 |
self._raw_close() |
| 77 |
|
| 78 |
|
| 79 |
@final |
| 80 |
class FdStream(Stream): |
| 81 |
"""Represents a stream given the file descriptor to a pipe, TTY, etc. |
| 82 |
|
| 83 |
*fd* must refer to a file that is open for reading and/or writing and |
| 84 |
supports non-blocking I/O (pipes and TTYs will work, on-disk files probably |
| 85 |
not). The returned stream takes ownership of the fd, so closing the stream |
| 86 |
will close the fd too. As with `os.fdopen`, you should not directly use |
| 87 |
an fd after you have wrapped it in a stream using this function. |
| 88 |
|
| 89 |
To be used as a Trio stream, an open file must be placed in non-blocking |
| 90 |
mode. Unfortunately, this impacts all I/O that goes through the |
| 91 |
underlying open file, including I/O that uses a different |
| 92 |
file descriptor than the one that was passed to Trio. If other threads |
| 93 |
or processes are using file descriptors that are related through `os.dup` |
| 94 |
or inheritance across `os.fork` to the one that Trio is using, they are |
| 95 |
unlikely to be prepared to have non-blocking I/O semantics suddenly |
| 96 |
thrust upon them. For example, you can use |
| 97 |
``FdStream(os.dup(sys.stdin.fileno()))`` to obtain a stream for reading |
| 98 |
from standard input, but it is only safe to do so with heavy caveats: your |
| 99 |
stdin must not be shared by any other processes, and you must not make any |
| 100 |
calls to synchronous methods of `sys.stdin` until the stream returned by |
| 101 |
`FdStream` is closed. See `issue #174 |
| 102 |
<https://github.com/python-trio/trio/issues/174>`__ for a discussion of the |
| 103 |
challenges involved in relaxing this restriction. |
| 104 |
|
| 105 |
.. warning:: one specific consequence of non-blocking mode |
| 106 |
applying to the entire open file description is that when |
| 107 |
your program is run with multiple standard streams connected to |
| 108 |
a TTY (as in a terminal emulator), all of the streams become |
| 109 |
non-blocking when you construct an `FdStream` for any of them. |
| 110 |
For example, if you construct an `FdStream` for standard input, |
| 111 |
you might observe Python loggers begin to fail with |
| 112 |
`BlockingIOError`. |
| 113 |
|
| 114 |
Args: |
| 115 |
fd (int): The fd to be wrapped. |
| 116 |
|
| 117 |
Returns: |
| 118 |
A new `FdStream` object. |
| 119 |
""" |
| 120 |
|
| 121 |
def __init__(self, fd: int) -> None: |
| 122 |
self._fd_holder = _FdHolder(fd) |
| 123 |
self._send_conflict_detector = ConflictDetector( |
| 124 |
"another task is using this stream for send", |
| 125 |
) |
| 126 |
self._receive_conflict_detector = ConflictDetector( |
| 127 |
"another task is using this stream for receive", |
| 128 |
) |
| 129 |
|
| 130 |
async def send_all(self, data: bytes | bytearray | memoryview) -> None: |
| 131 |
with self._send_conflict_detector: |
| 132 |
# have to check up front, because send_all(b"") on a closed pipe |
| 133 |
# should raise |
| 134 |
if self._fd_holder.closed: |
| 135 |
raise trio.ClosedResourceError("file was already closed") |
| 136 |
await trio.lowlevel.checkpoint() |
| 137 |
length = len(data) |
| 138 |
# adapted from the SocketStream code |
| 139 |
with memoryview(data) as view: |
| 140 |
sent = 0 |
| 141 |
while sent < length: |
| 142 |
with view[sent:] as remaining: |
| 143 |
try: |
| 144 |
sent += os.write(self._fd_holder.fd, remaining) |
| 145 |
except BlockingIOError: |
| 146 |
await trio.lowlevel.wait_writable(self._fd_holder.fd) |
| 147 |
except OSError as e: |
| 148 |
if e.errno == errno.EBADF: |
| 149 |
raise trio.ClosedResourceError( |
| 150 |
"file was already closed", |
| 151 |
) from None |
| 152 |
else: |
| 153 |
raise trio.BrokenResourceError from e |
| 154 |
|
| 155 |
async def wait_send_all_might_not_block(self) -> None: |
| 156 |
with self._send_conflict_detector: |
| 157 |
if self._fd_holder.closed: |
| 158 |
raise trio.ClosedResourceError("file was already closed") |
| 159 |
await trio.lowlevel.wait_writable(self._fd_holder.fd) |
| 160 |
|
| 161 |
async def receive_some(self, max_bytes: int | None = None) -> bytes: |
| 162 |
with self._receive_conflict_detector: |
| 163 |
if max_bytes is None: |
| 164 |
max_bytes = DEFAULT_RECEIVE_SIZE |
| 165 |
else: |
| 166 |
if not isinstance(max_bytes, int): |
| 167 |
raise TypeError("max_bytes must be integer >= 1") |
| 168 |
if max_bytes < 1: |
| 169 |
raise ValueError("max_bytes must be integer >= 1") |
| 170 |
|
| 171 |
await trio.lowlevel.checkpoint() |
| 172 |
while True: |
| 173 |
try: |
| 174 |
data = os.read(self._fd_holder.fd, max_bytes) |
| 175 |
except BlockingIOError: |
| 176 |
await trio.lowlevel.wait_readable(self._fd_holder.fd) |
| 177 |
except OSError as exc: |
| 178 |
if exc.errno == errno.EBADF: |
| 179 |
raise trio.ClosedResourceError( |
| 180 |
"file was already closed", |
| 181 |
) from None |
| 182 |
else: |
| 183 |
raise trio.BrokenResourceError from exc |
| 184 |
else: |
| 185 |
break |
| 186 |
|
| 187 |
return data |
| 188 |
|
| 189 |
def close(self) -> None: |
| 190 |
self._fd_holder.close() |
| 191 |
|
| 192 |
async def aclose(self) -> None: |
| 193 |
self.close() |
| 194 |
await trio.lowlevel.checkpoint() |
| 195 |
|
| 196 |
def fileno(self) -> int: |
| 197 |
return self._fd_holder.fd |