| 1 |
.. currentmodule:: trio |
| 2 |
|
| 3 |
I/O in Trio |
| 4 |
=========== |
| 5 |
|
| 6 |
.. _abstract-stream-api: |
| 7 |
|
| 8 |
The abstract Stream API |
| 9 |
----------------------- |
| 10 |
|
| 11 |
Trio provides a set of abstract base classes that define a standard |
| 12 |
interface for unidirectional and bidirectional byte streams. |
| 13 |
|
| 14 |
Why is this useful? Because it lets you write generic protocol |
| 15 |
implementations that can work over arbitrary transports, and easily |
| 16 |
create complex transport configurations. Here's some examples: |
| 17 |
|
| 18 |
* :class:`trio.SocketStream` wraps a raw socket (like a TCP connection |
| 19 |
over the network), and converts it to the standard stream interface. |
| 20 |
|
| 21 |
* :class:`trio.SSLStream` is a "stream adapter" that can take any |
| 22 |
object that implements the :class:`trio.abc.Stream` interface, and |
| 23 |
convert it into an encrypted stream. In Trio the standard way to |
| 24 |
speak SSL over the network is to wrap an |
| 25 |
:class:`~trio.SSLStream` around a :class:`~trio.SocketStream`. |
| 26 |
|
| 27 |
* If you spawn a :ref:`subprocess <subprocess>`, you can get a |
| 28 |
:class:`~trio.abc.SendStream` that lets you write to its stdin, and |
| 29 |
a :class:`~trio.abc.ReceiveStream` that lets you read from its |
| 30 |
stdout. If for some reason you wanted to speak SSL to a subprocess, |
| 31 |
you could use a :class:`StapledStream` to combine its stdin/stdout |
| 32 |
into a single bidirectional :class:`~trio.abc.Stream`, and then wrap |
| 33 |
that in an :class:`~trio.SSLStream`: |
| 34 |
|
| 35 |
.. code-block:: python |
| 36 |
|
| 37 |
ssl_context = ssl.create_default_context() |
| 38 |
ssl_context.check_hostname = False |
| 39 |
s = SSLStream(StapledStream(process.stdin, process.stdout), ssl_context) |
| 40 |
|
| 41 |
* It sometimes happens that you want to connect to an HTTPS server, |
| 42 |
but you have to go through a web proxy... and the proxy also uses |
| 43 |
HTTPS. So you end up having to do `SSL-on-top-of-SSL |
| 44 |
<https://daniel.haxx.se/blog/2016/11/26/https-proxy-with-curl/>`__. In |
| 45 |
Trio this is trivial – just wrap your first |
| 46 |
:class:`~trio.SSLStream` in a second |
| 47 |
:class:`~trio.SSLStream`: |
| 48 |
|
| 49 |
.. code-block:: python |
| 50 |
|
| 51 |
# Get a raw SocketStream connection to the proxy: |
| 52 |
s0 = await open_tcp_stream("proxy", 443) |
| 53 |
|
| 54 |
# Set up SSL connection to proxy: |
| 55 |
s1 = SSLStream(s0, proxy_ssl_context, server_hostname="proxy") |
| 56 |
# Request a connection to the website |
| 57 |
await s1.send_all(b"CONNECT website:443 / HTTP/1.0\r\n\r\n") |
| 58 |
await check_CONNECT_response(s1) |
| 59 |
|
| 60 |
# Set up SSL connection to the real website. Notice that s1 is |
| 61 |
# already an SSLStream object, and here we're wrapping a second |
| 62 |
# SSLStream object around it. |
| 63 |
s2 = SSLStream(s1, website_ssl_context, server_hostname="website") |
| 64 |
# Make our request |
| 65 |
await s2.send_all(b"GET /index.html HTTP/1.0\r\n\r\n") |
| 66 |
... |
| 67 |
|
| 68 |
* The :mod:`trio.testing` module provides a set of :ref:`flexible |
| 69 |
in-memory stream object implementations <testing-streams>`, so if |
| 70 |
you have a protocol implementation to test then you can start |
| 71 |
two tasks, set up a virtual "socket" connecting them, and then do |
| 72 |
things like inject random-but-repeatable delays into the connection. |
| 73 |
|
| 74 |
|
| 75 |
Abstract base classes |
| 76 |
~~~~~~~~~~~~~~~~~~~~~ |
| 77 |
|
| 78 |
.. currentmodule:: trio.abc |
| 79 |
|
| 80 |
.. http://docutils.sourceforge.net/docs/ref/rst/directives.html#list-table |
| 81 |
|
| 82 |
.. list-table:: Overview: abstract base classes for I/O |
| 83 |
:widths: auto |
| 84 |
:header-rows: 1 |
| 85 |
|
| 86 |
* - Abstract base class |
| 87 |
- Inherits from... |
| 88 |
- Adds these abstract methods... |
| 89 |
- And these concrete methods. |
| 90 |
- Example implementations |
| 91 |
* - :class:`AsyncResource` |
| 92 |
- |
| 93 |
- :meth:`~AsyncResource.aclose` |
| 94 |
- ``__aenter__``, ``__aexit__`` |
| 95 |
- :ref:`async-file-objects` |
| 96 |
* - :class:`SendStream` |
| 97 |
- :class:`AsyncResource` |
| 98 |
- :meth:`~SendStream.send_all`, |
| 99 |
:meth:`~SendStream.wait_send_all_might_not_block` |
| 100 |
- |
| 101 |
- :class:`~trio.testing.MemorySendStream` |
| 102 |
* - :class:`ReceiveStream` |
| 103 |
- :class:`AsyncResource` |
| 104 |
- :meth:`~ReceiveStream.receive_some` |
| 105 |
- ``__aiter__``, ``__anext__`` |
| 106 |
- :class:`~trio.testing.MemoryReceiveStream` |
| 107 |
* - :class:`Stream` |
| 108 |
- :class:`SendStream`, :class:`ReceiveStream` |
| 109 |
- |
| 110 |
- |
| 111 |
- :class:`~trio.SSLStream` |
| 112 |
* - :class:`HalfCloseableStream` |
| 113 |
- :class:`Stream` |
| 114 |
- :meth:`~HalfCloseableStream.send_eof` |
| 115 |
- |
| 116 |
- :class:`~trio.SocketStream`, :class:`~trio.StapledStream` |
| 117 |
* - :class:`Listener` |
| 118 |
- :class:`AsyncResource` |
| 119 |
- :meth:`~Listener.accept` |
| 120 |
- |
| 121 |
- :class:`~trio.SocketListener`, :class:`~trio.SSLListener` |
| 122 |
* - :class:`SendChannel` |
| 123 |
- :class:`AsyncResource` |
| 124 |
- :meth:`~SendChannel.send` |
| 125 |
- |
| 126 |
- `~trio.MemorySendChannel` |
| 127 |
* - :class:`ReceiveChannel` |
| 128 |
- :class:`AsyncResource` |
| 129 |
- :meth:`~ReceiveChannel.receive` |
| 130 |
- ``__aiter__``, ``__anext__`` |
| 131 |
- `~trio.MemoryReceiveChannel` |
| 132 |
* - `Channel` |
| 133 |
- `SendChannel`, `ReceiveChannel` |
| 134 |
- |
| 135 |
- |
| 136 |
- |
| 137 |
|
| 138 |
.. autoclass:: trio.abc.AsyncResource |
| 139 |
:members: |
| 140 |
|
| 141 |
.. currentmodule:: trio |
| 142 |
|
| 143 |
.. autofunction:: aclose_forcefully |
| 144 |
|
| 145 |
.. currentmodule:: trio.abc |
| 146 |
|
| 147 |
.. autoclass:: trio.abc.SendStream |
| 148 |
:members: |
| 149 |
:show-inheritance: |
| 150 |
|
| 151 |
.. autoclass:: trio.abc.ReceiveStream |
| 152 |
:members: |
| 153 |
:show-inheritance: |
| 154 |
|
| 155 |
.. autoclass:: trio.abc.Stream |
| 156 |
:members: |
| 157 |
:show-inheritance: |
| 158 |
|
| 159 |
.. autoclass:: trio.abc.HalfCloseableStream |
| 160 |
:members: |
| 161 |
:show-inheritance: |
| 162 |
|
| 163 |
.. currentmodule:: trio.abc |
| 164 |
|
| 165 |
.. autoclass:: trio.abc.Listener |
| 166 |
:members: |
| 167 |
:show-inheritance: |
| 168 |
|
| 169 |
.. autoclass:: trio.abc.SendChannel |
| 170 |
:members: |
| 171 |
:show-inheritance: |
| 172 |
|
| 173 |
.. autoclass:: trio.abc.ReceiveChannel |
| 174 |
:members: |
| 175 |
:show-inheritance: |
| 176 |
|
| 177 |
.. autoclass:: trio.abc.Channel |
| 178 |
:members: |
| 179 |
:show-inheritance: |
| 180 |
|
| 181 |
.. currentmodule:: trio |
| 182 |
|
| 183 |
|
| 184 |
Generic stream tools |
| 185 |
~~~~~~~~~~~~~~~~~~~~ |
| 186 |
|
| 187 |
Trio currently provides a generic helper for writing servers that |
| 188 |
listen for connections using one or more |
| 189 |
:class:`~trio.abc.Listener`\s, and a generic utility class for working |
| 190 |
with streams. And if you want to test code that's written against the |
| 191 |
streams interface, you should also check out :ref:`testing-streams` in |
| 192 |
:mod:`trio.testing`. |
| 193 |
|
| 194 |
.. autofunction:: serve_listeners |
| 195 |
|
| 196 |
.. autoclass:: StapledStream |
| 197 |
:members: |
| 198 |
:show-inheritance: |
| 199 |
|
| 200 |
|
| 201 |
.. _high-level-networking: |
| 202 |
|
| 203 |
Sockets and networking |
| 204 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 205 |
|
| 206 |
The high-level network interface is built on top of our stream |
| 207 |
abstraction. |
| 208 |
|
| 209 |
.. autofunction:: open_tcp_stream |
| 210 |
|
| 211 |
.. autofunction:: serve_tcp |
| 212 |
|
| 213 |
.. autofunction:: open_ssl_over_tcp_stream |
| 214 |
|
| 215 |
.. autofunction:: serve_ssl_over_tcp |
| 216 |
|
| 217 |
.. autofunction:: open_unix_socket |
| 218 |
|
| 219 |
.. autoclass:: SocketStream |
| 220 |
:members: |
| 221 |
:show-inheritance: |
| 222 |
|
| 223 |
.. autoclass:: SocketListener |
| 224 |
:members: |
| 225 |
:show-inheritance: |
| 226 |
|
| 227 |
.. autofunction:: open_tcp_listeners |
| 228 |
|
| 229 |
.. autofunction:: open_ssl_over_tcp_listeners |
| 230 |
|
| 231 |
|
| 232 |
SSL / TLS support |
| 233 |
~~~~~~~~~~~~~~~~~ |
| 234 |
|
| 235 |
Trio provides SSL/TLS support based on the standard library :mod:`ssl` |
| 236 |
module. Trio's :class:`SSLStream` and :class:`SSLListener` take their |
| 237 |
configuration from a :class:`ssl.SSLContext`, which you can create |
| 238 |
using :func:`ssl.create_default_context` and customize using the |
| 239 |
other constants and functions in the :mod:`ssl` module. |
| 240 |
|
| 241 |
.. warning:: Avoid instantiating :class:`ssl.SSLContext` directly. |
| 242 |
A newly constructed :class:`~ssl.SSLContext` has less secure |
| 243 |
defaults than one returned by :func:`ssl.create_default_context`. |
| 244 |
|
| 245 |
Instead of using :meth:`ssl.SSLContext.wrap_socket`, you |
| 246 |
create a :class:`SSLStream`: |
| 247 |
|
| 248 |
.. autoclass:: SSLStream |
| 249 |
:show-inheritance: |
| 250 |
:members: |
| 251 |
|
| 252 |
And if you're implementing a server, you can use :class:`SSLListener`: |
| 253 |
|
| 254 |
.. autoclass:: SSLListener |
| 255 |
:show-inheritance: |
| 256 |
:members: |
| 257 |
|
| 258 |
Some methods on :class:`SSLStream` raise :exc:`NeedHandshakeError` if |
| 259 |
you call them before the handshake completes: |
| 260 |
|
| 261 |
.. autoexception:: NeedHandshakeError |
| 262 |
|
| 263 |
|
| 264 |
Datagram TLS support |
| 265 |
~~~~~~~~~~~~~~~~~~~~ |
| 266 |
|
| 267 |
Trio also has support for Datagram TLS (DTLS), which is like TLS but |
| 268 |
for unreliable UDP connections. This can be useful for applications |
| 269 |
where TCP's reliable in-order delivery is problematic, like |
| 270 |
teleconferencing, latency-sensitive games, and VPNs. |
| 271 |
|
| 272 |
Currently, using DTLS with Trio requires PyOpenSSL. We hope to |
| 273 |
eventually allow the use of the stdlib `ssl` module as well, but |
| 274 |
unfortunately that's not yet possible. |
| 275 |
|
| 276 |
.. warning:: Note that PyOpenSSL is in many ways lower-level than the |
| 277 |
`ssl` module – in particular, it currently **HAS NO BUILT-IN |
| 278 |
MECHANISM TO VALIDATE CERTIFICATES**. We *strongly* recommend that |
| 279 |
you use the `service-identity |
| 280 |
<https://pypi.org/project/service-identity/>`__ library to validate |
| 281 |
hostnames and certificates. |
| 282 |
|
| 283 |
.. autoclass:: DTLSEndpoint |
| 284 |
|
| 285 |
.. automethod:: connect |
| 286 |
|
| 287 |
.. automethod:: serve |
| 288 |
|
| 289 |
.. automethod:: close |
| 290 |
|
| 291 |
.. autoclass:: DTLSChannel |
| 292 |
:show-inheritance: |
| 293 |
|
| 294 |
.. automethod:: do_handshake |
| 295 |
|
| 296 |
.. automethod:: send |
| 297 |
|
| 298 |
.. automethod:: receive |
| 299 |
|
| 300 |
.. automethod:: close |
| 301 |
|
| 302 |
.. automethod:: aclose |
| 303 |
|
| 304 |
.. automethod:: set_ciphertext_mtu |
| 305 |
|
| 306 |
.. automethod:: get_cleartext_mtu |
| 307 |
|
| 308 |
.. automethod:: statistics |
| 309 |
|
| 310 |
.. autoclass:: DTLSChannelStatistics |
| 311 |
:members: |
| 312 |
|
| 313 |
.. module:: trio.socket |
| 314 |
|
| 315 |
Low-level networking with :mod:`trio.socket` |
| 316 |
--------------------------------------------- |
| 317 |
|
| 318 |
The :mod:`trio.socket` module provides Trio's basic low-level |
| 319 |
networking API. If you're doing ordinary things with stream-oriented |
| 320 |
connections over IPv4/IPv6/Unix domain sockets, then you probably want |
| 321 |
to stick to the high-level API described above. If you want to use |
| 322 |
UDP, or exotic address families like ``AF_BLUETOOTH``, or otherwise |
| 323 |
get direct access to all the quirky bits of your system's networking |
| 324 |
API, then you're in the right place. |
| 325 |
|
| 326 |
|
| 327 |
Top-level exports |
| 328 |
~~~~~~~~~~~~~~~~~ |
| 329 |
|
| 330 |
Generally, the API exposed by :mod:`trio.socket` mirrors that of the |
| 331 |
standard library :mod:`socket` module. Most constants (like |
| 332 |
``SOL_SOCKET``) and simple utilities (like :func:`~socket.inet_aton`) |
| 333 |
are simply re-exported unchanged. But there are also some differences, |
| 334 |
which are described here. |
| 335 |
|
| 336 |
First, Trio provides analogues to all the standard library functions |
| 337 |
that return socket objects; their interface is identical, except that |
| 338 |
they're modified to return Trio socket objects instead: |
| 339 |
|
| 340 |
.. autofunction:: socket |
| 341 |
|
| 342 |
.. autofunction:: socketpair |
| 343 |
|
| 344 |
.. autofunction:: fromfd |
| 345 |
|
| 346 |
.. function:: fromshare(data) |
| 347 |
|
| 348 |
Like :func:`socket.fromshare`, but returns a Trio socket object. |
| 349 |
|
| 350 |
In addition, there is a new function to directly convert a standard |
| 351 |
library socket into a Trio socket: |
| 352 |
|
| 353 |
.. autofunction:: from_stdlib_socket |
| 354 |
|
| 355 |
Unlike :class:`socket.socket`, :func:`trio.socket.socket` is a |
| 356 |
function, not a class; if you want to check whether an object is a |
| 357 |
Trio socket, use ``isinstance(obj, trio.socket.SocketType)``. |
| 358 |
|
| 359 |
For name lookup, Trio provides the standard functions, but with some |
| 360 |
changes: |
| 361 |
|
| 362 |
.. autofunction:: getaddrinfo |
| 363 |
|
| 364 |
.. autofunction:: getnameinfo |
| 365 |
|
| 366 |
.. autofunction:: getprotobyname |
| 367 |
|
| 368 |
Trio intentionally DOES NOT include some obsolete, redundant, or |
| 369 |
broken features: |
| 370 |
|
| 371 |
* :func:`~socket.gethostbyname`, :func:`~socket.gethostbyname_ex`, |
| 372 |
:func:`~socket.gethostbyaddr`: obsolete; use |
| 373 |
:func:`~socket.getaddrinfo` and :func:`~socket.getnameinfo` instead. |
| 374 |
|
| 375 |
* :func:`~socket.getservbyport`: obsolete and `buggy |
| 376 |
<https://bugs.python.org/issue30482>`__; instead, do: |
| 377 |
|
| 378 |
.. code-block:: python |
| 379 |
|
| 380 |
_, service_name = await getnameinfo(('127.0.0.1', port), NI_NUMERICHOST) |
| 381 |
|
| 382 |
* :func:`~socket.getservbyname`: obsolete and `buggy |
| 383 |
<https://bugs.python.org/issue30482>`__; instead, do: |
| 384 |
|
| 385 |
.. code-block:: python |
| 386 |
|
| 387 |
await getaddrinfo(None, service_name) |
| 388 |
|
| 389 |
* :func:`~socket.getfqdn`: obsolete; use :func:`getaddrinfo` with the |
| 390 |
``AI_CANONNAME`` flag. |
| 391 |
|
| 392 |
* :func:`~socket.getdefaulttimeout`, |
| 393 |
:func:`~socket.setdefaulttimeout`: instead, use Trio's standard |
| 394 |
support for :ref:`cancellation`. |
| 395 |
|
| 396 |
* On Windows, ``SO_REUSEADDR`` is not exported, because it's a trap: |
| 397 |
the name is the same as Unix ``SO_REUSEADDR``, but the semantics are |
| 398 |
`different and extremely broken |
| 399 |
<https://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx>`__. In |
| 400 |
the very rare cases where you actually want ``SO_REUSEADDR`` on |
| 401 |
Windows, then it can still be accessed from the standard library's |
| 402 |
:mod:`socket` module. |
| 403 |
|
| 404 |
|
| 405 |
Socket objects |
| 406 |
~~~~~~~~~~~~~~ |
| 407 |
|
| 408 |
.. class:: SocketType |
| 409 |
|
| 410 |
.. note:: :class:`trio.socket.SocketType` is an abstract class and |
| 411 |
cannot be instantiated directly; you get concrete socket objects |
| 412 |
by calling constructors like :func:`trio.socket.socket`. |
| 413 |
However, you can use it to check if an object is a Trio socket |
| 414 |
via ``isinstance(obj, trio.socket.SocketType)``. |
| 415 |
|
| 416 |
Trio socket objects are overall very similar to the :ref:`standard |
| 417 |
library socket objects <python:socket-objects>`, with a few |
| 418 |
important differences: |
| 419 |
|
| 420 |
First, and most obviously, everything is made "Trio-style": |
| 421 |
blocking methods become async methods, and the following attributes |
| 422 |
are *not* supported: |
| 423 |
|
| 424 |
* :meth:`~socket.socket.setblocking`: Trio sockets always act like |
| 425 |
blocking sockets; if you need to read/write from multiple sockets |
| 426 |
at once, then create multiple tasks. |
| 427 |
* :meth:`~socket.socket.settimeout`: see :ref:`cancellation` instead. |
| 428 |
* :meth:`~socket.socket.makefile`: Python's file-like API is |
| 429 |
synchronous, so it can't be implemented on top of an async |
| 430 |
socket. |
| 431 |
* :meth:`~socket.socket.sendall`: Could be supported, but you're |
| 432 |
better off using the higher-level |
| 433 |
:class:`~trio.SocketStream`, and specifically the |
| 434 |
:meth:`~trio.abc.SendStream.send_all` method, which also does |
| 435 |
additional error checking. |
| 436 |
|
| 437 |
In addition, the following methods are similar to the equivalents |
| 438 |
in :class:`socket.socket`, but have some Trio-specific quirks: |
| 439 |
|
| 440 |
.. method:: connect |
| 441 |
:async: |
| 442 |
|
| 443 |
Connect the socket to a remote address. |
| 444 |
|
| 445 |
Similar to :meth:`socket.socket.connect`, except async. |
| 446 |
|
| 447 |
.. warning:: |
| 448 |
|
| 449 |
Due to limitations of the underlying operating system APIs, it is |
| 450 |
not always possible to properly cancel a connection attempt once it |
| 451 |
has begun. If :meth:`connect` is cancelled, and is unable to |
| 452 |
abort the connection attempt, then it will: |
| 453 |
|
| 454 |
1. forcibly close the socket to prevent accidental reuse |
| 455 |
2. raise :exc:`~trio.Cancelled`. |
| 456 |
|
| 457 |
tl;dr: if :meth:`connect` is cancelled then the socket is |
| 458 |
left in an unknown state – possibly open, and possibly |
| 459 |
closed. The only reasonable thing to do is to close it. |
| 460 |
|
| 461 |
.. method:: is_readable |
| 462 |
|
| 463 |
Check whether the socket is readable or not. |
| 464 |
|
| 465 |
.. method:: sendfile |
| 466 |
|
| 467 |
`Not implemented yet! <https://github.com/python-trio/trio/issues/45>`__ |
| 468 |
|
| 469 |
We also keep track of an extra bit of state, because it turns out |
| 470 |
to be useful for :class:`trio.SocketStream`: |
| 471 |
|
| 472 |
.. attribute:: did_shutdown_SHUT_WR |
| 473 |
|
| 474 |
This :class:`bool` attribute is True if you've called |
| 475 |
``sock.shutdown(SHUT_WR)`` or ``sock.shutdown(SHUT_RDWR)``, and |
| 476 |
False otherwise. |
| 477 |
|
| 478 |
The following methods are identical to their equivalents in |
| 479 |
:class:`socket.socket`, except async, and the ones that take address |
| 480 |
arguments require pre-resolved addresses: |
| 481 |
|
| 482 |
* :meth:`~socket.socket.accept` |
| 483 |
* :meth:`~socket.socket.bind` |
| 484 |
* :meth:`~socket.socket.recv` |
| 485 |
* :meth:`~socket.socket.recv_into` |
| 486 |
* :meth:`~socket.socket.recvfrom` |
| 487 |
* :meth:`~socket.socket.recvfrom_into` |
| 488 |
* :meth:`~socket.socket.recvmsg` (if available) |
| 489 |
* :meth:`~socket.socket.recvmsg_into` (if available) |
| 490 |
* :meth:`~socket.socket.send` |
| 491 |
* :meth:`~socket.socket.sendto` |
| 492 |
* :meth:`~socket.socket.sendmsg` (if available) |
| 493 |
|
| 494 |
All methods and attributes *not* mentioned above are identical to |
| 495 |
their equivalents in :class:`socket.socket`: |
| 496 |
|
| 497 |
* :attr:`~socket.socket.family` |
| 498 |
* :attr:`~socket.socket.type` |
| 499 |
* :attr:`~socket.socket.proto` |
| 500 |
* :meth:`~socket.socket.fileno` |
| 501 |
* :meth:`~socket.socket.listen` |
| 502 |
* :meth:`~socket.socket.getpeername` |
| 503 |
* :meth:`~socket.socket.getsockname` |
| 504 |
* :meth:`~socket.socket.close` |
| 505 |
* :meth:`~socket.socket.shutdown` |
| 506 |
* :meth:`~socket.socket.setsockopt` |
| 507 |
* :meth:`~socket.socket.getsockopt` |
| 508 |
* :meth:`~socket.socket.dup` |
| 509 |
* :meth:`~socket.socket.detach` |
| 510 |
* :meth:`~socket.socket.share` |
| 511 |
* :meth:`~socket.socket.set_inheritable` |
| 512 |
* :meth:`~socket.socket.get_inheritable` |
| 513 |
|
| 514 |
|
| 515 |
.. currentmodule:: trio |
| 516 |
|
| 517 |
|
| 518 |
.. _async-file-io: |
| 519 |
|
| 520 |
Asynchronous filesystem I/O |
| 521 |
--------------------------- |
| 522 |
|
| 523 |
Trio provides built-in facilities for performing asynchronous |
| 524 |
filesystem operations like reading or renaming a file. Generally, we |
| 525 |
recommend that you use these instead of Python's normal synchronous |
| 526 |
file APIs. But the tradeoffs here are somewhat subtle: sometimes |
| 527 |
people switch to async I/O, and then they're surprised and confused |
| 528 |
when they find it doesn't speed up their program. The next section |
| 529 |
explains the theory behind async file I/O, to help you better |
| 530 |
understand your code's behavior. Or, if you just want to get started, |
| 531 |
you can :ref:`jump down to the API overview <async-file-io-overview>`. |
| 532 |
|
| 533 |
|
| 534 |
Background: Why is async file I/O useful? The answer may surprise you |
| 535 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 536 |
|
| 537 |
Many people expect that switching from synchronous file I/O to |
| 538 |
async file I/O will always make their program faster. This is not |
| 539 |
true! If we just look at total throughput, then async file I/O might |
| 540 |
be faster, slower, or about the same, and it depends in a complicated |
| 541 |
way on things like your exact patterns of disk access, or how much RAM |
| 542 |
you have. The main motivation for async file I/O is not to improve |
| 543 |
throughput, but to **reduce the frequency of latency glitches.** |
| 544 |
|
| 545 |
To understand why, you need to know two things. |
| 546 |
|
| 547 |
First, right now no mainstream operating system offers a generic, |
| 548 |
reliable, native API for async file or filesystem operations, so we |
| 549 |
have to fake it by using threads (specifically, |
| 550 |
:func:`trio.to_thread.run_sync`). This is cheap but isn't free: on a |
| 551 |
typical PC, dispatching to a worker thread adds something like ~100 µs |
| 552 |
of overhead to each operation. ("µs" is pronounced "microseconds", and |
| 553 |
there are 1,000,000 µs in a second. Note that all the numbers here are |
| 554 |
going to be rough orders of magnitude to give you a sense of scale; if |
| 555 |
you need precise numbers for your environment, measure!) |
| 556 |
|
| 557 |
.. file.read benchmark is |
| 558 |
https://github.com/python-trio/trio/wiki/notes-to-self#file-read-latencypy |
| 559 |
.. Numbers for spinning disks and SSDs are from taking a few random |
| 560 |
recent reviews from http://www.storagereview.com/best_drives and |
| 561 |
looking at their "4K Write Latency" test results for "Average MS" |
| 562 |
and "Max MS": |
| 563 |
http://www.storagereview.com/samsung_ssd_850_evo_ssd_review |
| 564 |
http://www.storagereview.com/wd_black_6tb_hdd_review |
| 565 |
|
| 566 |
And second, the cost of a disk operation is incredibly |
| 567 |
bimodal. Sometimes, the data you need is already cached in RAM, and |
| 568 |
then accessing it is very, very fast – calling :class:`io.FileIO`\'s |
| 569 |
``read`` method on a cached file takes on the order of ~1 µs. But when |
| 570 |
the data isn't cached, then accessing it is much, much slower: the |
| 571 |
average is ~100 µs for SSDs and ~10,000 µs for spinning disks, and if |
| 572 |
you look at tail latencies then for both types of storage you'll see |
| 573 |
cases where occasionally some operation will be 10x or 100x slower |
| 574 |
than average. And that's assuming your program is the only thing |
| 575 |
trying to use that disk – if you're on some oversold cloud VM fighting |
| 576 |
for I/O with other tenants then who knows what will happen. And some |
| 577 |
operations can require multiple disk accesses. |
| 578 |
|
| 579 |
Putting these together: if your data is in RAM then it should be clear |
| 580 |
that using a thread is a terrible idea – if you add 100 µs of overhead |
| 581 |
to a 1 µs operation, then that's a 100x slowdown! On the other hand, |
| 582 |
if your data's on a spinning disk, then using a thread is *great* – |
| 583 |
instead of blocking the main thread and all tasks for 10,000 µs, we |
| 584 |
only block them for 100 µs and can spend the rest of that time running |
| 585 |
other tasks to get useful work done, which can effectively be a 100x |
| 586 |
speedup. |
| 587 |
|
| 588 |
But here's the problem: for any individual I/O operation, there's no |
| 589 |
way to know in advance whether it's going to be one of the fast ones |
| 590 |
or one of the slow ones, so you can't pick and choose. When you switch |
| 591 |
to async file I/O, it makes all the fast operations slower, and all |
| 592 |
the slow operations faster. Is that a win? In terms of overall speed, |
| 593 |
it's hard to say: it depends what kind of disks you're using and your |
| 594 |
kernel's disk cache hit rate, which in turn depends on your file |
| 595 |
access patterns, how much spare RAM you have, the load on your |
| 596 |
service, ... all kinds of things. If the answer is important to you, |
| 597 |
then there's no substitute for measuring your code's actual behavior |
| 598 |
in your actual deployment environment. But what we *can* say is that |
| 599 |
async disk I/O makes performance much more predictable across a wider |
| 600 |
range of runtime conditions. |
| 601 |
|
| 602 |
**If you're not sure what to do, then we recommend that you use async |
| 603 |
disk I/O by default,** because it makes your code more robust when |
| 604 |
conditions are bad, especially with regards to tail latencies; this |
| 605 |
improves the chances that what your users see matches what you saw in |
| 606 |
testing. Blocking the main thread stops *all* tasks from running for |
| 607 |
that time. 10,000 µs is 10 ms, and it doesn't take many 10 ms glitches |
| 608 |
to start adding up to `real money |
| 609 |
<https://google.com/search?q=latency+cost>`__; async disk I/O can help |
| 610 |
prevent those. Just don't expect it to be magic, and be aware of the |
| 611 |
tradeoffs. |
| 612 |
|
| 613 |
|
| 614 |
.. _async-file-io-overview: |
| 615 |
|
| 616 |
API overview |
| 617 |
~~~~~~~~~~~~ |
| 618 |
|
| 619 |
If you want to perform general filesystem operations like creating and |
| 620 |
listing directories, renaming files, or checking file metadata – or if |
| 621 |
you just want a friendly way to work with filesystem paths – then you |
| 622 |
want :class:`trio.Path`. It's an asyncified replacement for the |
| 623 |
standard library's :class:`pathlib.Path`, and provides the same |
| 624 |
comprehensive set of operations. |
| 625 |
|
| 626 |
For reading and writing to files and file-like objects, Trio also |
| 627 |
provides a mechanism for wrapping any synchronous file-like object |
| 628 |
into an asynchronous interface. If you have a :class:`trio.Path` |
| 629 |
object you can get one of these by calling its :meth:`~trio.Path.open` |
| 630 |
method; or if you know the file's name you can open it directly with |
| 631 |
:func:`trio.open_file`. Alternatively, if you already have an open |
| 632 |
file-like object, you can wrap it with :func:`trio.wrap_file` – one |
| 633 |
case where this is especially useful is to wrap :class:`io.BytesIO` or |
| 634 |
:class:`io.StringIO` when writing tests. |
| 635 |
|
| 636 |
|
| 637 |
Asynchronous path objects |
| 638 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 639 |
|
| 640 |
.. autoclass:: Path |
| 641 |
:members: |
| 642 |
:inherited-members: |
| 643 |
|
| 644 |
.. autoclass:: PosixPath |
| 645 |
|
| 646 |
.. autoclass:: WindowsPath |
| 647 |
|
| 648 |
|
| 649 |
.. _async-file-objects: |
| 650 |
|
| 651 |
Asynchronous file objects |
| 652 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 653 |
|
| 654 |
.. Suppress type annotations here, they refer to lots of internal types. |
| 655 |
The normal Python docs go into better detail. |
| 656 |
.. autofunction:: open_file(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=None, opener=None) |
| 657 |
|
| 658 |
.. autofunction:: wrap_file(file) |
| 659 |
|
| 660 |
.. interface:: Asynchronous file interface |
| 661 |
|
| 662 |
Trio's asynchronous file objects have an interface that |
| 663 |
automatically adapts to the object being wrapped. Intuitively, you |
| 664 |
can mostly treat them like a regular :term:`file object`, except |
| 665 |
adding an ``await`` in front of any of methods that do I/O. The |
| 666 |
definition of :term:`file object` is a little vague in Python |
| 667 |
though, so here are the details: |
| 668 |
|
| 669 |
* Synchronous attributes/methods: if any of the following |
| 670 |
attributes or methods are present, then they're re-exported |
| 671 |
unchanged: ``closed``, ``encoding``, ``errors``, ``fileno``, |
| 672 |
``isatty``, ``newlines``, ``readable``, ``seekable``, |
| 673 |
``writable``, ``buffer``, ``raw``, ``line_buffering``, |
| 674 |
``closefd``, ``name``, ``mode``, ``getvalue``, ``getbuffer``. |
| 675 |
|
| 676 |
* Async methods: if any of the following methods are present, then |
| 677 |
they're re-exported as an async method: ``flush``, ``read``, |
| 678 |
``read1``, ``readall``, ``readinto``, ``readline``, |
| 679 |
``readlines``, ``seek``, ``tell``, ``truncate``, ``write``, |
| 680 |
``writelines``, ``readinto1``, ``peek``, ``detach``. |
| 681 |
|
| 682 |
Special notes: |
| 683 |
|
| 684 |
* Async file objects implement Trio's |
| 685 |
:class:`~trio.abc.AsyncResource` interface: you close them by |
| 686 |
calling :meth:`~trio.abc.AsyncResource.aclose` instead of |
| 687 |
``close`` (!!), and they can be used as async context |
| 688 |
managers. Like all :meth:`~trio.abc.AsyncResource.aclose` |
| 689 |
methods, the ``aclose`` method on async file objects is |
| 690 |
guaranteed to close the file before returning, even if it is |
| 691 |
cancelled or otherwise raises an error. |
| 692 |
|
| 693 |
* Using the same async file object from multiple tasks |
| 694 |
simultaneously: because the async methods on async file objects |
| 695 |
are implemented using threads, it's only safe to call two of them |
| 696 |
at the same time from different tasks IF the underlying |
| 697 |
synchronous file object is thread-safe. You should consult the |
| 698 |
documentation for the object you're wrapping. For objects |
| 699 |
returned from :func:`trio.open_file` or :meth:`trio.Path.open`, |
| 700 |
it depends on whether you open the file in binary mode or text |
| 701 |
mode: `binary mode files are task-safe/thread-safe, text mode |
| 702 |
files are not |
| 703 |
<https://docs.python.org/3/library/io.html#multi-threading>`__. |
| 704 |
|
| 705 |
* Async file objects can be used as async iterators to iterate over |
| 706 |
the lines of the file: |
| 707 |
|
| 708 |
.. code-block:: python |
| 709 |
|
| 710 |
async with await trio.open_file(...) as f: |
| 711 |
async for line in f: |
| 712 |
print(line) |
| 713 |
|
| 714 |
* The ``detach`` method, if present, returns an async file object. |
| 715 |
|
| 716 |
This should include all the attributes exposed by classes in |
| 717 |
:mod:`io`. But if you're wrapping an object that has other |
| 718 |
attributes that aren't on the list above, then you can access them |
| 719 |
via the ``.wrapped`` attribute: |
| 720 |
|
| 721 |
.. attribute:: wrapped |
| 722 |
|
| 723 |
The underlying synchronous file object. |
| 724 |
|
| 725 |
|
| 726 |
.. _subprocess: |
| 727 |
|
| 728 |
Spawning subprocesses |
| 729 |
--------------------- |
| 730 |
|
| 731 |
Trio provides support for spawning other programs as subprocesses, |
| 732 |
communicating with them via pipes, sending them signals, and waiting |
| 733 |
for them to exit. |
| 734 |
|
| 735 |
Most of the time, this is done through our high-level interface, |
| 736 |
`trio.run_process`. It lets you either run a process to completion |
| 737 |
while optionally capturing the output, or else run it in a background |
| 738 |
task and interact with it while it's running: |
| 739 |
|
| 740 |
.. autofunction:: trio.run_process |
| 741 |
|
| 742 |
.. autoclass:: trio._subprocess.HasFileno(Protocol) |
| 743 |
|
| 744 |
.. automethod:: fileno |
| 745 |
|
| 746 |
.. autoclass:: trio._subprocess.StrOrBytesPath |
| 747 |
|
| 748 |
.. autoclass:: trio.Process() |
| 749 |
|
| 750 |
.. autoattribute:: returncode |
| 751 |
|
| 752 |
.. automethod:: wait |
| 753 |
|
| 754 |
.. automethod:: poll |
| 755 |
|
| 756 |
.. automethod:: kill |
| 757 |
|
| 758 |
.. automethod:: terminate |
| 759 |
|
| 760 |
.. automethod:: send_signal |
| 761 |
|
| 762 |
.. note:: :meth:`~subprocess.Popen.communicate` is not provided as a |
| 763 |
method on :class:`~trio.Process` objects; call :func:`~trio.run_process` |
| 764 |
normally for simple capturing, or write the loop yourself if you |
| 765 |
have unusual needs. :meth:`~subprocess.Popen.communicate` has |
| 766 |
quite unusual cancellation behavior in the standard library (on |
| 767 |
some platforms it spawns a background thread which continues to |
| 768 |
read from the child process even after the timeout has expired) |
| 769 |
and we wanted to provide an interface with fewer surprises. |
| 770 |
|
| 771 |
If `trio.run_process` is too limiting, we also offer a low-level API, |
| 772 |
`trio.lowlevel.open_process`. For example, if you want to spawn a |
| 773 |
child process that will outlive the parent process and be |
| 774 |
orphaned, then `~trio.run_process` can't do that, but |
| 775 |
`~trio.lowlevel.open_process` can. |
| 776 |
|
| 777 |
|
| 778 |
.. _subprocess-options: |
| 779 |
|
| 780 |
Options for starting subprocesses |
| 781 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 782 |
|
| 783 |
All of Trio's subprocess APIs accept the numerous keyword arguments used |
| 784 |
by the standard :mod:`subprocess` module to control the environment in |
| 785 |
which a process starts and the mechanisms used for communicating with |
| 786 |
it. These may be passed wherever you see ``**options`` in the |
| 787 |
documentation below. See the `full list |
| 788 |
<https://docs.python.org/3/library/subprocess.html#popen-constructor>`__ |
| 789 |
or just the `frequently used ones |
| 790 |
<https://docs.python.org/3/library/subprocess.html#frequently-used-arguments>`__ |
| 791 |
in the :mod:`subprocess` documentation. (You may need to ``import |
| 792 |
subprocess`` in order to access constants such as ``PIPE`` or |
| 793 |
``DEVNULL``.) |
| 794 |
|
| 795 |
Currently, Trio always uses unbuffered byte streams for communicating |
| 796 |
with a process, so it does not support the ``encoding``, ``errors``, |
| 797 |
``universal_newlines`` (alias ``text``), and ``bufsize`` |
| 798 |
options. |
| 799 |
|
| 800 |
|
| 801 |
.. _subprocess-quoting: |
| 802 |
|
| 803 |
Quoting: more than you wanted to know |
| 804 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 805 |
|
| 806 |
The command to run and its arguments usually must be passed to Trio's |
| 807 |
subprocess APIs as a sequence of strings, where the first element in |
| 808 |
the sequence specifies the command to run and the remaining elements |
| 809 |
specify its arguments, one argument per element. This form is used |
| 810 |
because it avoids potential quoting pitfalls; for example, you can run |
| 811 |
``["cp", "-f", source_file, dest_file]`` without worrying about |
| 812 |
whether ``source_file`` or ``dest_file`` contains spaces. |
| 813 |
|
| 814 |
If you only run subprocesses without ``shell=True`` and on UNIX, |
| 815 |
that's all you need to know about specifying the command. If you use |
| 816 |
``shell=True`` or run on Windows, you probably should read the |
| 817 |
rest of this section to be aware of potential pitfalls. |
| 818 |
|
| 819 |
With ``shell=True`` on UNIX, you must specify the command as a single |
| 820 |
string, which will be passed to the shell as if you'd entered it at an |
| 821 |
interactive prompt. The advantage of this option is that it lets you |
| 822 |
use shell features like pipes and redirection without writing code to |
| 823 |
handle them. For example, you can write ``Process("ls | grep |
| 824 |
some_string", shell=True)``. The disadvantage is that you must |
| 825 |
account for the shell's quoting rules, generally by wrapping in |
| 826 |
:func:`shlex.quote` any argument that might contain spaces, quotes, or |
| 827 |
other shell metacharacters. If you don't do that, your safe-looking |
| 828 |
``f"ls | grep {some_string}"`` might end in disaster when invoked with |
| 829 |
``some_string = "foo; rm -rf /"``. |
| 830 |
|
| 831 |
On Windows, the fundamental API for process spawning (the |
| 832 |
``CreateProcess()`` system call) takes a string, not a list, and it's |
| 833 |
actually up to the child process to decide how it wants to split that |
| 834 |
string into individual arguments. Since the C language specifies that |
| 835 |
``main()`` should take a list of arguments, *most* programs you |
| 836 |
encounter will follow the rules used by the Microsoft C/C++ runtime. |
| 837 |
:class:`subprocess.Popen`, and thus also Trio, uses these rules |
| 838 |
when it converts an argument sequence to a string, and they |
| 839 |
are `documented |
| 840 |
<https://docs.python.org/3/library/subprocess.html#converting-argument-sequence>`__ |
| 841 |
alongside the :mod:`subprocess` module. There is no documented |
| 842 |
Python standard library function that can directly perform that |
| 843 |
conversion, so even on Windows, you almost always want to pass an |
| 844 |
argument sequence rather than a string. But if the program you're |
| 845 |
spawning doesn't split its command line back into individual arguments |
| 846 |
in the standard way, you might need to pass a string to work around this. |
| 847 |
(Or you might just be out of luck: as far as I can tell, there's simply |
| 848 |
no way to pass an argument containing a double-quote to a Windows |
| 849 |
batch file.) |
| 850 |
|
| 851 |
On Windows with ``shell=True``, things get even more chaotic. Now |
| 852 |
there are two separate sets of quoting rules applied, one by the |
| 853 |
Windows command shell ``CMD.EXE`` and one by the process being |
| 854 |
spawned, and they're *different*. (And there's no :func:`shlex.quote` |
| 855 |
to save you: it uses UNIX-style quoting rules, even on Windows.) Most |
| 856 |
special characters interpreted by the shell ``&<>()^|`` are not |
| 857 |
treated as special if the shell thinks they're inside double quotes, |
| 858 |
but ``%FOO%`` environment variable substitutions still are, and the |
| 859 |
shell doesn't provide any way to write a double quote inside a |
| 860 |
double-quoted string. Outside double quotes, any character (including |
| 861 |
a double quote) can be escaped using a leading ``^``. But since a |
| 862 |
pipeline is processed by running each command in the pipeline in a |
| 863 |
subshell, multiple layers of escaping can be needed: |
| 864 |
|
| 865 |
.. code-block:: sh |
| 866 |
|
| 867 |
echo ^^^&x | find "x" | find "x" # prints: &x |
| 868 |
|
| 869 |
And if you combine pipelines with () grouping, you can need even more |
| 870 |
levels of escaping: |
| 871 |
|
| 872 |
.. code-block:: sh |
| 873 |
|
| 874 |
(echo ^^^^^^^&x | find "x") | find "x" # prints: &x |
| 875 |
|
| 876 |
Since process creation takes a single arguments string, ``CMD.EXE``\'s |
| 877 |
quoting does not influence word splitting, and double quotes are not |
| 878 |
removed during CMD.EXE's expansion pass. Double quotes are troublesome |
| 879 |
because CMD.EXE handles them differently from the MSVC runtime rules; in: |
| 880 |
|
| 881 |
.. code-block:: sh |
| 882 |
|
| 883 |
prog.exe "foo \"bar\" baz" |
| 884 |
|
| 885 |
the program will see one argument ``foo "bar" baz`` but CMD.EXE thinks |
| 886 |
``bar\`` is not quoted while ``foo \`` and ``baz`` are. All of this |
| 887 |
makes it a formidable task to reliably interpolate anything into a |
| 888 |
``shell=True`` command line on Windows, and Trio falls back on the |
| 889 |
:mod:`subprocess` behavior: If you pass a sequence with |
| 890 |
``shell=True``, it's quoted in the same way as a sequence with |
| 891 |
``shell=False``, and had better not contain any shell metacharacters |
| 892 |
you weren't planning on. |
| 893 |
|
| 894 |
Further reading: |
| 895 |
|
| 896 |
* https://stackoverflow.com/questions/30620876/how-to-properly-escape-filenames-in-windows-cmd-exe |
| 897 |
|
| 898 |
* https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts |
| 899 |
|
| 900 |
|
| 901 |
Signals |
| 902 |
------- |
| 903 |
|
| 904 |
.. currentmodule:: trio |
| 905 |
|
| 906 |
.. autofunction:: open_signal_receiver |
| 907 |
:with: signal_aiter |