Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1 | """Base implementation of event loop. |
| 2 | |
| 3 | The event loop can be broken up into a multiplexer (the part |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 4 | responsible for notifying us of I/O events) and the event loop proper, |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 5 | which wraps a multiplexer with functionality for scheduling callbacks, |
| 6 | immediately or at a given time in the future. |
| 7 | |
| 8 | Whenever a public API takes a callback, subsequent positional |
| 9 | arguments will be passed to the callback if/when it is called. This |
| 10 | avoids the proliferation of trivial lambdas implementing closures. |
| 11 | Keyword arguments for the callback are not supported; this is a |
| 12 | conscious design decision, leaving the door open for keyword arguments |
| 13 | to modify the meaning of the API call itself. |
| 14 | """ |
| 15 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 16 | import collections |
Serhiy Storchaka | 2e576f5 | 2017-04-24 09:05:00 +0300 | [diff] [blame] | 17 | import collections.abc |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 18 | import concurrent.futures |
| 19 | import heapq |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 20 | import itertools |
Victor Stinner | b75380f | 2014-06-30 14:39:11 +0200 | [diff] [blame] | 21 | import os |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 22 | import socket |
| 23 | import subprocess |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 24 | import threading |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 25 | import time |
Victor Stinner | b75380f | 2014-06-30 14:39:11 +0200 | [diff] [blame] | 26 | import traceback |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 27 | import sys |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 28 | import warnings |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 29 | import weakref |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 30 | |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 31 | try: |
| 32 | import ssl |
| 33 | except ImportError: # pragma: no cover |
| 34 | ssl = None |
| 35 | |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 36 | from . import constants |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 37 | from . import coroutines |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 38 | from . import events |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 39 | from . import exceptions |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 40 | from . import futures |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 41 | from . import protocols |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 42 | from . import sslproto |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 43 | from . import tasks |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 44 | from . import transports |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 45 | from .log import logger |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 46 | |
| 47 | |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 48 | __all__ = 'BaseEventLoop', |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 49 | |
| 50 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 51 | # Minimum number of _scheduled timer handles before cleanup of |
| 52 | # cancelled handles is performed. |
| 53 | _MIN_SCHEDULED_TIMER_HANDLES = 100 |
| 54 | |
| 55 | # Minimum fraction of _scheduled timer handles that are cancelled |
| 56 | # before cleanup of cancelled handles is performed. |
| 57 | _MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5 |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 58 | |
Victor Stinner | c94a93a | 2016-04-01 21:43:39 +0200 | [diff] [blame] | 59 | # Exceptions which must not call the exception handler in fatal error |
| 60 | # methods (_fatal_error()) |
| 61 | _FATAL_ERROR_IGNORE = (BrokenPipeError, |
| 62 | ConnectionResetError, ConnectionAbortedError) |
| 63 | |
Andrew Svetlov | 0dd7180 | 2018-09-12 14:03:54 -0700 | [diff] [blame] | 64 | if ssl is not None: |
| 65 | _FATAL_ERROR_IGNORE = _FATAL_ERROR_IGNORE + (ssl.SSLCertVerificationError,) |
| 66 | |
Yury Selivanov | d904c23 | 2018-06-28 21:59:32 -0400 | [diff] [blame] | 67 | _HAS_IPv6 = hasattr(socket, 'AF_INET6') |
| 68 | |
MartinAltmayer | 944451c | 2018-07-31 15:06:12 +0100 | [diff] [blame] | 69 | # Maximum timeout passed to select to avoid OS limitations |
| 70 | MAXIMUM_SELECT_TIMEOUT = 24 * 3600 |
| 71 | |
Victor Stinner | c94a93a | 2016-04-01 21:43:39 +0200 | [diff] [blame] | 72 | |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 73 | def _format_handle(handle): |
| 74 | cb = handle._callback |
Yury Selivanov | a0c1ba6 | 2016-10-28 12:52:37 -0400 | [diff] [blame] | 75 | if isinstance(getattr(cb, '__self__', None), tasks.Task): |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 76 | # format the task |
| 77 | return repr(cb.__self__) |
| 78 | else: |
| 79 | return str(handle) |
| 80 | |
| 81 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 82 | def _format_pipe(fd): |
| 83 | if fd == subprocess.PIPE: |
| 84 | return '<pipe>' |
| 85 | elif fd == subprocess.STDOUT: |
| 86 | return '<stdout>' |
| 87 | else: |
| 88 | return repr(fd) |
| 89 | |
| 90 | |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 91 | def _set_reuseport(sock): |
| 92 | if not hasattr(socket, 'SO_REUSEPORT'): |
| 93 | raise ValueError('reuse_port not supported by socket module') |
| 94 | else: |
| 95 | try: |
| 96 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) |
| 97 | except OSError: |
| 98 | raise ValueError('reuse_port not supported by socket module, ' |
| 99 | 'SO_REUSEPORT defined but not implemented.') |
| 100 | |
| 101 | |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 102 | def _ipaddr_info(host, port, family, type, proto): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 103 | # Try to skip getaddrinfo if "host" is already an IP. Users might have |
| 104 | # handled name resolution in their own code and pass in resolved IPs. |
| 105 | if not hasattr(socket, 'inet_pton'): |
| 106 | return |
| 107 | |
| 108 | if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \ |
| 109 | host is None: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 110 | return None |
| 111 | |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 112 | if type == socket.SOCK_STREAM: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 113 | proto = socket.IPPROTO_TCP |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 114 | elif type == socket.SOCK_DGRAM: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 115 | proto = socket.IPPROTO_UDP |
| 116 | else: |
| 117 | return None |
| 118 | |
Yury Selivanov | a714616 | 2016-06-02 16:51:07 -0400 | [diff] [blame] | 119 | if port is None: |
Yury Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 120 | port = 0 |
Guido van Rossum | e3c65a7 | 2016-09-30 08:17:15 -0700 | [diff] [blame] | 121 | elif isinstance(port, bytes) and port == b'': |
| 122 | port = 0 |
| 123 | elif isinstance(port, str) and port == '': |
| 124 | port = 0 |
| 125 | else: |
| 126 | # If port's a service name like "http", don't skip getaddrinfo. |
| 127 | try: |
| 128 | port = int(port) |
| 129 | except (TypeError, ValueError): |
| 130 | return None |
Yury Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 131 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 132 | if family == socket.AF_UNSPEC: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 133 | afs = [socket.AF_INET] |
Yury Selivanov | d904c23 | 2018-06-28 21:59:32 -0400 | [diff] [blame] | 134 | if _HAS_IPv6: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 135 | afs.append(socket.AF_INET6) |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 136 | else: |
| 137 | afs = [family] |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 138 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 139 | if isinstance(host, bytes): |
| 140 | host = host.decode('idna') |
| 141 | if '%' in host: |
| 142 | # Linux's inet_pton doesn't accept an IPv6 zone index after host, |
| 143 | # like '::1%lo0'. |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 144 | return None |
| 145 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 146 | for af in afs: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 147 | try: |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 148 | socket.inet_pton(af, host) |
| 149 | # The host has already been resolved. |
Yury Selivanov | d904c23 | 2018-06-28 21:59:32 -0400 | [diff] [blame] | 150 | if _HAS_IPv6 and af == socket.AF_INET6: |
| 151 | return af, type, proto, '', (host, port, 0, 0) |
| 152 | else: |
| 153 | return af, type, proto, '', (host, port) |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 154 | except OSError: |
| 155 | pass |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 156 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 157 | # "host" is not an IP address. |
| 158 | return None |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 159 | |
| 160 | |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 161 | def _run_until_complete_cb(fut): |
Yury Selivanov | 36c2c04 | 2017-12-19 07:19:53 -0500 | [diff] [blame] | 162 | if not fut.cancelled(): |
| 163 | exc = fut.exception() |
| 164 | if isinstance(exc, BaseException) and not isinstance(exc, Exception): |
| 165 | # Issue #22429: run_forever() already finished, no need to |
| 166 | # stop it. |
| 167 | return |
Yury Selivanov | ca9b36c | 2017-12-23 15:04:15 -0500 | [diff] [blame] | 168 | futures._get_loop(fut).stop() |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 169 | |
| 170 | |
Andrew Svetlov | 3bc0eba | 2018-12-03 21:08:13 +0200 | [diff] [blame] | 171 | if hasattr(socket, 'TCP_NODELAY'): |
| 172 | def _set_nodelay(sock): |
| 173 | if (sock.family in {socket.AF_INET, socket.AF_INET6} and |
| 174 | sock.type == socket.SOCK_STREAM and |
| 175 | sock.proto == socket.IPPROTO_TCP): |
| 176 | sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 177 | else: |
| 178 | def _set_nodelay(sock): |
| 179 | pass |
| 180 | |
| 181 | |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 182 | class _SendfileFallbackProtocol(protocols.Protocol): |
| 183 | def __init__(self, transp): |
| 184 | if not isinstance(transp, transports._FlowControlMixin): |
| 185 | raise TypeError("transport should be _FlowControlMixin instance") |
| 186 | self._transport = transp |
| 187 | self._proto = transp.get_protocol() |
| 188 | self._should_resume_reading = transp.is_reading() |
| 189 | self._should_resume_writing = transp._protocol_paused |
| 190 | transp.pause_reading() |
| 191 | transp.set_protocol(self) |
| 192 | if self._should_resume_writing: |
| 193 | self._write_ready_fut = self._transport._loop.create_future() |
| 194 | else: |
| 195 | self._write_ready_fut = None |
| 196 | |
| 197 | async def drain(self): |
| 198 | if self._transport.is_closing(): |
| 199 | raise ConnectionError("Connection closed by peer") |
| 200 | fut = self._write_ready_fut |
| 201 | if fut is None: |
| 202 | return |
| 203 | await fut |
| 204 | |
| 205 | def connection_made(self, transport): |
| 206 | raise RuntimeError("Invalid state: " |
| 207 | "connection should have been established already.") |
| 208 | |
| 209 | def connection_lost(self, exc): |
| 210 | if self._write_ready_fut is not None: |
| 211 | # Never happens if peer disconnects after sending the whole content |
| 212 | # Thus disconnection is always an exception from user perspective |
| 213 | if exc is None: |
| 214 | self._write_ready_fut.set_exception( |
| 215 | ConnectionError("Connection is closed by peer")) |
| 216 | else: |
| 217 | self._write_ready_fut.set_exception(exc) |
| 218 | self._proto.connection_lost(exc) |
| 219 | |
| 220 | def pause_writing(self): |
| 221 | if self._write_ready_fut is not None: |
| 222 | return |
| 223 | self._write_ready_fut = self._transport._loop.create_future() |
| 224 | |
| 225 | def resume_writing(self): |
| 226 | if self._write_ready_fut is None: |
| 227 | return |
| 228 | self._write_ready_fut.set_result(False) |
| 229 | self._write_ready_fut = None |
| 230 | |
| 231 | def data_received(self, data): |
| 232 | raise RuntimeError("Invalid state: reading should be paused") |
| 233 | |
| 234 | def eof_received(self): |
| 235 | raise RuntimeError("Invalid state: reading should be paused") |
| 236 | |
| 237 | async def restore(self): |
| 238 | self._transport.set_protocol(self._proto) |
| 239 | if self._should_resume_reading: |
| 240 | self._transport.resume_reading() |
| 241 | if self._write_ready_fut is not None: |
| 242 | # Cancel the future. |
| 243 | # Basically it has no effect because protocol is switched back, |
| 244 | # no code should wait for it anymore. |
| 245 | self._write_ready_fut.cancel() |
| 246 | if self._should_resume_writing: |
| 247 | self._proto.resume_writing() |
| 248 | |
| 249 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 250 | class Server(events.AbstractServer): |
| 251 | |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 252 | def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog, |
| 253 | ssl_handshake_timeout): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 254 | self._loop = loop |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 255 | self._sockets = sockets |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 256 | self._active_count = 0 |
| 257 | self._waiters = [] |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 258 | self._protocol_factory = protocol_factory |
| 259 | self._backlog = backlog |
| 260 | self._ssl_context = ssl_context |
| 261 | self._ssl_handshake_timeout = ssl_handshake_timeout |
| 262 | self._serving = False |
| 263 | self._serving_forever_fut = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 264 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 265 | def __repr__(self): |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 266 | return f'<{self.__class__.__name__} sockets={self.sockets!r}>' |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 267 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 268 | def _attach(self): |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 269 | assert self._sockets is not None |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 270 | self._active_count += 1 |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 271 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 272 | def _detach(self): |
| 273 | assert self._active_count > 0 |
| 274 | self._active_count -= 1 |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 275 | if self._active_count == 0 and self._sockets is None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 276 | self._wakeup() |
| 277 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 278 | def _wakeup(self): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 279 | waiters = self._waiters |
| 280 | self._waiters = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 281 | for waiter in waiters: |
| 282 | if not waiter.done(): |
| 283 | waiter.set_result(waiter) |
| 284 | |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 285 | def _start_serving(self): |
| 286 | if self._serving: |
| 287 | return |
| 288 | self._serving = True |
| 289 | for sock in self._sockets: |
| 290 | sock.listen(self._backlog) |
| 291 | self._loop._start_serving( |
| 292 | self._protocol_factory, sock, self._ssl_context, |
| 293 | self, self._backlog, self._ssl_handshake_timeout) |
| 294 | |
| 295 | def get_loop(self): |
| 296 | return self._loop |
| 297 | |
| 298 | def is_serving(self): |
| 299 | return self._serving |
| 300 | |
| 301 | @property |
| 302 | def sockets(self): |
| 303 | if self._sockets is None: |
| 304 | return [] |
| 305 | return list(self._sockets) |
| 306 | |
| 307 | def close(self): |
| 308 | sockets = self._sockets |
| 309 | if sockets is None: |
| 310 | return |
| 311 | self._sockets = None |
| 312 | |
| 313 | for sock in sockets: |
| 314 | self._loop._stop_serving(sock) |
| 315 | |
| 316 | self._serving = False |
| 317 | |
| 318 | if (self._serving_forever_fut is not None and |
| 319 | not self._serving_forever_fut.done()): |
| 320 | self._serving_forever_fut.cancel() |
| 321 | self._serving_forever_fut = None |
| 322 | |
| 323 | if self._active_count == 0: |
| 324 | self._wakeup() |
| 325 | |
| 326 | async def start_serving(self): |
| 327 | self._start_serving() |
Yury Selivanov | dbf1022 | 2018-05-28 14:31:28 -0400 | [diff] [blame] | 328 | # Skip one loop iteration so that all 'loop.add_reader' |
| 329 | # go through. |
| 330 | await tasks.sleep(0, loop=self._loop) |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 331 | |
| 332 | async def serve_forever(self): |
| 333 | if self._serving_forever_fut is not None: |
| 334 | raise RuntimeError( |
| 335 | f'server {self!r} is already being awaited on serve_forever()') |
| 336 | if self._sockets is None: |
| 337 | raise RuntimeError(f'server {self!r} is closed') |
| 338 | |
| 339 | self._start_serving() |
| 340 | self._serving_forever_fut = self._loop.create_future() |
| 341 | |
| 342 | try: |
| 343 | await self._serving_forever_fut |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 344 | except exceptions.CancelledError: |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 345 | try: |
| 346 | self.close() |
| 347 | await self.wait_closed() |
| 348 | finally: |
| 349 | raise |
| 350 | finally: |
| 351 | self._serving_forever_fut = None |
| 352 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 353 | async def wait_closed(self): |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 354 | if self._sockets is None or self._waiters is None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 355 | return |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 356 | waiter = self._loop.create_future() |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 357 | self._waiters.append(waiter) |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 358 | await waiter |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 359 | |
| 360 | |
| 361 | class BaseEventLoop(events.AbstractEventLoop): |
| 362 | |
| 363 | def __init__(self): |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 364 | self._timer_cancelled_count = 0 |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 365 | self._closed = False |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 366 | self._stopping = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 367 | self._ready = collections.deque() |
| 368 | self._scheduled = [] |
| 369 | self._default_executor = None |
| 370 | self._internal_fds = 0 |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 371 | # Identifier of the thread running the event loop, or None if the |
| 372 | # event loop is not running |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 373 | self._thread_id = None |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 374 | self._clock_resolution = time.get_clock_info('monotonic').resolution |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 375 | self._exception_handler = None |
Victor Stinner | 44862df | 2017-11-20 07:14:07 -0800 | [diff] [blame] | 376 | self.set_debug(coroutines._is_debug_mode()) |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 377 | # In debug mode, if the execution of a callback or a step of a task |
| 378 | # exceed this duration in seconds, the slow callback/task is logged. |
| 379 | self.slow_callback_duration = 0.1 |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 380 | self._current_handle = None |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 381 | self._task_factory = None |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 382 | self._coroutine_origin_tracking_enabled = False |
| 383 | self._coroutine_origin_tracking_saved_depth = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 384 | |
Yury Selivanov | a4afcdf | 2018-01-21 14:56:59 -0500 | [diff] [blame] | 385 | # A weak set of all asynchronous generators that are |
| 386 | # being iterated by the loop. |
| 387 | self._asyncgens = weakref.WeakSet() |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 388 | # Set to True when `loop.shutdown_asyncgens` is called. |
| 389 | self._asyncgens_shutdown_called = False |
| 390 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 391 | def __repr__(self): |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 392 | return ( |
| 393 | f'<{self.__class__.__name__} running={self.is_running()} ' |
| 394 | f'closed={self.is_closed()} debug={self.get_debug()}>' |
| 395 | ) |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 396 | |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 397 | def create_future(self): |
| 398 | """Create a Future object attached to the loop.""" |
| 399 | return futures.Future(loop=self) |
| 400 | |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 401 | def create_task(self, coro, *, name=None): |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 402 | """Schedule a coroutine object. |
| 403 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 404 | Return a task object. |
| 405 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 406 | self._check_closed() |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 407 | if self._task_factory is None: |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 408 | task = tasks.Task(coro, loop=self, name=name) |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 409 | if task._source_traceback: |
| 410 | del task._source_traceback[-1] |
| 411 | else: |
| 412 | task = self._task_factory(self, coro) |
Alex Grönholm | cca4eec | 2018-08-09 00:06:47 +0300 | [diff] [blame] | 413 | tasks._set_task_name(task, name) |
| 414 | |
Victor Stinner | c39ba7d | 2014-07-11 00:21:27 +0200 | [diff] [blame] | 415 | return task |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 416 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 417 | def set_task_factory(self, factory): |
| 418 | """Set a task factory that will be used by loop.create_task(). |
| 419 | |
| 420 | If factory is None the default task factory will be set. |
| 421 | |
| 422 | If factory is a callable, it should have a signature matching |
| 423 | '(loop, coro)', where 'loop' will be a reference to the active |
| 424 | event loop, 'coro' will be a coroutine object. The callable |
| 425 | must return a Future. |
| 426 | """ |
| 427 | if factory is not None and not callable(factory): |
| 428 | raise TypeError('task factory must be a callable or None') |
| 429 | self._task_factory = factory |
| 430 | |
| 431 | def get_task_factory(self): |
| 432 | """Return a task factory, or None if the default one is in use.""" |
| 433 | return self._task_factory |
| 434 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 435 | def _make_socket_transport(self, sock, protocol, waiter=None, *, |
| 436 | extra=None, server=None): |
| 437 | """Create socket transport.""" |
| 438 | raise NotImplementedError |
| 439 | |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 440 | def _make_ssl_transport( |
| 441 | self, rawsock, protocol, sslcontext, waiter=None, |
| 442 | *, server_side=False, server_hostname=None, |
| 443 | extra=None, server=None, |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 444 | ssl_handshake_timeout=None, |
| 445 | call_connection_made=True): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 446 | """Create SSL transport.""" |
| 447 | raise NotImplementedError |
| 448 | |
| 449 | def _make_datagram_transport(self, sock, protocol, |
Victor Stinner | bfff45d | 2014-07-08 23:57:31 +0200 | [diff] [blame] | 450 | address=None, waiter=None, extra=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 451 | """Create datagram transport.""" |
| 452 | raise NotImplementedError |
| 453 | |
| 454 | def _make_read_pipe_transport(self, pipe, protocol, waiter=None, |
| 455 | extra=None): |
| 456 | """Create read pipe transport.""" |
| 457 | raise NotImplementedError |
| 458 | |
| 459 | def _make_write_pipe_transport(self, pipe, protocol, waiter=None, |
| 460 | extra=None): |
| 461 | """Create write pipe transport.""" |
| 462 | raise NotImplementedError |
| 463 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 464 | async def _make_subprocess_transport(self, protocol, args, shell, |
| 465 | stdin, stdout, stderr, bufsize, |
| 466 | extra=None, **kwargs): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 467 | """Create subprocess transport.""" |
| 468 | raise NotImplementedError |
| 469 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 470 | def _write_to_self(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 471 | """Write a byte to self-pipe, to wake up the event loop. |
| 472 | |
| 473 | This may be called from a different thread. |
| 474 | |
| 475 | The subclass is responsible for implementing the self-pipe. |
| 476 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 477 | raise NotImplementedError |
| 478 | |
| 479 | def _process_events(self, event_list): |
| 480 | """Process selector events.""" |
| 481 | raise NotImplementedError |
| 482 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 483 | def _check_closed(self): |
| 484 | if self._closed: |
| 485 | raise RuntimeError('Event loop is closed') |
| 486 | |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 487 | def _asyncgen_finalizer_hook(self, agen): |
| 488 | self._asyncgens.discard(agen) |
| 489 | if not self.is_closed(): |
twisteroid ambassador | c880ffe | 2018-10-09 23:30:21 +0800 | [diff] [blame] | 490 | self.call_soon_threadsafe(self.create_task, agen.aclose()) |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 491 | |
| 492 | def _asyncgen_firstiter_hook(self, agen): |
| 493 | if self._asyncgens_shutdown_called: |
| 494 | warnings.warn( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 495 | f"asynchronous generator {agen!r} was scheduled after " |
| 496 | f"loop.shutdown_asyncgens() call", |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 497 | ResourceWarning, source=self) |
| 498 | |
| 499 | self._asyncgens.add(agen) |
| 500 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 501 | async def shutdown_asyncgens(self): |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 502 | """Shutdown all active asynchronous generators.""" |
| 503 | self._asyncgens_shutdown_called = True |
| 504 | |
Yury Selivanov | a4afcdf | 2018-01-21 14:56:59 -0500 | [diff] [blame] | 505 | if not len(self._asyncgens): |
Yury Selivanov | 0a91d48 | 2016-09-15 13:24:03 -0400 | [diff] [blame] | 506 | # If Python version is <3.6 or we don't have any asynchronous |
| 507 | # generators alive. |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 508 | return |
| 509 | |
| 510 | closing_agens = list(self._asyncgens) |
| 511 | self._asyncgens.clear() |
| 512 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 513 | results = await tasks.gather( |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 514 | *[ag.aclose() for ag in closing_agens], |
| 515 | return_exceptions=True, |
| 516 | loop=self) |
| 517 | |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 518 | for result, agen in zip(results, closing_agens): |
| 519 | if isinstance(result, Exception): |
| 520 | self.call_exception_handler({ |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 521 | 'message': f'an error occurred during closing of ' |
| 522 | f'asynchronous generator {agen!r}', |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 523 | 'exception': result, |
| 524 | 'asyncgen': agen |
| 525 | }) |
| 526 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 527 | def run_forever(self): |
| 528 | """Run until stop() is called.""" |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 529 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 530 | if self.is_running(): |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 531 | raise RuntimeError('This event loop is already running') |
| 532 | if events._get_running_loop() is not None: |
| 533 | raise RuntimeError( |
| 534 | 'Cannot run the event loop while another loop is running') |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 535 | self._set_coroutine_origin_tracking(self._debug) |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 536 | self._thread_id = threading.get_ident() |
Yury Selivanov | a4afcdf | 2018-01-21 14:56:59 -0500 | [diff] [blame] | 537 | |
| 538 | old_agen_hooks = sys.get_asyncgen_hooks() |
| 539 | sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, |
| 540 | finalizer=self._asyncgen_finalizer_hook) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 541 | try: |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 542 | events._set_running_loop(self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 543 | while True: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 544 | self._run_once() |
| 545 | if self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 546 | break |
| 547 | finally: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 548 | self._stopping = False |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 549 | self._thread_id = None |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 550 | events._set_running_loop(None) |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 551 | self._set_coroutine_origin_tracking(False) |
Yury Selivanov | a4afcdf | 2018-01-21 14:56:59 -0500 | [diff] [blame] | 552 | sys.set_asyncgen_hooks(*old_agen_hooks) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 553 | |
| 554 | def run_until_complete(self, future): |
| 555 | """Run until the Future is done. |
| 556 | |
| 557 | If the argument is a coroutine, it is wrapped in a Task. |
| 558 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 559 | WARNING: It would be disastrous to call run_until_complete() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 560 | with the same coroutine twice -- it would wrap it in two |
| 561 | different Tasks and that can't be good. |
| 562 | |
| 563 | Return the Future's result, or raise its exception. |
| 564 | """ |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 565 | self._check_closed() |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 566 | |
Guido van Rossum | 7b3b3dc | 2016-09-09 14:26:31 -0700 | [diff] [blame] | 567 | new_task = not futures.isfuture(future) |
Yury Selivanov | 59eb9a4 | 2015-05-11 14:48:38 -0400 | [diff] [blame] | 568 | future = tasks.ensure_future(future, loop=self) |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 569 | if new_task: |
| 570 | # An exception is raised if the future didn't complete, so there |
| 571 | # is no need to log the "destroy pending task" message |
| 572 | future._log_destroy_pending = False |
| 573 | |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 574 | future.add_done_callback(_run_until_complete_cb) |
Victor Stinner | c8bd53f | 2014-10-11 14:30:18 +0200 | [diff] [blame] | 575 | try: |
| 576 | self.run_forever() |
| 577 | except: |
| 578 | if new_task and future.done() and not future.cancelled(): |
| 579 | # The coroutine raised a BaseException. Consume the exception |
| 580 | # to not log a warning, the caller doesn't have access to the |
| 581 | # local task. |
| 582 | future.exception() |
| 583 | raise |
jimmylai | 21b3e04 | 2017-05-22 22:32:46 -0700 | [diff] [blame] | 584 | finally: |
| 585 | future.remove_done_callback(_run_until_complete_cb) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 586 | if not future.done(): |
| 587 | raise RuntimeError('Event loop stopped before Future completed.') |
| 588 | |
| 589 | return future.result() |
| 590 | |
| 591 | def stop(self): |
| 592 | """Stop running the event loop. |
| 593 | |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 594 | Every callback already scheduled will still run. This simply informs |
| 595 | run_forever to stop looping after a complete iteration. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 596 | """ |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 597 | self._stopping = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 598 | |
Antoine Pitrou | 4ca7355 | 2013-10-20 00:54:10 +0200 | [diff] [blame] | 599 | def close(self): |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 600 | """Close the event loop. |
| 601 | |
| 602 | This clears the queues and shuts down the executor, |
| 603 | but does not wait for the executor to finish. |
Victor Stinner | f328c7d | 2014-06-23 01:02:37 +0200 | [diff] [blame] | 604 | |
| 605 | The event loop must not be running. |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 606 | """ |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 607 | if self.is_running(): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 608 | raise RuntimeError("Cannot close a running event loop") |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 609 | if self._closed: |
| 610 | return |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 611 | if self._debug: |
| 612 | logger.debug("Close %r", self) |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 613 | self._closed = True |
| 614 | self._ready.clear() |
| 615 | self._scheduled.clear() |
| 616 | executor = self._default_executor |
| 617 | if executor is not None: |
| 618 | self._default_executor = None |
| 619 | executor.shutdown(wait=False) |
Antoine Pitrou | 4ca7355 | 2013-10-20 00:54:10 +0200 | [diff] [blame] | 620 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 621 | def is_closed(self): |
| 622 | """Returns True if the event loop was closed.""" |
| 623 | return self._closed |
| 624 | |
Victor Stinner | fb2c346 | 2019-01-10 11:24:40 +0100 | [diff] [blame] | 625 | def __del__(self, _warn=warnings.warn): |
INADA Naoki | 3e2ad8e | 2017-04-25 10:57:18 +0900 | [diff] [blame] | 626 | if not self.is_closed(): |
Victor Stinner | fb2c346 | 2019-01-10 11:24:40 +0100 | [diff] [blame] | 627 | _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self) |
INADA Naoki | 3e2ad8e | 2017-04-25 10:57:18 +0900 | [diff] [blame] | 628 | if not self.is_running(): |
| 629 | self.close() |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 630 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 631 | def is_running(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 632 | """Returns True if the event loop is running.""" |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 633 | return (self._thread_id is not None) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 634 | |
| 635 | def time(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 636 | """Return the time according to the event loop's clock. |
| 637 | |
| 638 | This is a float expressed in seconds since an epoch, but the |
| 639 | epoch, precision, accuracy and drift are unspecified and may |
| 640 | differ per event loop. |
| 641 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 642 | return time.monotonic() |
| 643 | |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 644 | def call_later(self, delay, callback, *args, context=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 645 | """Arrange for a callback to be called at a given time. |
| 646 | |
| 647 | Return a Handle: an opaque object with a cancel() method that |
| 648 | can be used to cancel the call. |
| 649 | |
| 650 | The delay can be an int or float, expressed in seconds. It is |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 651 | always relative to the current time. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 652 | |
| 653 | Each callback will be called exactly once. If two callbacks |
| 654 | are scheduled for exactly the same time, it undefined which |
| 655 | will be called first. |
| 656 | |
| 657 | Any positional arguments after the callback will be passed to |
| 658 | the callback when it is called. |
| 659 | """ |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 660 | timer = self.call_at(self.time() + delay, callback, *args, |
| 661 | context=context) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 662 | if timer._source_traceback: |
| 663 | del timer._source_traceback[-1] |
| 664 | return timer |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 665 | |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 666 | def call_at(self, when, callback, *args, context=None): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 667 | """Like call_later(), but uses an absolute time. |
| 668 | |
| 669 | Absolute time corresponds to the event loop's time() method. |
| 670 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 671 | self._check_closed() |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 672 | if self._debug: |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 673 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 674 | self._check_callback(callback, 'call_at') |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 675 | timer = events.TimerHandle(when, callback, args, self, context) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 676 | if timer._source_traceback: |
| 677 | del timer._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 678 | heapq.heappush(self._scheduled, timer) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 679 | timer._scheduled = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 680 | return timer |
| 681 | |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 682 | def call_soon(self, callback, *args, context=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 683 | """Arrange for a callback to be called as soon as possible. |
| 684 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 685 | This operates as a FIFO queue: callbacks are called in the |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 686 | order in which they are registered. Each callback will be |
| 687 | called exactly once. |
| 688 | |
| 689 | Any positional arguments after the callback will be passed to |
| 690 | the callback when it is called. |
| 691 | """ |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 692 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 693 | if self._debug: |
| 694 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 695 | self._check_callback(callback, 'call_soon') |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 696 | handle = self._call_soon(callback, args, context) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 697 | if handle._source_traceback: |
| 698 | del handle._source_traceback[-1] |
| 699 | return handle |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 700 | |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 701 | def _check_callback(self, callback, method): |
| 702 | if (coroutines.iscoroutine(callback) or |
| 703 | coroutines.iscoroutinefunction(callback)): |
| 704 | raise TypeError( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 705 | f"coroutines cannot be used with {method}()") |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 706 | if not callable(callback): |
| 707 | raise TypeError( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 708 | f'a callable object was expected by {method}(), ' |
| 709 | f'got {callback!r}') |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 710 | |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 711 | def _call_soon(self, callback, args, context): |
| 712 | handle = events.Handle(callback, args, self, context) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 713 | if handle._source_traceback: |
| 714 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 715 | self._ready.append(handle) |
| 716 | return handle |
| 717 | |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 718 | def _check_thread(self): |
| 719 | """Check that the current thread is the thread running the event loop. |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 720 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 721 | Non-thread-safe methods of this class make this assumption and will |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 722 | likely behave incorrectly when the assumption is violated. |
| 723 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 724 | Should only be called when (self._debug == True). The caller is |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 725 | responsible for checking this condition for performance reasons. |
| 726 | """ |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 727 | if self._thread_id is None: |
Victor Stinner | 751c7c0 | 2014-06-23 15:14:13 +0200 | [diff] [blame] | 728 | return |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 729 | thread_id = threading.get_ident() |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 730 | if thread_id != self._thread_id: |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 731 | raise RuntimeError( |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 732 | "Non-thread-safe operation invoked on an event loop other " |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 733 | "than the current one") |
| 734 | |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 735 | def call_soon_threadsafe(self, callback, *args, context=None): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 736 | """Like call_soon(), but thread-safe.""" |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 737 | self._check_closed() |
| 738 | if self._debug: |
| 739 | self._check_callback(callback, 'call_soon_threadsafe') |
Yury Selivanov | f23746a | 2018-01-22 19:11:18 -0500 | [diff] [blame] | 740 | handle = self._call_soon(callback, args, context) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 741 | if handle._source_traceback: |
| 742 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 743 | self._write_to_self() |
| 744 | return handle |
| 745 | |
Yury Selivanov | bec2372 | 2018-01-28 14:09:40 -0500 | [diff] [blame] | 746 | def run_in_executor(self, executor, func, *args): |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 747 | self._check_closed() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 748 | if self._debug: |
| 749 | self._check_callback(func, 'run_in_executor') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 750 | if executor is None: |
| 751 | executor = self._default_executor |
| 752 | if executor is None: |
Yury Selivanov | e8a6045 | 2016-10-21 17:40:42 -0400 | [diff] [blame] | 753 | executor = concurrent.futures.ThreadPoolExecutor() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 754 | self._default_executor = executor |
Yury Selivanov | bec2372 | 2018-01-28 14:09:40 -0500 | [diff] [blame] | 755 | return futures.wrap_future( |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 756 | executor.submit(func, *args), loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 757 | |
| 758 | def set_default_executor(self, executor): |
Elvis Pranskevichus | 22d2508 | 2018-07-30 11:42:43 +0100 | [diff] [blame] | 759 | if not isinstance(executor, concurrent.futures.ThreadPoolExecutor): |
| 760 | warnings.warn( |
| 761 | 'Using the default executor that is not an instance of ' |
| 762 | 'ThreadPoolExecutor is deprecated and will be prohibited ' |
| 763 | 'in Python 3.9', |
| 764 | DeprecationWarning, 2) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 765 | self._default_executor = executor |
| 766 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 767 | def _getaddrinfo_debug(self, host, port, family, type, proto, flags): |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 768 | msg = [f"{host}:{port!r}"] |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 769 | if family: |
Yury Selivanov | 19d0d54 | 2017-12-10 19:52:53 -0500 | [diff] [blame] | 770 | msg.append(f'family={family!r}') |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 771 | if type: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 772 | msg.append(f'type={type!r}') |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 773 | if proto: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 774 | msg.append(f'proto={proto!r}') |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 775 | if flags: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 776 | msg.append(f'flags={flags!r}') |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 777 | msg = ', '.join(msg) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 778 | logger.debug('Get address info %s', msg) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 779 | |
| 780 | t0 = self.time() |
| 781 | addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags) |
| 782 | dt = self.time() - t0 |
| 783 | |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 784 | msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}' |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 785 | if dt >= self.slow_callback_duration: |
| 786 | logger.info(msg) |
| 787 | else: |
| 788 | logger.debug(msg) |
| 789 | return addrinfo |
| 790 | |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 791 | async def getaddrinfo(self, host, port, *, |
| 792 | family=0, type=0, proto=0, flags=0): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 793 | if self._debug: |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 794 | getaddr_func = self._getaddrinfo_debug |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 795 | else: |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 796 | getaddr_func = socket.getaddrinfo |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 797 | |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 798 | return await self.run_in_executor( |
| 799 | None, getaddr_func, host, port, family, type, proto, flags) |
| 800 | |
| 801 | async def getnameinfo(self, sockaddr, flags=0): |
| 802 | return await self.run_in_executor( |
| 803 | None, socket.getnameinfo, sockaddr, flags) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 804 | |
Andrew Svetlov | 6b5a279 | 2018-01-16 19:59:34 +0200 | [diff] [blame] | 805 | async def sock_sendfile(self, sock, file, offset=0, count=None, |
| 806 | *, fallback=True): |
| 807 | if self._debug and sock.gettimeout() != 0: |
| 808 | raise ValueError("the socket must be non-blocking") |
| 809 | self._check_sendfile_params(sock, file, offset, count) |
| 810 | try: |
| 811 | return await self._sock_sendfile_native(sock, file, |
| 812 | offset, count) |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 813 | except exceptions.SendfileNotAvailableError as exc: |
Andrew Svetlov | 7464e87 | 2018-01-19 20:04:29 +0200 | [diff] [blame] | 814 | if not fallback: |
| 815 | raise |
| 816 | return await self._sock_sendfile_fallback(sock, file, |
| 817 | offset, count) |
Andrew Svetlov | 6b5a279 | 2018-01-16 19:59:34 +0200 | [diff] [blame] | 818 | |
| 819 | async def _sock_sendfile_native(self, sock, file, offset, count): |
| 820 | # NB: sendfile syscall is not supported for SSL sockets and |
| 821 | # non-mmap files even if sendfile is supported by OS |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 822 | raise exceptions.SendfileNotAvailableError( |
Andrew Svetlov | 6b5a279 | 2018-01-16 19:59:34 +0200 | [diff] [blame] | 823 | f"syscall sendfile is not available for socket {sock!r} " |
| 824 | "and file {file!r} combination") |
| 825 | |
| 826 | async def _sock_sendfile_fallback(self, sock, file, offset, count): |
| 827 | if offset: |
| 828 | file.seek(offset) |
Yury Selivanov | 7165754 | 2018-05-28 18:31:55 -0400 | [diff] [blame] | 829 | blocksize = ( |
| 830 | min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE) |
| 831 | if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE |
| 832 | ) |
Andrew Svetlov | 6b5a279 | 2018-01-16 19:59:34 +0200 | [diff] [blame] | 833 | buf = bytearray(blocksize) |
| 834 | total_sent = 0 |
| 835 | try: |
| 836 | while True: |
| 837 | if count: |
| 838 | blocksize = min(count - total_sent, blocksize) |
| 839 | if blocksize <= 0: |
| 840 | break |
| 841 | view = memoryview(buf)[:blocksize] |
Yury Selivanov | 7165754 | 2018-05-28 18:31:55 -0400 | [diff] [blame] | 842 | read = await self.run_in_executor(None, file.readinto, view) |
Andrew Svetlov | 6b5a279 | 2018-01-16 19:59:34 +0200 | [diff] [blame] | 843 | if not read: |
| 844 | break # EOF |
| 845 | await self.sock_sendall(sock, view) |
| 846 | total_sent += read |
| 847 | return total_sent |
| 848 | finally: |
| 849 | if total_sent > 0 and hasattr(file, 'seek'): |
| 850 | file.seek(offset + total_sent) |
| 851 | |
| 852 | def _check_sendfile_params(self, sock, file, offset, count): |
| 853 | if 'b' not in getattr(file, 'mode', 'b'): |
| 854 | raise ValueError("file should be opened in binary mode") |
| 855 | if not sock.type == socket.SOCK_STREAM: |
| 856 | raise ValueError("only SOCK_STREAM type sockets are supported") |
| 857 | if count is not None: |
| 858 | if not isinstance(count, int): |
| 859 | raise TypeError( |
| 860 | "count must be a positive integer (got {!r})".format(count)) |
| 861 | if count <= 0: |
| 862 | raise ValueError( |
| 863 | "count must be a positive integer (got {!r})".format(count)) |
| 864 | if not isinstance(offset, int): |
| 865 | raise TypeError( |
| 866 | "offset must be a non-negative integer (got {!r})".format( |
| 867 | offset)) |
| 868 | if offset < 0: |
| 869 | raise ValueError( |
| 870 | "offset must be a non-negative integer (got {!r})".format( |
| 871 | offset)) |
| 872 | |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 873 | async def create_connection( |
| 874 | self, protocol_factory, host=None, port=None, |
| 875 | *, ssl=None, family=0, |
| 876 | proto=0, flags=0, sock=None, |
| 877 | local_addr=None, server_hostname=None, |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 878 | ssl_handshake_timeout=None): |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 879 | """Connect to a TCP server. |
| 880 | |
| 881 | Create a streaming transport connection to a given Internet host and |
| 882 | port: socket family AF_INET or socket.AF_INET6 depending on host (or |
| 883 | family if specified), socket type SOCK_STREAM. protocol_factory must be |
| 884 | a callable returning a protocol instance. |
| 885 | |
| 886 | This method is a coroutine which will try to establish the connection |
| 887 | in the background. When successful, the coroutine returns a |
| 888 | (transport, protocol) pair. |
| 889 | """ |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 890 | if server_hostname is not None and not ssl: |
| 891 | raise ValueError('server_hostname is only meaningful with ssl') |
| 892 | |
| 893 | if server_hostname is None and ssl: |
| 894 | # Use host as default for server_hostname. It is an error |
| 895 | # if host is empty or not set, e.g. when an |
| 896 | # already-connected socket was passed or when only a port |
| 897 | # is given. To avoid this error, you can pass |
| 898 | # server_hostname='' -- this will bypass the hostname |
| 899 | # check. (This also means that if host is a numeric |
| 900 | # IP/IPv6 address, we will attempt to verify that exact |
| 901 | # address; this will probably fail, but it is possible to |
| 902 | # create a certificate for a specific IP address, so we |
| 903 | # don't judge it here.) |
| 904 | if not host: |
| 905 | raise ValueError('You must set server_hostname ' |
| 906 | 'when using ssl without a host') |
| 907 | server_hostname = host |
Guido van Rossum | a8d630a | 2013-11-01 14:20:55 -0700 | [diff] [blame] | 908 | |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 909 | if ssl_handshake_timeout is not None and not ssl: |
| 910 | raise ValueError( |
| 911 | 'ssl_handshake_timeout is only meaningful with ssl') |
| 912 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 913 | if host is not None or port is not None: |
| 914 | if sock is not None: |
| 915 | raise ValueError( |
| 916 | 'host/port and sock can not be specified at the same time') |
| 917 | |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 918 | infos = await self._ensure_resolved( |
| 919 | (host, port), family=family, |
| 920 | type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 921 | if not infos: |
| 922 | raise OSError('getaddrinfo() returned empty list') |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 923 | |
| 924 | if local_addr is not None: |
| 925 | laddr_infos = await self._ensure_resolved( |
| 926 | local_addr, family=family, |
| 927 | type=socket.SOCK_STREAM, proto=proto, |
| 928 | flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 929 | if not laddr_infos: |
| 930 | raise OSError('getaddrinfo() returned empty list') |
| 931 | |
| 932 | exceptions = [] |
| 933 | for family, type, proto, cname, address in infos: |
| 934 | try: |
| 935 | sock = socket.socket(family=family, type=type, proto=proto) |
| 936 | sock.setblocking(False) |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 937 | if local_addr is not None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 938 | for _, _, _, _, laddr in laddr_infos: |
| 939 | try: |
| 940 | sock.bind(laddr) |
| 941 | break |
| 942 | except OSError as exc: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 943 | msg = ( |
| 944 | f'error while attempting to bind on ' |
| 945 | f'address {laddr!r}: ' |
| 946 | f'{exc.strerror.lower()}' |
| 947 | ) |
| 948 | exc = OSError(exc.errno, msg) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 949 | exceptions.append(exc) |
| 950 | else: |
| 951 | sock.close() |
| 952 | sock = None |
| 953 | continue |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 954 | if self._debug: |
| 955 | logger.debug("connect %r to %r", sock, address) |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 956 | await self.sock_connect(sock, address) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 957 | except OSError as exc: |
| 958 | if sock is not None: |
| 959 | sock.close() |
| 960 | exceptions.append(exc) |
Victor Stinner | 223a624 | 2014-06-04 00:11:52 +0200 | [diff] [blame] | 961 | except: |
| 962 | if sock is not None: |
| 963 | sock.close() |
| 964 | raise |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 965 | else: |
| 966 | break |
| 967 | else: |
| 968 | if len(exceptions) == 1: |
| 969 | raise exceptions[0] |
| 970 | else: |
| 971 | # If they all have the same str(), raise one. |
| 972 | model = str(exceptions[0]) |
| 973 | if all(str(exc) == model for exc in exceptions): |
| 974 | raise exceptions[0] |
| 975 | # Raise a combined exception so the user can see all |
| 976 | # the various error messages. |
| 977 | raise OSError('Multiple exceptions: {}'.format( |
| 978 | ', '.join(str(exc) for exc in exceptions))) |
| 979 | |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 980 | else: |
| 981 | if sock is None: |
| 982 | raise ValueError( |
| 983 | 'host and port was not specified and no sock specified') |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 984 | if sock.type != socket.SOCK_STREAM: |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 985 | # We allow AF_INET, AF_INET6, AF_UNIX as long as they |
| 986 | # are SOCK_STREAM. |
| 987 | # We support passing AF_UNIX sockets even though we have |
| 988 | # a dedicated API for that: create_unix_connection. |
| 989 | # Disallowing AF_UNIX in this method, breaks backwards |
| 990 | # compatibility. |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 991 | raise ValueError( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 992 | f'A Stream Socket was expected, got {sock!r}') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 993 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 994 | transport, protocol = await self._create_connection_transport( |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 995 | sock, protocol_factory, ssl, server_hostname, |
| 996 | ssl_handshake_timeout=ssl_handshake_timeout) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 997 | if self._debug: |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 998 | # Get the socket from the transport because SSL transport closes |
| 999 | # the old socket and creates a new SSL socket |
| 1000 | sock = transport.get_extra_info('socket') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1001 | logger.debug("%r connected to %s:%r: (%r, %r)", |
| 1002 | sock, host, port, transport, protocol) |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 1003 | return transport, protocol |
| 1004 | |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 1005 | async def _create_connection_transport( |
| 1006 | self, sock, protocol_factory, ssl, |
| 1007 | server_hostname, server_side=False, |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 1008 | ssl_handshake_timeout=None): |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1009 | |
| 1010 | sock.setblocking(False) |
| 1011 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1012 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1013 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1014 | if ssl: |
| 1015 | sslcontext = None if isinstance(ssl, bool) else ssl |
| 1016 | transport = self._make_ssl_transport( |
| 1017 | sock, protocol, sslcontext, waiter, |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 1018 | server_side=server_side, server_hostname=server_hostname, |
| 1019 | ssl_handshake_timeout=ssl_handshake_timeout) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1020 | else: |
| 1021 | transport = self._make_socket_transport(sock, protocol, waiter) |
| 1022 | |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 1023 | try: |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1024 | await waiter |
Victor Stinner | 0c2e408 | 2015-01-22 00:17:41 +0100 | [diff] [blame] | 1025 | except: |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 1026 | transport.close() |
| 1027 | raise |
| 1028 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1029 | return transport, protocol |
| 1030 | |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 1031 | async def sendfile(self, transport, file, offset=0, count=None, |
| 1032 | *, fallback=True): |
| 1033 | """Send a file to transport. |
| 1034 | |
| 1035 | Return the total number of bytes which were sent. |
| 1036 | |
| 1037 | The method uses high-performance os.sendfile if available. |
| 1038 | |
| 1039 | file must be a regular file object opened in binary mode. |
| 1040 | |
| 1041 | offset tells from where to start reading the file. If specified, |
| 1042 | count is the total number of bytes to transmit as opposed to |
| 1043 | sending the file until EOF is reached. File position is updated on |
| 1044 | return or also in case of error in which case file.tell() |
| 1045 | can be used to figure out the number of bytes |
| 1046 | which were sent. |
| 1047 | |
| 1048 | fallback set to True makes asyncio to manually read and send |
| 1049 | the file when the platform does not support the sendfile syscall |
| 1050 | (e.g. Windows or SSL socket on Unix). |
| 1051 | |
| 1052 | Raise SendfileNotAvailableError if the system does not support |
| 1053 | sendfile syscall and fallback is False. |
| 1054 | """ |
| 1055 | if transport.is_closing(): |
| 1056 | raise RuntimeError("Transport is closing") |
| 1057 | mode = getattr(transport, '_sendfile_compatible', |
| 1058 | constants._SendfileMode.UNSUPPORTED) |
| 1059 | if mode is constants._SendfileMode.UNSUPPORTED: |
| 1060 | raise RuntimeError( |
| 1061 | f"sendfile is not supported for transport {transport!r}") |
| 1062 | if mode is constants._SendfileMode.TRY_NATIVE: |
| 1063 | try: |
| 1064 | return await self._sendfile_native(transport, file, |
| 1065 | offset, count) |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 1066 | except exceptions.SendfileNotAvailableError as exc: |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 1067 | if not fallback: |
| 1068 | raise |
Yury Selivanov | b1a6ac4 | 2018-01-27 15:52:52 -0500 | [diff] [blame] | 1069 | |
| 1070 | if not fallback: |
| 1071 | raise RuntimeError( |
| 1072 | f"fallback is disabled and native sendfile is not " |
| 1073 | f"supported for transport {transport!r}") |
| 1074 | |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 1075 | return await self._sendfile_fallback(transport, file, |
| 1076 | offset, count) |
| 1077 | |
| 1078 | async def _sendfile_native(self, transp, file, offset, count): |
Andrew Svetlov | 0baa72f | 2018-09-11 10:13:04 -0700 | [diff] [blame] | 1079 | raise exceptions.SendfileNotAvailableError( |
Andrew Svetlov | 7c68407 | 2018-01-27 21:22:47 +0200 | [diff] [blame] | 1080 | "sendfile syscall is not supported") |
| 1081 | |
| 1082 | async def _sendfile_fallback(self, transp, file, offset, count): |
| 1083 | if offset: |
| 1084 | file.seek(offset) |
| 1085 | blocksize = min(count, 16384) if count else 16384 |
| 1086 | buf = bytearray(blocksize) |
| 1087 | total_sent = 0 |
| 1088 | proto = _SendfileFallbackProtocol(transp) |
| 1089 | try: |
| 1090 | while True: |
| 1091 | if count: |
| 1092 | blocksize = min(count - total_sent, blocksize) |
| 1093 | if blocksize <= 0: |
| 1094 | return total_sent |
| 1095 | view = memoryview(buf)[:blocksize] |
| 1096 | read = file.readinto(view) |
| 1097 | if not read: |
| 1098 | return total_sent # EOF |
| 1099 | await proto.drain() |
| 1100 | transp.write(view) |
| 1101 | total_sent += read |
| 1102 | finally: |
| 1103 | if total_sent > 0 and hasattr(file, 'seek'): |
| 1104 | file.seek(offset + total_sent) |
| 1105 | await proto.restore() |
| 1106 | |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 1107 | async def start_tls(self, transport, protocol, sslcontext, *, |
| 1108 | server_side=False, |
| 1109 | server_hostname=None, |
| 1110 | ssl_handshake_timeout=None): |
| 1111 | """Upgrade transport to TLS. |
| 1112 | |
| 1113 | Return a new transport that *protocol* should start using |
| 1114 | immediately. |
| 1115 | """ |
| 1116 | if ssl is None: |
| 1117 | raise RuntimeError('Python ssl module is not available') |
| 1118 | |
| 1119 | if not isinstance(sslcontext, ssl.SSLContext): |
| 1120 | raise TypeError( |
| 1121 | f'sslcontext is expected to be an instance of ssl.SSLContext, ' |
| 1122 | f'got {sslcontext!r}') |
| 1123 | |
| 1124 | if not getattr(transport, '_start_tls_compatible', False): |
| 1125 | raise TypeError( |
Yury Selivanov | 415bc46 | 2018-06-05 08:59:58 -0400 | [diff] [blame] | 1126 | f'transport {transport!r} is not supported by start_tls()') |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 1127 | |
| 1128 | waiter = self.create_future() |
| 1129 | ssl_protocol = sslproto.SSLProtocol( |
| 1130 | self, protocol, sslcontext, waiter, |
| 1131 | server_side, server_hostname, |
| 1132 | ssl_handshake_timeout=ssl_handshake_timeout, |
| 1133 | call_connection_made=False) |
| 1134 | |
Yury Selivanov | f295587 | 2018-05-29 01:00:12 -0400 | [diff] [blame] | 1135 | # Pause early so that "ssl_protocol.data_received()" doesn't |
| 1136 | # have a chance to get called before "ssl_protocol.connection_made()". |
| 1137 | transport.pause_reading() |
| 1138 | |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 1139 | transport.set_protocol(ssl_protocol) |
Yury Selivanov | 415bc46 | 2018-06-05 08:59:58 -0400 | [diff] [blame] | 1140 | conmade_cb = self.call_soon(ssl_protocol.connection_made, transport) |
| 1141 | resume_cb = self.call_soon(transport.resume_reading) |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 1142 | |
Yury Selivanov | 9602643 | 2018-06-04 11:32:35 -0400 | [diff] [blame] | 1143 | try: |
| 1144 | await waiter |
| 1145 | except Exception: |
| 1146 | transport.close() |
Yury Selivanov | 415bc46 | 2018-06-05 08:59:58 -0400 | [diff] [blame] | 1147 | conmade_cb.cancel() |
| 1148 | resume_cb.cancel() |
Yury Selivanov | 9602643 | 2018-06-04 11:32:35 -0400 | [diff] [blame] | 1149 | raise |
| 1150 | |
Yury Selivanov | f111b3d | 2017-12-30 00:35:36 -0500 | [diff] [blame] | 1151 | return ssl_protocol._app_transport |
| 1152 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1153 | async def create_datagram_endpoint(self, protocol_factory, |
| 1154 | local_addr=None, remote_addr=None, *, |
| 1155 | family=0, proto=0, flags=0, |
| 1156 | reuse_address=None, reuse_port=None, |
| 1157 | allow_broadcast=None, sock=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1158 | """Create datagram connection.""" |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1159 | if sock is not None: |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 1160 | if sock.type != socket.SOCK_DGRAM: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1161 | raise ValueError( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1162 | f'A UDP Socket was expected, got {sock!r}') |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1163 | if (local_addr or remote_addr or |
| 1164 | family or proto or flags or |
| 1165 | reuse_address or reuse_port or allow_broadcast): |
| 1166 | # show the problematic kwargs in exception msg |
| 1167 | opts = dict(local_addr=local_addr, remote_addr=remote_addr, |
| 1168 | family=family, proto=proto, flags=flags, |
| 1169 | reuse_address=reuse_address, reuse_port=reuse_port, |
| 1170 | allow_broadcast=allow_broadcast) |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1171 | problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1172 | raise ValueError( |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1173 | f'socket modifier keyword arguments can not be used ' |
| 1174 | f'when sock is specified. ({problems})') |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1175 | sock.setblocking(False) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1176 | r_addr = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1177 | else: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1178 | if not (local_addr or remote_addr): |
| 1179 | if family == 0: |
| 1180 | raise ValueError('unexpected address family') |
| 1181 | addr_pairs_info = (((family, proto), (None, None)),) |
Quentin Dawans | fe4ea9c | 2017-10-30 14:43:02 +0100 | [diff] [blame] | 1182 | elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX: |
| 1183 | for addr in (local_addr, remote_addr): |
Victor Stinner | 28e6165 | 2017-11-28 00:34:08 +0100 | [diff] [blame] | 1184 | if addr is not None and not isinstance(addr, str): |
Quentin Dawans | fe4ea9c | 2017-10-30 14:43:02 +0100 | [diff] [blame] | 1185 | raise TypeError('string is expected') |
| 1186 | addr_pairs_info = (((family, proto), |
| 1187 | (local_addr, remote_addr)), ) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1188 | else: |
| 1189 | # join address by (family, protocol) |
Inada Naoki | f345170 | 2019-02-05 17:04:40 +0900 | [diff] [blame] | 1190 | addr_infos = {} # Using order preserving dict |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1191 | for idx, addr in ((0, local_addr), (1, remote_addr)): |
| 1192 | if addr is not None: |
| 1193 | assert isinstance(addr, tuple) and len(addr) == 2, ( |
| 1194 | '2-tuple is expected') |
| 1195 | |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 1196 | infos = await self._ensure_resolved( |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 1197 | addr, family=family, type=socket.SOCK_DGRAM, |
| 1198 | proto=proto, flags=flags, loop=self) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1199 | if not infos: |
| 1200 | raise OSError('getaddrinfo() returned empty list') |
| 1201 | |
| 1202 | for fam, _, pro, _, address in infos: |
| 1203 | key = (fam, pro) |
| 1204 | if key not in addr_infos: |
| 1205 | addr_infos[key] = [None, None] |
| 1206 | addr_infos[key][idx] = address |
| 1207 | |
| 1208 | # each addr has to have info for each (family, proto) pair |
| 1209 | addr_pairs_info = [ |
| 1210 | (key, addr_pair) for key, addr_pair in addr_infos.items() |
| 1211 | if not ((local_addr and addr_pair[0] is None) or |
| 1212 | (remote_addr and addr_pair[1] is None))] |
| 1213 | |
| 1214 | if not addr_pairs_info: |
| 1215 | raise ValueError('can not get address information') |
| 1216 | |
| 1217 | exceptions = [] |
| 1218 | |
| 1219 | if reuse_address is None: |
| 1220 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 1221 | |
| 1222 | for ((family, proto), |
| 1223 | (local_address, remote_address)) in addr_pairs_info: |
| 1224 | sock = None |
| 1225 | r_addr = None |
| 1226 | try: |
| 1227 | sock = socket.socket( |
| 1228 | family=family, type=socket.SOCK_DGRAM, proto=proto) |
| 1229 | if reuse_address: |
| 1230 | sock.setsockopt( |
| 1231 | socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1232 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 1233 | _set_reuseport(sock) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1234 | if allow_broadcast: |
| 1235 | sock.setsockopt( |
| 1236 | socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 1237 | sock.setblocking(False) |
| 1238 | |
| 1239 | if local_addr: |
| 1240 | sock.bind(local_address) |
| 1241 | if remote_addr: |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1242 | await self.sock_connect(sock, remote_address) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1243 | r_addr = remote_address |
| 1244 | except OSError as exc: |
| 1245 | if sock is not None: |
| 1246 | sock.close() |
| 1247 | exceptions.append(exc) |
| 1248 | except: |
| 1249 | if sock is not None: |
| 1250 | sock.close() |
| 1251 | raise |
| 1252 | else: |
| 1253 | break |
| 1254 | else: |
| 1255 | raise exceptions[0] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1256 | |
| 1257 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1258 | waiter = self.create_future() |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1259 | transport = self._make_datagram_transport( |
| 1260 | sock, protocol, r_addr, waiter) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 1261 | if self._debug: |
| 1262 | if local_addr: |
| 1263 | logger.info("Datagram endpoint local_addr=%r remote_addr=%r " |
| 1264 | "created: (%r, %r)", |
| 1265 | local_addr, remote_addr, transport, protocol) |
| 1266 | else: |
| 1267 | logger.debug("Datagram endpoint remote_addr=%r created: " |
| 1268 | "(%r, %r)", |
| 1269 | remote_addr, transport, protocol) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1270 | |
| 1271 | try: |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1272 | await waiter |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1273 | except: |
| 1274 | transport.close() |
| 1275 | raise |
| 1276 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1277 | return transport, protocol |
| 1278 | |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 1279 | async def _ensure_resolved(self, address, *, |
| 1280 | family=0, type=socket.SOCK_STREAM, |
| 1281 | proto=0, flags=0, loop): |
| 1282 | host, port = address[:2] |
| 1283 | info = _ipaddr_info(host, port, family, type, proto) |
| 1284 | if info is not None: |
| 1285 | # "host" is already a resolved IP. |
| 1286 | return [info] |
| 1287 | else: |
| 1288 | return await loop.getaddrinfo(host, port, family=family, type=type, |
| 1289 | proto=proto, flags=flags) |
| 1290 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1291 | async def _create_server_getaddrinfo(self, host, port, family, flags): |
Yury Selivanov | 19a44f6 | 2017-12-14 20:53:26 -0500 | [diff] [blame] | 1292 | infos = await self._ensure_resolved((host, port), family=family, |
| 1293 | type=socket.SOCK_STREAM, |
| 1294 | flags=flags, loop=self) |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1295 | if not infos: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1296 | raise OSError(f'getaddrinfo({host!r}) returned empty list') |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1297 | return infos |
| 1298 | |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 1299 | async def create_server( |
| 1300 | self, protocol_factory, host=None, port=None, |
| 1301 | *, |
| 1302 | family=socket.AF_UNSPEC, |
| 1303 | flags=socket.AI_PASSIVE, |
| 1304 | sock=None, |
| 1305 | backlog=100, |
| 1306 | ssl=None, |
| 1307 | reuse_address=None, |
| 1308 | reuse_port=None, |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 1309 | ssl_handshake_timeout=None, |
| 1310 | start_serving=True): |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1311 | """Create a TCP server. |
| 1312 | |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1313 | The host parameter can be a string, in that case the TCP server is |
| 1314 | bound to host and port. |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1315 | |
| 1316 | The host parameter can also be a sequence of strings and in that case |
Yury Selivanov | e076ffb | 2016-03-02 11:17:01 -0500 | [diff] [blame] | 1317 | the TCP server is bound to all hosts of the sequence. If a host |
| 1318 | appears multiple times (possibly indirectly e.g. when hostnames |
| 1319 | resolve to the same IP address), the server is only bound once to that |
| 1320 | host. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 1321 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1322 | Return a Server object which can be used to stop the service. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 1323 | |
| 1324 | This method is a coroutine. |
| 1325 | """ |
Guido van Rossum | 28dff0d | 2013-11-01 14:22:30 -0700 | [diff] [blame] | 1326 | if isinstance(ssl, bool): |
| 1327 | raise TypeError('ssl argument must be an SSLContext or None') |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 1328 | |
| 1329 | if ssl_handshake_timeout is not None and ssl is None: |
| 1330 | raise ValueError( |
| 1331 | 'ssl_handshake_timeout is only meaningful with ssl') |
| 1332 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1333 | if host is not None or port is not None: |
| 1334 | if sock is not None: |
| 1335 | raise ValueError( |
| 1336 | 'host/port and sock can not be specified at the same time') |
| 1337 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1338 | if reuse_address is None: |
| 1339 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 1340 | sockets = [] |
| 1341 | if host == '': |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1342 | hosts = [None] |
| 1343 | elif (isinstance(host, str) or |
Serhiy Storchaka | 2e576f5 | 2017-04-24 09:05:00 +0300 | [diff] [blame] | 1344 | not isinstance(host, collections.abc.Iterable)): |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1345 | hosts = [host] |
| 1346 | else: |
| 1347 | hosts = host |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1348 | |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1349 | fs = [self._create_server_getaddrinfo(host, port, family=family, |
| 1350 | flags=flags) |
| 1351 | for host in hosts] |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1352 | infos = await tasks.gather(*fs, loop=self) |
Yury Selivanov | e076ffb | 2016-03-02 11:17:01 -0500 | [diff] [blame] | 1353 | infos = set(itertools.chain.from_iterable(infos)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1354 | |
| 1355 | completed = False |
| 1356 | try: |
| 1357 | for res in infos: |
| 1358 | af, socktype, proto, canonname, sa = res |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1359 | try: |
| 1360 | sock = socket.socket(af, socktype, proto) |
| 1361 | except socket.error: |
| 1362 | # Assume it's a bad family/type/protocol combination. |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 1363 | if self._debug: |
| 1364 | logger.warning('create_server() failed to create ' |
| 1365 | 'socket.socket(%r, %r, %r)', |
| 1366 | af, socktype, proto, exc_info=True) |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1367 | continue |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1368 | sockets.append(sock) |
| 1369 | if reuse_address: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1370 | sock.setsockopt( |
| 1371 | socket.SOL_SOCKET, socket.SO_REUSEADDR, True) |
| 1372 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 1373 | _set_reuseport(sock) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1374 | # Disable IPv4/IPv6 dual stack support (enabled by |
| 1375 | # default on Linux) which makes a single socket |
| 1376 | # listen on both address families. |
Yury Selivanov | d904c23 | 2018-06-28 21:59:32 -0400 | [diff] [blame] | 1377 | if (_HAS_IPv6 and |
| 1378 | af == socket.AF_INET6 and |
| 1379 | hasattr(socket, 'IPPROTO_IPV6')): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1380 | sock.setsockopt(socket.IPPROTO_IPV6, |
| 1381 | socket.IPV6_V6ONLY, |
| 1382 | True) |
| 1383 | try: |
| 1384 | sock.bind(sa) |
| 1385 | except OSError as err: |
| 1386 | raise OSError(err.errno, 'error while attempting ' |
| 1387 | 'to bind on address %r: %s' |
Serhiy Storchaka | 5affd23 | 2017-04-05 09:37:24 +0300 | [diff] [blame] | 1388 | % (sa, err.strerror.lower())) from None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1389 | completed = True |
| 1390 | finally: |
| 1391 | if not completed: |
| 1392 | for sock in sockets: |
| 1393 | sock.close() |
| 1394 | else: |
| 1395 | if sock is None: |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1396 | raise ValueError('Neither host/port nor sock were specified') |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 1397 | if sock.type != socket.SOCK_STREAM: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1398 | raise ValueError(f'A Stream Socket was expected, got {sock!r}') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1399 | sockets = [sock] |
| 1400 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1401 | for sock in sockets: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1402 | sock.setblocking(False) |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 1403 | |
| 1404 | server = Server(self, sockets, protocol_factory, |
| 1405 | ssl, backlog, ssl_handshake_timeout) |
| 1406 | if start_serving: |
| 1407 | server._start_serving() |
Yury Selivanov | dbf1022 | 2018-05-28 14:31:28 -0400 | [diff] [blame] | 1408 | # Skip one loop iteration so that all 'loop.add_reader' |
| 1409 | # go through. |
| 1410 | await tasks.sleep(0, loop=self) |
Yury Selivanov | c9070d0 | 2018-01-25 18:08:09 -0500 | [diff] [blame] | 1411 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 1412 | if self._debug: |
| 1413 | logger.info("%r is serving", server) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1414 | return server |
| 1415 | |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 1416 | async def connect_accepted_socket( |
| 1417 | self, protocol_factory, sock, |
| 1418 | *, ssl=None, |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 1419 | ssl_handshake_timeout=None): |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1420 | """Handle an accepted connection. |
| 1421 | |
| 1422 | This is used by servers that accept connections outside of |
| 1423 | asyncio but that use asyncio to handle connections. |
| 1424 | |
| 1425 | This method is a coroutine. When completed, the coroutine |
| 1426 | returns a (transport, protocol) pair. |
| 1427 | """ |
Yury Selivanov | a7bd64c | 2017-12-19 06:44:37 -0500 | [diff] [blame] | 1428 | if sock.type != socket.SOCK_STREAM: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1429 | raise ValueError(f'A Stream Socket was expected, got {sock!r}') |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1430 | |
Andrew Svetlov | 51eb1c6 | 2017-12-20 20:24:43 +0200 | [diff] [blame] | 1431 | if ssl_handshake_timeout is not None and not ssl: |
| 1432 | raise ValueError( |
| 1433 | 'ssl_handshake_timeout is only meaningful with ssl') |
| 1434 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1435 | transport, protocol = await self._create_connection_transport( |
Neil Aspinall | f7686c1 | 2017-12-19 19:45:42 +0000 | [diff] [blame] | 1436 | sock, protocol_factory, ssl, '', server_side=True, |
| 1437 | ssl_handshake_timeout=ssl_handshake_timeout) |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1438 | if self._debug: |
| 1439 | # Get the socket from the transport because SSL transport closes |
| 1440 | # the old socket and creates a new SSL socket |
| 1441 | sock = transport.get_extra_info('socket') |
| 1442 | logger.debug("%r handled: (%r, %r)", sock, transport, protocol) |
| 1443 | return transport, protocol |
| 1444 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1445 | async def connect_read_pipe(self, protocol_factory, pipe): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1446 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1447 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1448 | transport = self._make_read_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1449 | |
| 1450 | try: |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1451 | await waiter |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1452 | except: |
| 1453 | transport.close() |
| 1454 | raise |
| 1455 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1456 | if self._debug: |
| 1457 | logger.debug('Read pipe %r connected: (%r, %r)', |
| 1458 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1459 | return transport, protocol |
| 1460 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1461 | async def connect_write_pipe(self, protocol_factory, pipe): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1462 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1463 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1464 | transport = self._make_write_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1465 | |
| 1466 | try: |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1467 | await waiter |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1468 | except: |
| 1469 | transport.close() |
| 1470 | raise |
| 1471 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1472 | if self._debug: |
| 1473 | logger.debug('Write pipe %r connected: (%r, %r)', |
| 1474 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1475 | return transport, protocol |
| 1476 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1477 | def _log_subprocess(self, msg, stdin, stdout, stderr): |
| 1478 | info = [msg] |
| 1479 | if stdin is not None: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1480 | info.append(f'stdin={_format_pipe(stdin)}') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1481 | if stdout is not None and stderr == subprocess.STDOUT: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1482 | info.append(f'stdout=stderr={_format_pipe(stdout)}') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1483 | else: |
| 1484 | if stdout is not None: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1485 | info.append(f'stdout={_format_pipe(stdout)}') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1486 | if stderr is not None: |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1487 | info.append(f'stderr={_format_pipe(stderr)}') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1488 | logger.debug(' '.join(info)) |
| 1489 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1490 | async def subprocess_shell(self, protocol_factory, cmd, *, |
| 1491 | stdin=subprocess.PIPE, |
| 1492 | stdout=subprocess.PIPE, |
| 1493 | stderr=subprocess.PIPE, |
| 1494 | universal_newlines=False, |
| 1495 | shell=True, bufsize=0, |
| 1496 | **kwargs): |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1497 | if not isinstance(cmd, (bytes, str)): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1498 | raise ValueError("cmd must be a string") |
| 1499 | if universal_newlines: |
| 1500 | raise ValueError("universal_newlines must be False") |
| 1501 | if not shell: |
Victor Stinner | 323748e | 2014-01-31 12:28:30 +0100 | [diff] [blame] | 1502 | raise ValueError("shell must be True") |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1503 | if bufsize != 0: |
| 1504 | raise ValueError("bufsize must be 0") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1505 | protocol = protocol_factory() |
Yury Selivanov | 12f482e | 2018-06-08 18:24:37 -0400 | [diff] [blame] | 1506 | debug_log = None |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1507 | if self._debug: |
| 1508 | # don't log parameters: they may contain sensitive information |
| 1509 | # (password) and may be too long |
| 1510 | debug_log = 'run shell command %r' % cmd |
| 1511 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1512 | transport = await self._make_subprocess_transport( |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1513 | protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs) |
Yury Selivanov | 12f482e | 2018-06-08 18:24:37 -0400 | [diff] [blame] | 1514 | if self._debug and debug_log is not None: |
Vinay Sajip | dd917f8 | 2016-08-31 08:22:29 +0100 | [diff] [blame] | 1515 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1516 | return transport, protocol |
| 1517 | |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1518 | async def subprocess_exec(self, protocol_factory, program, *args, |
| 1519 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1520 | stderr=subprocess.PIPE, universal_newlines=False, |
| 1521 | shell=False, bufsize=0, **kwargs): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1522 | if universal_newlines: |
| 1523 | raise ValueError("universal_newlines must be False") |
| 1524 | if shell: |
| 1525 | raise ValueError("shell must be False") |
| 1526 | if bufsize != 0: |
| 1527 | raise ValueError("bufsize must be 0") |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1528 | popen_args = (program,) + args |
| 1529 | for arg in popen_args: |
| 1530 | if not isinstance(arg, (str, bytes)): |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1531 | raise TypeError( |
| 1532 | f"program arguments must be a bytes or text string, " |
| 1533 | f"not {type(arg).__name__}") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1534 | protocol = protocol_factory() |
Yury Selivanov | 12f482e | 2018-06-08 18:24:37 -0400 | [diff] [blame] | 1535 | debug_log = None |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1536 | if self._debug: |
| 1537 | # don't log parameters: they may contain sensitive information |
| 1538 | # (password) and may be too long |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1539 | debug_log = f'execute program {program!r}' |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1540 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Andrew Svetlov | 5f841b5 | 2017-12-09 00:23:48 +0200 | [diff] [blame] | 1541 | transport = await self._make_subprocess_transport( |
Yury Selivanov | 5779752 | 2014-02-18 22:56:15 -0500 | [diff] [blame] | 1542 | protocol, popen_args, False, stdin, stdout, stderr, |
| 1543 | bufsize, **kwargs) |
Yury Selivanov | 12f482e | 2018-06-08 18:24:37 -0400 | [diff] [blame] | 1544 | if self._debug and debug_log is not None: |
Vinay Sajip | dd917f8 | 2016-08-31 08:22:29 +0100 | [diff] [blame] | 1545 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1546 | return transport, protocol |
| 1547 | |
Yury Selivanov | 7ed7ce6 | 2016-05-16 15:20:38 -0400 | [diff] [blame] | 1548 | def get_exception_handler(self): |
| 1549 | """Return an exception handler, or None if the default one is in use. |
| 1550 | """ |
| 1551 | return self._exception_handler |
| 1552 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1553 | def set_exception_handler(self, handler): |
| 1554 | """Set handler as the new event loop exception handler. |
| 1555 | |
| 1556 | If handler is None, the default exception handler will |
| 1557 | be set. |
| 1558 | |
| 1559 | If handler is a callable object, it should have a |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1560 | signature matching '(loop, context)', where 'loop' |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1561 | will be a reference to the active event loop, 'context' |
| 1562 | will be a dict object (see `call_exception_handler()` |
| 1563 | documentation for details about context). |
| 1564 | """ |
| 1565 | if handler is not None and not callable(handler): |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1566 | raise TypeError(f'A callable object or None is expected, ' |
| 1567 | f'got {handler!r}') |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1568 | self._exception_handler = handler |
| 1569 | |
| 1570 | def default_exception_handler(self, context): |
| 1571 | """Default exception handler. |
| 1572 | |
| 1573 | This is called when an exception occurs and no exception |
| 1574 | handler is set, and can be called by a custom exception |
| 1575 | handler that wants to defer to the default behavior. |
| 1576 | |
Antoine Pitrou | 921e943 | 2017-11-07 17:23:29 +0100 | [diff] [blame] | 1577 | This default handler logs the error message and other |
| 1578 | context-dependent information. In debug mode, a truncated |
| 1579 | stack trace is also appended showing where the given object |
| 1580 | (e.g. a handle or future or task) was created, if any. |
| 1581 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1582 | The context parameter has the same meaning as in |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1583 | `call_exception_handler()`. |
| 1584 | """ |
| 1585 | message = context.get('message') |
| 1586 | if not message: |
| 1587 | message = 'Unhandled exception in event loop' |
| 1588 | |
| 1589 | exception = context.get('exception') |
| 1590 | if exception is not None: |
| 1591 | exc_info = (type(exception), exception, exception.__traceback__) |
| 1592 | else: |
| 1593 | exc_info = False |
| 1594 | |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1595 | if ('source_traceback' not in context and |
| 1596 | self._current_handle is not None and |
| 1597 | self._current_handle._source_traceback): |
| 1598 | context['handle_traceback'] = \ |
| 1599 | self._current_handle._source_traceback |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1600 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1601 | log_lines = [message] |
| 1602 | for key in sorted(context): |
| 1603 | if key in {'message', 'exception'}: |
| 1604 | continue |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1605 | value = context[key] |
| 1606 | if key == 'source_traceback': |
| 1607 | tb = ''.join(traceback.format_list(value)) |
| 1608 | value = 'Object created at (most recent call last):\n' |
| 1609 | value += tb.rstrip() |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1610 | elif key == 'handle_traceback': |
| 1611 | tb = ''.join(traceback.format_list(value)) |
| 1612 | value = 'Handle created at (most recent call last):\n' |
| 1613 | value += tb.rstrip() |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1614 | else: |
| 1615 | value = repr(value) |
Yury Selivanov | 6370f34 | 2017-12-10 18:36:12 -0500 | [diff] [blame] | 1616 | log_lines.append(f'{key}: {value}') |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1617 | |
| 1618 | logger.error('\n'.join(log_lines), exc_info=exc_info) |
| 1619 | |
| 1620 | def call_exception_handler(self, context): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1621 | """Call the current event loop's exception handler. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1622 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1623 | The context argument is a dict containing the following keys: |
| 1624 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1625 | - 'message': Error message; |
| 1626 | - 'exception' (optional): Exception object; |
| 1627 | - 'future' (optional): Future instance; |
Yury Selivanov | a4afcdf | 2018-01-21 14:56:59 -0500 | [diff] [blame] | 1628 | - 'task' (optional): Task instance; |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1629 | - 'handle' (optional): Handle instance; |
| 1630 | - 'protocol' (optional): Protocol instance; |
| 1631 | - 'transport' (optional): Transport instance; |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 1632 | - 'socket' (optional): Socket instance; |
| 1633 | - 'asyncgen' (optional): Asynchronous generator that caused |
| 1634 | the exception. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1635 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1636 | New keys maybe introduced in the future. |
| 1637 | |
| 1638 | Note: do not overload this method in an event loop subclass. |
| 1639 | For custom exception handling, use the |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1640 | `set_exception_handler()` method. |
| 1641 | """ |
| 1642 | if self._exception_handler is None: |
| 1643 | try: |
| 1644 | self.default_exception_handler(context) |
| 1645 | except Exception: |
| 1646 | # Second protection layer for unexpected errors |
| 1647 | # in the default implementation, as well as for subclassed |
| 1648 | # event loops with overloaded "default_exception_handler". |
| 1649 | logger.error('Exception in default exception handler', |
| 1650 | exc_info=True) |
| 1651 | else: |
| 1652 | try: |
| 1653 | self._exception_handler(self, context) |
| 1654 | except Exception as exc: |
| 1655 | # Exception in the user set custom exception handler. |
| 1656 | try: |
| 1657 | # Let's try default handler. |
| 1658 | self.default_exception_handler({ |
| 1659 | 'message': 'Unhandled error in exception handler', |
| 1660 | 'exception': exc, |
| 1661 | 'context': context, |
| 1662 | }) |
| 1663 | except Exception: |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1664 | # Guard 'default_exception_handler' in case it is |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1665 | # overloaded. |
| 1666 | logger.error('Exception in default exception handler ' |
| 1667 | 'while handling an unexpected error ' |
| 1668 | 'in custom exception handler', |
| 1669 | exc_info=True) |
| 1670 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1671 | def _add_callback(self, handle): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1672 | """Add a Handle to _scheduled (TimerHandle) or _ready.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1673 | assert isinstance(handle, events.Handle), 'A Handle is required here' |
| 1674 | if handle._cancelled: |
| 1675 | return |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1676 | assert not isinstance(handle, events.TimerHandle) |
| 1677 | self._ready.append(handle) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1678 | |
| 1679 | def _add_callback_signalsafe(self, handle): |
| 1680 | """Like _add_callback() but called from a signal handler.""" |
| 1681 | self._add_callback(handle) |
| 1682 | self._write_to_self() |
| 1683 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1684 | def _timer_handle_cancelled(self, handle): |
| 1685 | """Notification that a TimerHandle has been cancelled.""" |
| 1686 | if handle._scheduled: |
| 1687 | self._timer_cancelled_count += 1 |
| 1688 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1689 | def _run_once(self): |
| 1690 | """Run one full iteration of the event loop. |
| 1691 | |
| 1692 | This calls all currently ready callbacks, polls for I/O, |
| 1693 | schedules the resulting callbacks, and finally schedules |
| 1694 | 'call_later' callbacks. |
| 1695 | """ |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1696 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1697 | sched_count = len(self._scheduled) |
| 1698 | if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and |
| 1699 | self._timer_cancelled_count / sched_count > |
| 1700 | _MIN_CANCELLED_TIMER_HANDLES_FRACTION): |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1701 | # Remove delayed calls that were cancelled if their number |
| 1702 | # is too high |
| 1703 | new_scheduled = [] |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1704 | for handle in self._scheduled: |
| 1705 | if handle._cancelled: |
| 1706 | handle._scheduled = False |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1707 | else: |
| 1708 | new_scheduled.append(handle) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1709 | |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1710 | heapq.heapify(new_scheduled) |
| 1711 | self._scheduled = new_scheduled |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1712 | self._timer_cancelled_count = 0 |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1713 | else: |
| 1714 | # Remove delayed calls that were cancelled from head of queue. |
| 1715 | while self._scheduled and self._scheduled[0]._cancelled: |
| 1716 | self._timer_cancelled_count -= 1 |
| 1717 | handle = heapq.heappop(self._scheduled) |
| 1718 | handle._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1719 | |
| 1720 | timeout = None |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 1721 | if self._ready or self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1722 | timeout = 0 |
| 1723 | elif self._scheduled: |
| 1724 | # Compute the desired timeout. |
| 1725 | when = self._scheduled[0]._when |
MartinAltmayer | 944451c | 2018-07-31 15:06:12 +0100 | [diff] [blame] | 1726 | timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1727 | |
Andrew Svetlov | d5bd036 | 2018-09-30 08:28:40 +0300 | [diff] [blame] | 1728 | event_list = self._selector.select(timeout) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1729 | self._process_events(event_list) |
| 1730 | |
| 1731 | # Handle 'later' callbacks that are ready. |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1732 | end_time = self.time() + self._clock_resolution |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1733 | while self._scheduled: |
| 1734 | handle = self._scheduled[0] |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1735 | if handle._when >= end_time: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1736 | break |
| 1737 | handle = heapq.heappop(self._scheduled) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1738 | handle._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1739 | self._ready.append(handle) |
| 1740 | |
| 1741 | # This is the only place where callbacks are actually *called*. |
| 1742 | # All other places just add them to ready. |
| 1743 | # Note: We run all currently scheduled callbacks, but not any |
| 1744 | # callbacks scheduled by callbacks run this time around -- |
| 1745 | # they will be run the next time (after another I/O poll). |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1746 | # Use an idiom that is thread-safe without using locks. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1747 | ntodo = len(self._ready) |
| 1748 | for i in range(ntodo): |
| 1749 | handle = self._ready.popleft() |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1750 | if handle._cancelled: |
| 1751 | continue |
| 1752 | if self._debug: |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1753 | try: |
| 1754 | self._current_handle = handle |
| 1755 | t0 = self.time() |
| 1756 | handle._run() |
| 1757 | dt = self.time() - t0 |
| 1758 | if dt >= self.slow_callback_duration: |
| 1759 | logger.warning('Executing %s took %.3f seconds', |
| 1760 | _format_handle(handle), dt) |
| 1761 | finally: |
| 1762 | self._current_handle = None |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1763 | else: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1764 | handle._run() |
| 1765 | handle = None # Needed to break cycles when an exception occurs. |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1766 | |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 1767 | def _set_coroutine_origin_tracking(self, enabled): |
| 1768 | if bool(enabled) == bool(self._coroutine_origin_tracking_enabled): |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1769 | return |
| 1770 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1771 | if enabled: |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 1772 | self._coroutine_origin_tracking_saved_depth = ( |
| 1773 | sys.get_coroutine_origin_tracking_depth()) |
| 1774 | sys.set_coroutine_origin_tracking_depth( |
| 1775 | constants.DEBUG_STACK_DEPTH) |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1776 | else: |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 1777 | sys.set_coroutine_origin_tracking_depth( |
| 1778 | self._coroutine_origin_tracking_saved_depth) |
| 1779 | |
| 1780 | self._coroutine_origin_tracking_enabled = enabled |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1781 | |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1782 | def get_debug(self): |
| 1783 | return self._debug |
| 1784 | |
| 1785 | def set_debug(self, enabled): |
| 1786 | self._debug = enabled |
Yury Selivanov | 1af2bf7 | 2015-05-11 22:27:25 -0400 | [diff] [blame] | 1787 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1788 | if self.is_running(): |
Nathaniel J. Smith | fc2f407 | 2018-01-21 06:44:07 -0800 | [diff] [blame] | 1789 | self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled) |