blob: f789635e0f893a3ec86346393b0b939557bfd963 [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Base implementation of event loop.
2
3The event loop can be broken up into a multiplexer (the part
Victor Stinneracdb7822014-07-14 18:33:40 +02004responsible for notifying us of I/O events) and the event loop proper,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07005which wraps a multiplexer with functionality for scheduling callbacks,
6immediately or at a given time in the future.
7
8Whenever a public API takes a callback, subsequent positional
9arguments will be passed to the callback if/when it is called. This
10avoids the proliferation of trivial lambdas implementing closures.
11Keyword arguments for the callback are not supported; this is a
12conscious design decision, leaving the door open for keyword arguments
13to modify the meaning of the API call itself.
14"""
15
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import collections
Serhiy Storchaka2e576f52017-04-24 09:05:00 +030017import collections.abc
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import concurrent.futures
twisteroid ambassador88f07a82019-05-05 19:14:35 +080019import functools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070020import heapq
Victor Stinner5e4a7d82015-09-21 18:33:43 +020021import itertools
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
Quentin Dawans56065d42019-04-09 15:40:59 +020024import stat
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010026import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070027import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020028import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070029import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010030import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070031import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032
Yury Selivanovf111b3d2017-12-30 00:35:36 -050033try:
34 import ssl
35except ImportError: # pragma: no cover
36 ssl = None
37
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020039from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040from . import events
Andrew Svetlov0baa72f2018-09-11 10:13:04 -070041from . import exceptions
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042from . import futures
Andrew Svetlov7c684072018-01-27 21:22:47 +020043from . import protocols
Yury Selivanovf111b3d2017-12-30 00:35:36 -050044from . import sslproto
twisteroid ambassador88f07a82019-05-05 19:14:35 +080045from . import staggered
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046from . import tasks
Andrew Svetlov7c684072018-01-27 21:22:47 +020047from . import transports
Yury Selivanov8cd51652019-05-27 15:57:20 +020048from . import trsock
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070049from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070050
51
Yury Selivanov6370f342017-12-10 18:36:12 -050052__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070053
54
Yury Selivanov592ada92014-09-25 12:07:56 -040055# Minimum number of _scheduled timer handles before cleanup of
56# cancelled handles is performed.
57_MIN_SCHEDULED_TIMER_HANDLES = 100
58
59# Minimum fraction of _scheduled timer handles that are cancelled
60# before cleanup of cancelled handles is performed.
61_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070062
Andrew Svetlov0dd71802018-09-12 14:03:54 -070063
Yury Selivanovd904c232018-06-28 21:59:32 -040064_HAS_IPv6 = hasattr(socket, 'AF_INET6')
65
MartinAltmayer944451c2018-07-31 15:06:12 +010066# Maximum timeout passed to select to avoid OS limitations
67MAXIMUM_SELECT_TIMEOUT = 24 * 3600
68
Kyle Stanleyab513a32019-12-09 09:21:10 -050069# Used for deprecation and removal of `loop.create_datagram_endpoint()`'s
70# *reuse_address* parameter
71_unset = object()
72
Victor Stinnerc94a93a2016-04-01 21:43:39 +020073
Victor Stinner0e6f52a2014-06-20 17:34:15 +020074def _format_handle(handle):
75 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040076 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020077 # format the task
78 return repr(cb.__self__)
79 else:
80 return str(handle)
81
82
Victor Stinneracdb7822014-07-14 18:33:40 +020083def _format_pipe(fd):
84 if fd == subprocess.PIPE:
85 return '<pipe>'
86 elif fd == subprocess.STDOUT:
87 return '<stdout>'
88 else:
89 return repr(fd)
90
91
Yury Selivanov5587d7c2016-09-15 15:45:07 -040092def _set_reuseport(sock):
93 if not hasattr(socket, 'SO_REUSEPORT'):
94 raise ValueError('reuse_port not supported by socket module')
95 else:
96 try:
97 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
98 except OSError:
99 raise ValueError('reuse_port not supported by socket module, '
100 'SO_REUSEPORT defined but not implemented.')
101
102
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +0200103def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400104 # Try to skip getaddrinfo if "host" is already an IP. Users might have
105 # handled name resolution in their own code and pass in resolved IPs.
106 if not hasattr(socket, 'inet_pton'):
107 return
108
109 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
110 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500111 return None
112
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500113 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500114 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500115 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500116 proto = socket.IPPROTO_UDP
117 else:
118 return None
119
Yury Selivanova7146162016-06-02 16:51:07 -0400120 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400121 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700122 elif isinstance(port, bytes) and port == b'':
123 port = 0
124 elif isinstance(port, str) and port == '':
125 port = 0
126 else:
127 # If port's a service name like "http", don't skip getaddrinfo.
128 try:
129 port = int(port)
130 except (TypeError, ValueError):
131 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400132
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400133 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500134 afs = [socket.AF_INET]
Yury Selivanovd904c232018-06-28 21:59:32 -0400135 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500136 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400137 else:
138 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500139
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 if isinstance(host, bytes):
141 host = host.decode('idna')
142 if '%' in host:
143 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
144 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145 return None
146
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400147 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400149 socket.inet_pton(af, host)
150 # The host has already been resolved.
Yury Selivanovd904c232018-06-28 21:59:32 -0400151 if _HAS_IPv6 and af == socket.AF_INET6:
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +0200152 return af, type, proto, '', (host, port, flowinfo, scopeid)
Yury Selivanovd904c232018-06-28 21:59:32 -0400153 else:
154 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400155 except OSError:
156 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500157
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400158 # "host" is not an IP address.
159 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500160
161
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800162def _interleave_addrinfos(addrinfos, first_address_family_count=1):
163 """Interleave list of addrinfo tuples by family."""
164 # Group addresses by family
165 addrinfos_by_family = collections.OrderedDict()
166 for addr in addrinfos:
167 family = addr[0]
168 if family not in addrinfos_by_family:
169 addrinfos_by_family[family] = []
170 addrinfos_by_family[family].append(addr)
171 addrinfos_lists = list(addrinfos_by_family.values())
172
173 reordered = []
174 if first_address_family_count > 1:
175 reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
176 del addrinfos_lists[0][:first_address_family_count - 1]
177 reordered.extend(
178 a for a in itertools.chain.from_iterable(
179 itertools.zip_longest(*addrinfos_lists)
180 ) if a is not None)
181 return reordered
182
183
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100184def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500185 if not fut.cancelled():
186 exc = fut.exception()
Yury Selivanov431b5402019-05-27 14:45:12 +0200187 if isinstance(exc, (SystemExit, KeyboardInterrupt)):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500188 # Issue #22429: run_forever() already finished, no need to
189 # stop it.
190 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500191 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100192
193
Andrew Svetlov3bc0eba2018-12-03 21:08:13 +0200194if hasattr(socket, 'TCP_NODELAY'):
195 def _set_nodelay(sock):
196 if (sock.family in {socket.AF_INET, socket.AF_INET6} and
197 sock.type == socket.SOCK_STREAM and
198 sock.proto == socket.IPPROTO_TCP):
199 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
200else:
201 def _set_nodelay(sock):
202 pass
203
204
Andrew Svetlov7c684072018-01-27 21:22:47 +0200205class _SendfileFallbackProtocol(protocols.Protocol):
206 def __init__(self, transp):
207 if not isinstance(transp, transports._FlowControlMixin):
208 raise TypeError("transport should be _FlowControlMixin instance")
209 self._transport = transp
210 self._proto = transp.get_protocol()
211 self._should_resume_reading = transp.is_reading()
212 self._should_resume_writing = transp._protocol_paused
213 transp.pause_reading()
214 transp.set_protocol(self)
215 if self._should_resume_writing:
216 self._write_ready_fut = self._transport._loop.create_future()
217 else:
218 self._write_ready_fut = None
219
220 async def drain(self):
221 if self._transport.is_closing():
222 raise ConnectionError("Connection closed by peer")
223 fut = self._write_ready_fut
224 if fut is None:
225 return
226 await fut
227
228 def connection_made(self, transport):
229 raise RuntimeError("Invalid state: "
230 "connection should have been established already.")
231
232 def connection_lost(self, exc):
233 if self._write_ready_fut is not None:
234 # Never happens if peer disconnects after sending the whole content
235 # Thus disconnection is always an exception from user perspective
236 if exc is None:
237 self._write_ready_fut.set_exception(
238 ConnectionError("Connection is closed by peer"))
239 else:
240 self._write_ready_fut.set_exception(exc)
241 self._proto.connection_lost(exc)
242
243 def pause_writing(self):
244 if self._write_ready_fut is not None:
245 return
246 self._write_ready_fut = self._transport._loop.create_future()
247
248 def resume_writing(self):
249 if self._write_ready_fut is None:
250 return
251 self._write_ready_fut.set_result(False)
252 self._write_ready_fut = None
253
254 def data_received(self, data):
255 raise RuntimeError("Invalid state: reading should be paused")
256
257 def eof_received(self):
258 raise RuntimeError("Invalid state: reading should be paused")
259
260 async def restore(self):
261 self._transport.set_protocol(self._proto)
262 if self._should_resume_reading:
263 self._transport.resume_reading()
264 if self._write_ready_fut is not None:
265 # Cancel the future.
266 # Basically it has no effect because protocol is switched back,
267 # no code should wait for it anymore.
268 self._write_ready_fut.cancel()
269 if self._should_resume_writing:
270 self._proto.resume_writing()
271
272
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700273class Server(events.AbstractServer):
274
Yury Selivanovc9070d02018-01-25 18:08:09 -0500275 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
Pablo Galindo77199532021-05-03 16:21:59 +0100276 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200277 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500278 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200279 self._active_count = 0
280 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500281 self._protocol_factory = protocol_factory
282 self._backlog = backlog
283 self._ssl_context = ssl_context
284 self._ssl_handshake_timeout = ssl_handshake_timeout
285 self._serving = False
286 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700287
Victor Stinnere912e652014-07-12 03:11:53 +0200288 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500289 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200290
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200291 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500292 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200293 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700294
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200295 def _detach(self):
296 assert self._active_count > 0
297 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500298 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700299 self._wakeup()
300
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700301 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200302 waiters = self._waiters
303 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700304 for waiter in waiters:
305 if not waiter.done():
306 waiter.set_result(waiter)
307
Yury Selivanovc9070d02018-01-25 18:08:09 -0500308 def _start_serving(self):
309 if self._serving:
310 return
311 self._serving = True
312 for sock in self._sockets:
313 sock.listen(self._backlog)
314 self._loop._start_serving(
315 self._protocol_factory, sock, self._ssl_context,
Pablo Galindo77199532021-05-03 16:21:59 +0100316 self, self._backlog, self._ssl_handshake_timeout)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500317
318 def get_loop(self):
319 return self._loop
320
321 def is_serving(self):
322 return self._serving
323
324 @property
325 def sockets(self):
326 if self._sockets is None:
Yury Selivanov8cd51652019-05-27 15:57:20 +0200327 return ()
328 return tuple(trsock.TransportSocket(s) for s in self._sockets)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500329
330 def close(self):
331 sockets = self._sockets
332 if sockets is None:
333 return
334 self._sockets = None
335
336 for sock in sockets:
337 self._loop._stop_serving(sock)
338
339 self._serving = False
340
341 if (self._serving_forever_fut is not None and
342 not self._serving_forever_fut.done()):
343 self._serving_forever_fut.cancel()
344 self._serving_forever_fut = None
345
346 if self._active_count == 0:
347 self._wakeup()
348
349 async def start_serving(self):
350 self._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -0400351 # Skip one loop iteration so that all 'loop.add_reader'
352 # go through.
Yurii Karabase4fe3032020-11-28 10:21:17 +0200353 await tasks.sleep(0)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500354
355 async def serve_forever(self):
356 if self._serving_forever_fut is not None:
357 raise RuntimeError(
358 f'server {self!r} is already being awaited on serve_forever()')
359 if self._sockets is None:
360 raise RuntimeError(f'server {self!r} is closed')
361
362 self._start_serving()
363 self._serving_forever_fut = self._loop.create_future()
364
365 try:
366 await self._serving_forever_fut
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700367 except exceptions.CancelledError:
Yury Selivanovc9070d02018-01-25 18:08:09 -0500368 try:
369 self.close()
370 await self.wait_closed()
371 finally:
372 raise
373 finally:
374 self._serving_forever_fut = None
375
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200376 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500377 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700378 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400379 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200380 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200381 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700382
383
384class BaseEventLoop(events.AbstractEventLoop):
385
386 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400387 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200388 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800389 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700390 self._ready = collections.deque()
391 self._scheduled = []
392 self._default_executor = None
393 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100394 # Identifier of the thread running the event loop, or None if the
395 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100396 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100397 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500398 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800399 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200400 # In debug mode, if the execution of a callback or a step of a task
401 # exceed this duration in seconds, the slow callback/task is logged.
402 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100403 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400404 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800405 self._coroutine_origin_tracking_enabled = False
406 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700407
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500408 # A weak set of all asynchronous generators that are
409 # being iterated by the loop.
410 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700411 # Set to True when `loop.shutdown_asyncgens` is called.
412 self._asyncgens_shutdown_called = False
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400413 # Set to True when `loop.shutdown_default_executor` is called.
414 self._executor_shutdown_called = False
Yury Selivanoveb636452016-09-08 22:01:51 -0700415
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200416 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500417 return (
418 f'<{self.__class__.__name__} running={self.is_running()} '
419 f'closed={self.is_closed()} debug={self.get_debug()}>'
420 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200421
Yury Selivanov7661db62016-05-16 15:38:39 -0400422 def create_future(self):
423 """Create a Future object attached to the loop."""
424 return futures.Future(loop=self)
425
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300426 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200427 """Schedule a coroutine object.
428
Victor Stinneracdb7822014-07-14 18:33:40 +0200429 Return a task object.
430 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100431 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400432 if self._task_factory is None:
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300433 task = tasks.Task(coro, loop=self, name=name)
Yury Selivanov740169c2015-05-11 14:23:38 -0400434 if task._source_traceback:
435 del task._source_traceback[-1]
436 else:
437 task = self._task_factory(self, coro)
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300438 tasks._set_task_name(task, name)
439
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200440 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200441
Yury Selivanov740169c2015-05-11 14:23:38 -0400442 def set_task_factory(self, factory):
443 """Set a task factory that will be used by loop.create_task().
444
445 If factory is None the default task factory will be set.
446
447 If factory is a callable, it should have a signature matching
448 '(loop, coro)', where 'loop' will be a reference to the active
449 event loop, 'coro' will be a coroutine object. The callable
450 must return a Future.
451 """
452 if factory is not None and not callable(factory):
453 raise TypeError('task factory must be a callable or None')
454 self._task_factory = factory
455
456 def get_task_factory(self):
457 """Return a task factory, or None if the default one is in use."""
458 return self._task_factory
459
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700460 def _make_socket_transport(self, sock, protocol, waiter=None, *,
461 extra=None, server=None):
462 """Create socket transport."""
463 raise NotImplementedError
464
Neil Aspinallf7686c12017-12-19 19:45:42 +0000465 def _make_ssl_transport(
466 self, rawsock, protocol, sslcontext, waiter=None,
467 *, server_side=False, server_hostname=None,
468 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500469 ssl_handshake_timeout=None,
470 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700471 """Create SSL transport."""
472 raise NotImplementedError
473
474 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200475 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476 """Create datagram transport."""
477 raise NotImplementedError
478
479 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
480 extra=None):
481 """Create read pipe transport."""
482 raise NotImplementedError
483
484 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
485 extra=None):
486 """Create write pipe transport."""
487 raise NotImplementedError
488
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200489 async def _make_subprocess_transport(self, protocol, args, shell,
490 stdin, stdout, stderr, bufsize,
491 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700492 """Create subprocess transport."""
493 raise NotImplementedError
494
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700495 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200496 """Write a byte to self-pipe, to wake up the event loop.
497
498 This may be called from a different thread.
499
500 The subclass is responsible for implementing the self-pipe.
501 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700502 raise NotImplementedError
503
504 def _process_events(self, event_list):
505 """Process selector events."""
506 raise NotImplementedError
507
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200508 def _check_closed(self):
509 if self._closed:
510 raise RuntimeError('Event loop is closed')
511
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400512 def _check_default_executor(self):
513 if self._executor_shutdown_called:
514 raise RuntimeError('Executor shutdown has been called')
515
Yury Selivanoveb636452016-09-08 22:01:51 -0700516 def _asyncgen_finalizer_hook(self, agen):
517 self._asyncgens.discard(agen)
518 if not self.is_closed():
twisteroid ambassadorc880ffe2018-10-09 23:30:21 +0800519 self.call_soon_threadsafe(self.create_task, agen.aclose())
Yury Selivanoveb636452016-09-08 22:01:51 -0700520
521 def _asyncgen_firstiter_hook(self, agen):
522 if self._asyncgens_shutdown_called:
523 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500524 f"asynchronous generator {agen!r} was scheduled after "
525 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700526 ResourceWarning, source=self)
527
528 self._asyncgens.add(agen)
529
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200530 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700531 """Shutdown all active asynchronous generators."""
532 self._asyncgens_shutdown_called = True
533
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500534 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400535 # If Python version is <3.6 or we don't have any asynchronous
536 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700537 return
538
539 closing_agens = list(self._asyncgens)
540 self._asyncgens.clear()
541
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200542 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700543 *[ag.aclose() for ag in closing_agens],
Yurii Karabase4fe3032020-11-28 10:21:17 +0200544 return_exceptions=True)
Yury Selivanoveb636452016-09-08 22:01:51 -0700545
Yury Selivanoveb636452016-09-08 22:01:51 -0700546 for result, agen in zip(results, closing_agens):
547 if isinstance(result, Exception):
548 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500549 'message': f'an error occurred during closing of '
550 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700551 'exception': result,
552 'asyncgen': agen
553 })
554
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400555 async def shutdown_default_executor(self):
556 """Schedule the shutdown of the default executor."""
557 self._executor_shutdown_called = True
558 if self._default_executor is None:
559 return
560 future = self.create_future()
561 thread = threading.Thread(target=self._do_shutdown, args=(future,))
562 thread.start()
563 try:
564 await future
565 finally:
566 thread.join()
567
568 def _do_shutdown(self, future):
569 try:
570 self._default_executor.shutdown(wait=True)
571 self.call_soon_threadsafe(future.set_result, None)
572 except Exception as ex:
573 self.call_soon_threadsafe(future.set_exception, ex)
574
Andrew Svetlov10ac0cd2020-01-07 15:23:01 +0200575 def _check_running(self):
Victor Stinner956de692014-12-26 21:07:52 +0100576 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400577 raise RuntimeError('This event loop is already running')
578 if events._get_running_loop() is not None:
579 raise RuntimeError(
580 'Cannot run the event loop while another loop is running')
Andrew Svetlov3a5de512020-01-04 11:10:14 +0200581
582 def run_forever(self):
583 """Run until stop() is called."""
584 self._check_closed()
Andrew Svetlov10ac0cd2020-01-07 15:23:01 +0200585 self._check_running()
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800586 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100587 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500588
589 old_agen_hooks = sys.get_asyncgen_hooks()
590 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
591 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400593 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700594 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800595 self._run_once()
596 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700597 break
598 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800599 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100600 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400601 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800602 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500603 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700604
605 def run_until_complete(self, future):
606 """Run until the Future is done.
607
608 If the argument is a coroutine, it is wrapped in a Task.
609
Victor Stinneracdb7822014-07-14 18:33:40 +0200610 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700611 with the same coroutine twice -- it would wrap it in two
612 different Tasks and that can't be good.
613
614 Return the Future's result, or raise its exception.
615 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200616 self._check_closed()
Andrew Svetlov10ac0cd2020-01-07 15:23:01 +0200617 self._check_running()
Victor Stinner98b63912014-06-30 14:51:04 +0200618
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700619 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400620 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200621 if new_task:
622 # An exception is raised if the future didn't complete, so there
623 # is no need to log the "destroy pending task" message
624 future._log_destroy_pending = False
625
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100626 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200627 try:
628 self.run_forever()
629 except:
630 if new_task and future.done() and not future.cancelled():
631 # The coroutine raised a BaseException. Consume the exception
632 # to not log a warning, the caller doesn't have access to the
633 # local task.
634 future.exception()
635 raise
jimmylai21b3e042017-05-22 22:32:46 -0700636 finally:
637 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700638 if not future.done():
639 raise RuntimeError('Event loop stopped before Future completed.')
640
641 return future.result()
642
643 def stop(self):
644 """Stop running the event loop.
645
Guido van Rossum41f69f42015-11-19 13:28:47 -0800646 Every callback already scheduled will still run. This simply informs
647 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700648 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800649 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700650
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200651 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700652 """Close the event loop.
653
654 This clears the queues and shuts down the executor,
655 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200656
657 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700658 """
Victor Stinner956de692014-12-26 21:07:52 +0100659 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200660 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200661 if self._closed:
662 return
Victor Stinnere912e652014-07-12 03:11:53 +0200663 if self._debug:
664 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400665 self._closed = True
666 self._ready.clear()
667 self._scheduled.clear()
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400668 self._executor_shutdown_called = True
Yury Selivanove8944cb2015-05-12 11:43:04 -0400669 executor = self._default_executor
670 if executor is not None:
671 self._default_executor = None
Łukasz Langa7f9a2ae2019-06-04 13:03:20 +0200672 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200673
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200674 def is_closed(self):
675 """Returns True if the event loop was closed."""
676 return self._closed
677
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100678 def __del__(self, _warn=warnings.warn):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900679 if not self.is_closed():
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100680 _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900681 if not self.is_running():
682 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100683
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700684 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200685 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100686 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700687
688 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200689 """Return the time according to the event loop's clock.
690
691 This is a float expressed in seconds since an epoch, but the
692 epoch, precision, accuracy and drift are unspecified and may
693 differ per event loop.
694 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700695 return time.monotonic()
696
Yury Selivanovf23746a2018-01-22 19:11:18 -0500697 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700698 """Arrange for a callback to be called at a given time.
699
700 Return a Handle: an opaque object with a cancel() method that
701 can be used to cancel the call.
702
703 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200704 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705
706 Each callback will be called exactly once. If two callbacks
707 are scheduled for exactly the same time, it undefined which
708 will be called first.
709
710 Any positional arguments after the callback will be passed to
711 the callback when it is called.
712 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500713 timer = self.call_at(self.time() + delay, callback, *args,
714 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200715 if timer._source_traceback:
716 del timer._source_traceback[-1]
717 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700718
Yury Selivanovf23746a2018-01-22 19:11:18 -0500719 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200720 """Like call_later(), but uses an absolute time.
721
722 Absolute time corresponds to the event loop's time() method.
723 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100724 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100725 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100726 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700727 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500728 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200729 if timer._source_traceback:
730 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700731 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400732 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700733 return timer
734
Yury Selivanovf23746a2018-01-22 19:11:18 -0500735 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700736 """Arrange for a callback to be called as soon as possible.
737
Victor Stinneracdb7822014-07-14 18:33:40 +0200738 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700739 order in which they are registered. Each callback will be
740 called exactly once.
741
742 Any positional arguments after the callback will be passed to
743 the callback when it is called.
744 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700745 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100746 if self._debug:
747 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700748 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500749 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200750 if handle._source_traceback:
751 del handle._source_traceback[-1]
752 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100753
Yury Selivanov491a9122016-11-03 15:09:24 -0700754 def _check_callback(self, callback, method):
755 if (coroutines.iscoroutine(callback) or
756 coroutines.iscoroutinefunction(callback)):
757 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500758 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700759 if not callable(callback):
760 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500761 f'a callable object was expected by {method}(), '
762 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700763
Yury Selivanovf23746a2018-01-22 19:11:18 -0500764 def _call_soon(self, callback, args, context):
765 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200766 if handle._source_traceback:
767 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700768 self._ready.append(handle)
769 return handle
770
Victor Stinner956de692014-12-26 21:07:52 +0100771 def _check_thread(self):
772 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100773
Victor Stinneracdb7822014-07-14 18:33:40 +0200774 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100775 likely behave incorrectly when the assumption is violated.
776
Victor Stinneracdb7822014-07-14 18:33:40 +0200777 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100778 responsible for checking this condition for performance reasons.
779 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100780 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200781 return
Victor Stinner956de692014-12-26 21:07:52 +0100782 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100783 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100784 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200785 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100786 "than the current one")
787
Yury Selivanovf23746a2018-01-22 19:11:18 -0500788 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200789 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700790 self._check_closed()
791 if self._debug:
792 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500793 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200794 if handle._source_traceback:
795 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700796 self._write_to_self()
797 return handle
798
Yury Selivanovbec23722018-01-28 14:09:40 -0500799 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100800 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700801 if self._debug:
802 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700803 if executor is None:
804 executor = self._default_executor
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400805 # Only check when the default executor is being used
806 self._check_default_executor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700807 if executor is None:
Markus Mohrhard374d9982020-02-28 04:01:47 +0800808 executor = concurrent.futures.ThreadPoolExecutor(
809 thread_name_prefix='asyncio'
810 )
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700811 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500812 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500813 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700814
815 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100816 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
817 warnings.warn(
818 'Using the default executor that is not an instance of '
819 'ThreadPoolExecutor is deprecated and will be prohibited '
820 'in Python 3.9',
821 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700822 self._default_executor = executor
823
Victor Stinnere912e652014-07-12 03:11:53 +0200824 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500825 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200826 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500827 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200828 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500829 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200830 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500831 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200832 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500833 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200834 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200835 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200836
837 t0 = self.time()
838 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
839 dt = self.time() - t0
840
Yury Selivanov6370f342017-12-10 18:36:12 -0500841 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200842 if dt >= self.slow_callback_duration:
843 logger.info(msg)
844 else:
845 logger.debug(msg)
846 return addrinfo
847
Yury Selivanov19a44f62017-12-14 20:53:26 -0500848 async def getaddrinfo(self, host, port, *,
849 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400850 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500851 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200852 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500853 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700854
Yury Selivanov19a44f62017-12-14 20:53:26 -0500855 return await self.run_in_executor(
856 None, getaddr_func, host, port, family, type, proto, flags)
857
858 async def getnameinfo(self, sockaddr, flags=0):
859 return await self.run_in_executor(
860 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700861
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200862 async def sock_sendfile(self, sock, file, offset=0, count=None,
863 *, fallback=True):
864 if self._debug and sock.gettimeout() != 0:
865 raise ValueError("the socket must be non-blocking")
866 self._check_sendfile_params(sock, file, offset, count)
867 try:
868 return await self._sock_sendfile_native(sock, file,
869 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700870 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7464e872018-01-19 20:04:29 +0200871 if not fallback:
872 raise
873 return await self._sock_sendfile_fallback(sock, file,
874 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200875
876 async def _sock_sendfile_native(self, sock, file, offset, count):
877 # NB: sendfile syscall is not supported for SSL sockets and
878 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700879 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200880 f"syscall sendfile is not available for socket {sock!r} "
881 "and file {file!r} combination")
882
883 async def _sock_sendfile_fallback(self, sock, file, offset, count):
884 if offset:
885 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400886 blocksize = (
887 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
888 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
889 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200890 buf = bytearray(blocksize)
891 total_sent = 0
892 try:
893 while True:
894 if count:
895 blocksize = min(count - total_sent, blocksize)
896 if blocksize <= 0:
897 break
898 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400899 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200900 if not read:
901 break # EOF
Andrew Svetlovef215232019-06-15 14:05:08 +0300902 await self.sock_sendall(sock, view[:read])
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200903 total_sent += read
904 return total_sent
905 finally:
906 if total_sent > 0 and hasattr(file, 'seek'):
907 file.seek(offset + total_sent)
908
909 def _check_sendfile_params(self, sock, file, offset, count):
910 if 'b' not in getattr(file, 'mode', 'b'):
911 raise ValueError("file should be opened in binary mode")
912 if not sock.type == socket.SOCK_STREAM:
913 raise ValueError("only SOCK_STREAM type sockets are supported")
914 if count is not None:
915 if not isinstance(count, int):
916 raise TypeError(
917 "count must be a positive integer (got {!r})".format(count))
918 if count <= 0:
919 raise ValueError(
920 "count must be a positive integer (got {!r})".format(count))
921 if not isinstance(offset, int):
922 raise TypeError(
923 "offset must be a non-negative integer (got {!r})".format(
924 offset))
925 if offset < 0:
926 raise ValueError(
927 "offset must be a non-negative integer (got {!r})".format(
928 offset))
929
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800930 async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
931 """Create, bind and connect one socket."""
932 my_exceptions = []
933 exceptions.append(my_exceptions)
934 family, type_, proto, _, address = addr_info
935 sock = None
936 try:
937 sock = socket.socket(family=family, type=type_, proto=proto)
938 sock.setblocking(False)
939 if local_addr_infos is not None:
940 for _, _, _, _, laddr in local_addr_infos:
941 try:
942 sock.bind(laddr)
943 break
944 except OSError as exc:
945 msg = (
946 f'error while attempting to bind on '
947 f'address {laddr!r}: '
948 f'{exc.strerror.lower()}'
949 )
950 exc = OSError(exc.errno, msg)
951 my_exceptions.append(exc)
952 else: # all bind attempts failed
953 raise my_exceptions.pop()
954 await self.sock_connect(sock, address)
955 return sock
956 except OSError as exc:
957 my_exceptions.append(exc)
958 if sock is not None:
959 sock.close()
960 raise
961 except:
962 if sock is not None:
963 sock.close()
964 raise
965
Neil Aspinallf7686c12017-12-19 19:45:42 +0000966 async def create_connection(
967 self, protocol_factory, host=None, port=None,
968 *, ssl=None, family=0,
969 proto=0, flags=0, sock=None,
970 local_addr=None, server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800971 ssl_handshake_timeout=None,
972 happy_eyeballs_delay=None, interleave=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200973 """Connect to a TCP server.
974
975 Create a streaming transport connection to a given Internet host and
976 port: socket family AF_INET or socket.AF_INET6 depending on host (or
977 family if specified), socket type SOCK_STREAM. protocol_factory must be
978 a callable returning a protocol instance.
979
980 This method is a coroutine which will try to establish the connection
981 in the background. When successful, the coroutine returns a
982 (transport, protocol) pair.
983 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700984 if server_hostname is not None and not ssl:
985 raise ValueError('server_hostname is only meaningful with ssl')
986
987 if server_hostname is None and ssl:
988 # Use host as default for server_hostname. It is an error
989 # if host is empty or not set, e.g. when an
990 # already-connected socket was passed or when only a port
991 # is given. To avoid this error, you can pass
992 # server_hostname='' -- this will bypass the hostname
993 # check. (This also means that if host is a numeric
994 # IP/IPv6 address, we will attempt to verify that exact
995 # address; this will probably fail, but it is possible to
996 # create a certificate for a specific IP address, so we
997 # don't judge it here.)
998 if not host:
999 raise ValueError('You must set server_hostname '
1000 'when using ssl without a host')
1001 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -07001002
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001003 if ssl_handshake_timeout is not None and not ssl:
1004 raise ValueError(
1005 'ssl_handshake_timeout is only meaningful with ssl')
1006
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001007 if happy_eyeballs_delay is not None and interleave is None:
1008 # If using happy eyeballs, default to interleave addresses by family
1009 interleave = 1
1010
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001011 if host is not None or port is not None:
1012 if sock is not None:
1013 raise ValueError(
1014 'host/port and sock can not be specified at the same time')
1015
Yury Selivanov19a44f62017-12-14 20:53:26 -05001016 infos = await self._ensure_resolved(
1017 (host, port), family=family,
1018 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001019 if not infos:
1020 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -05001021
1022 if local_addr is not None:
1023 laddr_infos = await self._ensure_resolved(
1024 local_addr, family=family,
1025 type=socket.SOCK_STREAM, proto=proto,
1026 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001027 if not laddr_infos:
1028 raise OSError('getaddrinfo() returned empty list')
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001029 else:
1030 laddr_infos = None
1031
1032 if interleave:
1033 infos = _interleave_addrinfos(infos, interleave)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001034
1035 exceptions = []
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001036 if happy_eyeballs_delay is None:
1037 # not using happy eyeballs
1038 for addrinfo in infos:
1039 try:
1040 sock = await self._connect_sock(
1041 exceptions, addrinfo, laddr_infos)
1042 break
1043 except OSError:
1044 continue
1045 else: # using happy eyeballs
1046 sock, _, _ = await staggered.staggered_race(
1047 (functools.partial(self._connect_sock,
1048 exceptions, addrinfo, laddr_infos)
1049 for addrinfo in infos),
1050 happy_eyeballs_delay, loop=self)
1051
1052 if sock is None:
1053 exceptions = [exc for sub in exceptions for exc in sub]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001054 if len(exceptions) == 1:
1055 raise exceptions[0]
1056 else:
1057 # If they all have the same str(), raise one.
1058 model = str(exceptions[0])
1059 if all(str(exc) == model for exc in exceptions):
1060 raise exceptions[0]
1061 # Raise a combined exception so the user can see all
1062 # the various error messages.
1063 raise OSError('Multiple exceptions: {}'.format(
1064 ', '.join(str(exc) for exc in exceptions)))
1065
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001066 else:
1067 if sock is None:
1068 raise ValueError(
1069 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001070 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -05001071 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
1072 # are SOCK_STREAM.
1073 # We support passing AF_UNIX sockets even though we have
1074 # a dedicated API for that: create_unix_connection.
1075 # Disallowing AF_UNIX in this method, breaks backwards
1076 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001077 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001078 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001079
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001080 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001081 sock, protocol_factory, ssl, server_hostname,
Pablo Galindo77199532021-05-03 16:21:59 +01001082 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001083 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +02001084 # Get the socket from the transport because SSL transport closes
1085 # the old socket and creates a new SSL socket
1086 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +02001087 logger.debug("%r connected to %s:%r: (%r, %r)",
1088 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -05001089 return transport, protocol
1090
Neil Aspinallf7686c12017-12-19 19:45:42 +00001091 async def _create_connection_transport(
1092 self, sock, protocol_factory, ssl,
1093 server_hostname, server_side=False,
Pablo Galindo77199532021-05-03 16:21:59 +01001094 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001095
1096 sock.setblocking(False)
1097
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001098 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001099 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001100 if ssl:
1101 sslcontext = None if isinstance(ssl, bool) else ssl
1102 transport = self._make_ssl_transport(
1103 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001104 server_side=server_side, server_hostname=server_hostname,
Pablo Galindo77199532021-05-03 16:21:59 +01001105 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001106 else:
1107 transport = self._make_socket_transport(sock, protocol, waiter)
1108
Victor Stinner29ad0112015-01-15 00:04:21 +01001109 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001110 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001111 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001112 transport.close()
1113 raise
1114
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001115 return transport, protocol
1116
Andrew Svetlov7c684072018-01-27 21:22:47 +02001117 async def sendfile(self, transport, file, offset=0, count=None,
1118 *, fallback=True):
1119 """Send a file to transport.
1120
1121 Return the total number of bytes which were sent.
1122
1123 The method uses high-performance os.sendfile if available.
1124
1125 file must be a regular file object opened in binary mode.
1126
1127 offset tells from where to start reading the file. If specified,
1128 count is the total number of bytes to transmit as opposed to
1129 sending the file until EOF is reached. File position is updated on
1130 return or also in case of error in which case file.tell()
1131 can be used to figure out the number of bytes
1132 which were sent.
1133
1134 fallback set to True makes asyncio to manually read and send
1135 the file when the platform does not support the sendfile syscall
1136 (e.g. Windows or SSL socket on Unix).
1137
1138 Raise SendfileNotAvailableError if the system does not support
1139 sendfile syscall and fallback is False.
1140 """
1141 if transport.is_closing():
1142 raise RuntimeError("Transport is closing")
1143 mode = getattr(transport, '_sendfile_compatible',
1144 constants._SendfileMode.UNSUPPORTED)
1145 if mode is constants._SendfileMode.UNSUPPORTED:
1146 raise RuntimeError(
1147 f"sendfile is not supported for transport {transport!r}")
1148 if mode is constants._SendfileMode.TRY_NATIVE:
1149 try:
1150 return await self._sendfile_native(transport, file,
1151 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001152 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7c684072018-01-27 21:22:47 +02001153 if not fallback:
1154 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001155
1156 if not fallback:
1157 raise RuntimeError(
1158 f"fallback is disabled and native sendfile is not "
1159 f"supported for transport {transport!r}")
1160
Andrew Svetlov7c684072018-01-27 21:22:47 +02001161 return await self._sendfile_fallback(transport, file,
1162 offset, count)
1163
1164 async def _sendfile_native(self, transp, file, offset, count):
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001165 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov7c684072018-01-27 21:22:47 +02001166 "sendfile syscall is not supported")
1167
1168 async def _sendfile_fallback(self, transp, file, offset, count):
1169 if offset:
1170 file.seek(offset)
1171 blocksize = min(count, 16384) if count else 16384
1172 buf = bytearray(blocksize)
1173 total_sent = 0
1174 proto = _SendfileFallbackProtocol(transp)
1175 try:
1176 while True:
1177 if count:
1178 blocksize = min(count - total_sent, blocksize)
1179 if blocksize <= 0:
1180 return total_sent
1181 view = memoryview(buf)[:blocksize]
Andrew Svetlov02372652019-06-15 14:05:35 +03001182 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov7c684072018-01-27 21:22:47 +02001183 if not read:
1184 return total_sent # EOF
1185 await proto.drain()
Andrew Svetlovef215232019-06-15 14:05:08 +03001186 transp.write(view[:read])
Andrew Svetlov7c684072018-01-27 21:22:47 +02001187 total_sent += read
1188 finally:
1189 if total_sent > 0 and hasattr(file, 'seek'):
1190 file.seek(offset + total_sent)
1191 await proto.restore()
1192
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001193 async def start_tls(self, transport, protocol, sslcontext, *,
1194 server_side=False,
1195 server_hostname=None,
Pablo Galindo77199532021-05-03 16:21:59 +01001196 ssl_handshake_timeout=None):
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001197 """Upgrade transport to TLS.
1198
1199 Return a new transport that *protocol* should start using
1200 immediately.
1201 """
1202 if ssl is None:
1203 raise RuntimeError('Python ssl module is not available')
1204
1205 if not isinstance(sslcontext, ssl.SSLContext):
1206 raise TypeError(
1207 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1208 f'got {sslcontext!r}')
1209
1210 if not getattr(transport, '_start_tls_compatible', False):
1211 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001212 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001213
1214 waiter = self.create_future()
1215 ssl_protocol = sslproto.SSLProtocol(
1216 self, protocol, sslcontext, waiter,
1217 server_side, server_hostname,
1218 ssl_handshake_timeout=ssl_handshake_timeout,
1219 call_connection_made=False)
1220
Yury Selivanovf2955872018-05-29 01:00:12 -04001221 # Pause early so that "ssl_protocol.data_received()" doesn't
1222 # have a chance to get called before "ssl_protocol.connection_made()".
1223 transport.pause_reading()
1224
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001225 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001226 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1227 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001228
Yury Selivanov96026432018-06-04 11:32:35 -04001229 try:
1230 await waiter
Yury Selivanov431b5402019-05-27 14:45:12 +02001231 except BaseException:
Yury Selivanov96026432018-06-04 11:32:35 -04001232 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001233 conmade_cb.cancel()
1234 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001235 raise
1236
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001237 return ssl_protocol._app_transport
1238
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001239 async def create_datagram_endpoint(self, protocol_factory,
1240 local_addr=None, remote_addr=None, *,
1241 family=0, proto=0, flags=0,
Kyle Stanleyab513a32019-12-09 09:21:10 -05001242 reuse_address=_unset, reuse_port=None,
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001243 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001244 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001245 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001246 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001247 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001248 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001249 if (local_addr or remote_addr or
1250 family or proto or flags or
Kyle Stanleyab513a32019-12-09 09:21:10 -05001251 reuse_port or allow_broadcast):
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001252 # show the problematic kwargs in exception msg
1253 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1254 family=family, proto=proto, flags=flags,
1255 reuse_address=reuse_address, reuse_port=reuse_port,
1256 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001257 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001258 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001259 f'socket modifier keyword arguments can not be used '
1260 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001261 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001262 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001263 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001264 if not (local_addr or remote_addr):
1265 if family == 0:
1266 raise ValueError('unexpected address family')
1267 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001268 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1269 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001270 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001271 raise TypeError('string is expected')
Quentin Dawans56065d42019-04-09 15:40:59 +02001272
1273 if local_addr and local_addr[0] not in (0, '\x00'):
1274 try:
1275 if stat.S_ISSOCK(os.stat(local_addr).st_mode):
1276 os.remove(local_addr)
1277 except FileNotFoundError:
1278 pass
1279 except OSError as err:
1280 # Directory may have permissions only to create socket.
1281 logger.error('Unable to check or remove stale UNIX '
1282 'socket %r: %r',
1283 local_addr, err)
1284
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001285 addr_pairs_info = (((family, proto),
1286 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001287 else:
1288 # join address by (family, protocol)
Inada Naokif3451702019-02-05 17:04:40 +09001289 addr_infos = {} # Using order preserving dict
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001290 for idx, addr in ((0, local_addr), (1, remote_addr)):
1291 if addr is not None:
1292 assert isinstance(addr, tuple) and len(addr) == 2, (
1293 '2-tuple is expected')
1294
Yury Selivanov19a44f62017-12-14 20:53:26 -05001295 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001296 addr, family=family, type=socket.SOCK_DGRAM,
1297 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001298 if not infos:
1299 raise OSError('getaddrinfo() returned empty list')
1300
1301 for fam, _, pro, _, address in infos:
1302 key = (fam, pro)
1303 if key not in addr_infos:
1304 addr_infos[key] = [None, None]
1305 addr_infos[key][idx] = address
1306
1307 # each addr has to have info for each (family, proto) pair
1308 addr_pairs_info = [
1309 (key, addr_pair) for key, addr_pair in addr_infos.items()
1310 if not ((local_addr and addr_pair[0] is None) or
1311 (remote_addr and addr_pair[1] is None))]
1312
1313 if not addr_pairs_info:
1314 raise ValueError('can not get address information')
1315
1316 exceptions = []
1317
Kyle Stanleyab513a32019-12-09 09:21:10 -05001318 # bpo-37228
1319 if reuse_address is not _unset:
1320 if reuse_address:
1321 raise ValueError("Passing `reuse_address=True` is no "
1322 "longer supported, as the usage of "
1323 "SO_REUSEPORT in UDP poses a significant "
1324 "security concern.")
1325 else:
1326 warnings.warn("The *reuse_address* parameter has been "
1327 "deprecated as of 3.5.10 and is scheduled "
1328 "for removal in 3.11.", DeprecationWarning,
1329 stacklevel=2)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001330
1331 for ((family, proto),
1332 (local_address, remote_address)) in addr_pairs_info:
1333 sock = None
1334 r_addr = None
1335 try:
1336 sock = socket.socket(
1337 family=family, type=socket.SOCK_DGRAM, proto=proto)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001338 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001339 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001340 if allow_broadcast:
1341 sock.setsockopt(
1342 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1343 sock.setblocking(False)
1344
1345 if local_addr:
1346 sock.bind(local_address)
1347 if remote_addr:
Vincent Michel63deaa52019-05-07 19:18:49 +02001348 if not allow_broadcast:
1349 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001350 r_addr = remote_address
1351 except OSError as exc:
1352 if sock is not None:
1353 sock.close()
1354 exceptions.append(exc)
1355 except:
1356 if sock is not None:
1357 sock.close()
1358 raise
1359 else:
1360 break
1361 else:
1362 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001363
1364 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001365 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001366 transport = self._make_datagram_transport(
1367 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001368 if self._debug:
1369 if local_addr:
1370 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1371 "created: (%r, %r)",
1372 local_addr, remote_addr, transport, protocol)
1373 else:
1374 logger.debug("Datagram endpoint remote_addr=%r created: "
1375 "(%r, %r)",
1376 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001377
1378 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001379 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001380 except:
1381 transport.close()
1382 raise
1383
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001384 return transport, protocol
1385
Yury Selivanov19a44f62017-12-14 20:53:26 -05001386 async def _ensure_resolved(self, address, *,
1387 family=0, type=socket.SOCK_STREAM,
1388 proto=0, flags=0, loop):
1389 host, port = address[:2]
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +02001390 info = _ipaddr_info(host, port, family, type, proto, *address[2:])
Yury Selivanov19a44f62017-12-14 20:53:26 -05001391 if info is not None:
1392 # "host" is already a resolved IP.
1393 return [info]
1394 else:
1395 return await loop.getaddrinfo(host, port, family=family, type=type,
1396 proto=proto, flags=flags)
1397
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001398 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001399 infos = await self._ensure_resolved((host, port), family=family,
1400 type=socket.SOCK_STREAM,
1401 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001402 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001403 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001404 return infos
1405
Neil Aspinallf7686c12017-12-19 19:45:42 +00001406 async def create_server(
1407 self, protocol_factory, host=None, port=None,
1408 *,
1409 family=socket.AF_UNSPEC,
1410 flags=socket.AI_PASSIVE,
1411 sock=None,
1412 backlog=100,
1413 ssl=None,
1414 reuse_address=None,
1415 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001416 ssl_handshake_timeout=None,
1417 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001418 """Create a TCP server.
1419
Yury Selivanov6370f342017-12-10 18:36:12 -05001420 The host parameter can be a string, in that case the TCP server is
1421 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001422
1423 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001424 the TCP server is bound to all hosts of the sequence. If a host
1425 appears multiple times (possibly indirectly e.g. when hostnames
1426 resolve to the same IP address), the server is only bound once to that
1427 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001428
Victor Stinneracdb7822014-07-14 18:33:40 +02001429 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001430
1431 This method is a coroutine.
1432 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001433 if isinstance(ssl, bool):
1434 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001435
1436 if ssl_handshake_timeout is not None and ssl is None:
1437 raise ValueError(
1438 'ssl_handshake_timeout is only meaningful with ssl')
1439
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001440 if host is not None or port is not None:
1441 if sock is not None:
1442 raise ValueError(
1443 'host/port and sock can not be specified at the same time')
1444
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001445 if reuse_address is None:
1446 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1447 sockets = []
1448 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001449 hosts = [None]
1450 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001451 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001452 hosts = [host]
1453 else:
1454 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001455
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001456 fs = [self._create_server_getaddrinfo(host, port, family=family,
1457 flags=flags)
1458 for host in hosts]
Yurii Karabase4fe3032020-11-28 10:21:17 +02001459 infos = await tasks.gather(*fs)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001460 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001461
1462 completed = False
1463 try:
1464 for res in infos:
1465 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001466 try:
1467 sock = socket.socket(af, socktype, proto)
1468 except socket.error:
1469 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001470 if self._debug:
1471 logger.warning('create_server() failed to create '
1472 'socket.socket(%r, %r, %r)',
1473 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001474 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001475 sockets.append(sock)
1476 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001477 sock.setsockopt(
1478 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1479 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001480 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001481 # Disable IPv4/IPv6 dual stack support (enabled by
1482 # default on Linux) which makes a single socket
1483 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001484 if (_HAS_IPv6 and
1485 af == socket.AF_INET6 and
1486 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001487 sock.setsockopt(socket.IPPROTO_IPV6,
1488 socket.IPV6_V6ONLY,
1489 True)
1490 try:
1491 sock.bind(sa)
1492 except OSError as err:
1493 raise OSError(err.errno, 'error while attempting '
1494 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001495 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001496 completed = True
1497 finally:
1498 if not completed:
1499 for sock in sockets:
1500 sock.close()
1501 else:
1502 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001503 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001504 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001505 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001506 sockets = [sock]
1507
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001508 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001509 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001510
1511 server = Server(self, sockets, protocol_factory,
Pablo Galindo77199532021-05-03 16:21:59 +01001512 ssl, backlog, ssl_handshake_timeout)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001513 if start_serving:
1514 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001515 # Skip one loop iteration so that all 'loop.add_reader'
1516 # go through.
Yurii Karabase4fe3032020-11-28 10:21:17 +02001517 await tasks.sleep(0)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001518
Victor Stinnere912e652014-07-12 03:11:53 +02001519 if self._debug:
1520 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001521 return server
1522
Neil Aspinallf7686c12017-12-19 19:45:42 +00001523 async def connect_accepted_socket(
1524 self, protocol_factory, sock,
1525 *, ssl=None,
Pablo Galindo77199532021-05-03 16:21:59 +01001526 ssl_handshake_timeout=None):
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001527 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001528 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001529
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001530 if ssl_handshake_timeout is not None and not ssl:
1531 raise ValueError(
1532 'ssl_handshake_timeout is only meaningful with ssl')
1533
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001534 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001535 sock, protocol_factory, ssl, '', server_side=True,
Pablo Galindo77199532021-05-03 16:21:59 +01001536 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001537 if self._debug:
1538 # Get the socket from the transport because SSL transport closes
1539 # the old socket and creates a new SSL socket
1540 sock = transport.get_extra_info('socket')
1541 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1542 return transport, protocol
1543
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001544 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001545 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001546 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001547 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001548
1549 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001550 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001551 except:
1552 transport.close()
1553 raise
1554
Victor Stinneracdb7822014-07-14 18:33:40 +02001555 if self._debug:
1556 logger.debug('Read pipe %r connected: (%r, %r)',
1557 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001558 return transport, protocol
1559
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001560 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001561 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001562 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001563 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001564
1565 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001566 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001567 except:
1568 transport.close()
1569 raise
1570
Victor Stinneracdb7822014-07-14 18:33:40 +02001571 if self._debug:
1572 logger.debug('Write pipe %r connected: (%r, %r)',
1573 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001574 return transport, protocol
1575
Victor Stinneracdb7822014-07-14 18:33:40 +02001576 def _log_subprocess(self, msg, stdin, stdout, stderr):
1577 info = [msg]
1578 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001579 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001580 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001581 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001582 else:
1583 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001584 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001585 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001586 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001587 logger.debug(' '.join(info))
1588
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001589 async def subprocess_shell(self, protocol_factory, cmd, *,
1590 stdin=subprocess.PIPE,
1591 stdout=subprocess.PIPE,
1592 stderr=subprocess.PIPE,
1593 universal_newlines=False,
1594 shell=True, bufsize=0,
sbstpf0d4c642019-05-27 19:51:19 -04001595 encoding=None, errors=None, text=None,
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001596 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001597 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001598 raise ValueError("cmd must be a string")
1599 if universal_newlines:
1600 raise ValueError("universal_newlines must be False")
1601 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001602 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001603 if bufsize != 0:
1604 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001605 if text:
1606 raise ValueError("text must be False")
1607 if encoding is not None:
1608 raise ValueError("encoding must be None")
1609 if errors is not None:
1610 raise ValueError("errors must be None")
1611
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001612 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001613 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001614 if self._debug:
1615 # don't log parameters: they may contain sensitive information
1616 # (password) and may be too long
1617 debug_log = 'run shell command %r' % cmd
1618 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001619 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001620 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001621 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001622 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001623 return transport, protocol
1624
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001625 async def subprocess_exec(self, protocol_factory, program, *args,
1626 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1627 stderr=subprocess.PIPE, universal_newlines=False,
sbstpf0d4c642019-05-27 19:51:19 -04001628 shell=False, bufsize=0,
1629 encoding=None, errors=None, text=None,
1630 **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001631 if universal_newlines:
1632 raise ValueError("universal_newlines must be False")
1633 if shell:
1634 raise ValueError("shell must be False")
1635 if bufsize != 0:
1636 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001637 if text:
1638 raise ValueError("text must be False")
1639 if encoding is not None:
1640 raise ValueError("encoding must be None")
1641 if errors is not None:
1642 raise ValueError("errors must be None")
1643
Victor Stinner20e07432014-02-11 11:44:56 +01001644 popen_args = (program,) + args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001645 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001646 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001647 if self._debug:
1648 # don't log parameters: they may contain sensitive information
1649 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001650 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001651 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001652 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001653 protocol, popen_args, False, stdin, stdout, stderr,
1654 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001655 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001656 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001657 return transport, protocol
1658
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001659 def get_exception_handler(self):
1660 """Return an exception handler, or None if the default one is in use.
1661 """
1662 return self._exception_handler
1663
Yury Selivanov569efa22014-02-18 18:02:19 -05001664 def set_exception_handler(self, handler):
1665 """Set handler as the new event loop exception handler.
1666
1667 If handler is None, the default exception handler will
1668 be set.
1669
1670 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001671 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001672 will be a reference to the active event loop, 'context'
1673 will be a dict object (see `call_exception_handler()`
1674 documentation for details about context).
1675 """
1676 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001677 raise TypeError(f'A callable object or None is expected, '
1678 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001679 self._exception_handler = handler
1680
1681 def default_exception_handler(self, context):
1682 """Default exception handler.
1683
1684 This is called when an exception occurs and no exception
1685 handler is set, and can be called by a custom exception
1686 handler that wants to defer to the default behavior.
1687
Antoine Pitrou921e9432017-11-07 17:23:29 +01001688 This default handler logs the error message and other
1689 context-dependent information. In debug mode, a truncated
1690 stack trace is also appended showing where the given object
1691 (e.g. a handle or future or task) was created, if any.
1692
Victor Stinneracdb7822014-07-14 18:33:40 +02001693 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001694 `call_exception_handler()`.
1695 """
1696 message = context.get('message')
1697 if not message:
1698 message = 'Unhandled exception in event loop'
1699
1700 exception = context.get('exception')
1701 if exception is not None:
1702 exc_info = (type(exception), exception, exception.__traceback__)
1703 else:
1704 exc_info = False
1705
Yury Selivanov6370f342017-12-10 18:36:12 -05001706 if ('source_traceback' not in context and
1707 self._current_handle is not None and
1708 self._current_handle._source_traceback):
1709 context['handle_traceback'] = \
1710 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001711
Yury Selivanov569efa22014-02-18 18:02:19 -05001712 log_lines = [message]
1713 for key in sorted(context):
1714 if key in {'message', 'exception'}:
1715 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001716 value = context[key]
1717 if key == 'source_traceback':
1718 tb = ''.join(traceback.format_list(value))
1719 value = 'Object created at (most recent call last):\n'
1720 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001721 elif key == 'handle_traceback':
1722 tb = ''.join(traceback.format_list(value))
1723 value = 'Handle created at (most recent call last):\n'
1724 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001725 else:
1726 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001727 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001728
1729 logger.error('\n'.join(log_lines), exc_info=exc_info)
1730
1731 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001732 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001733
Victor Stinneracdb7822014-07-14 18:33:40 +02001734 The context argument is a dict containing the following keys:
1735
Yury Selivanov569efa22014-02-18 18:02:19 -05001736 - 'message': Error message;
1737 - 'exception' (optional): Exception object;
1738 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001739 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001740 - 'handle' (optional): Handle instance;
1741 - 'protocol' (optional): Protocol instance;
1742 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001743 - 'socket' (optional): Socket instance;
1744 - 'asyncgen' (optional): Asynchronous generator that caused
1745 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001746
Victor Stinneracdb7822014-07-14 18:33:40 +02001747 New keys maybe introduced in the future.
1748
1749 Note: do not overload this method in an event loop subclass.
1750 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001751 `set_exception_handler()` method.
1752 """
1753 if self._exception_handler is None:
1754 try:
1755 self.default_exception_handler(context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001756 except (SystemExit, KeyboardInterrupt):
1757 raise
1758 except BaseException:
Yury Selivanov569efa22014-02-18 18:02:19 -05001759 # Second protection layer for unexpected errors
1760 # in the default implementation, as well as for subclassed
1761 # event loops with overloaded "default_exception_handler".
1762 logger.error('Exception in default exception handler',
1763 exc_info=True)
1764 else:
1765 try:
1766 self._exception_handler(self, context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001767 except (SystemExit, KeyboardInterrupt):
1768 raise
1769 except BaseException as exc:
Yury Selivanov569efa22014-02-18 18:02:19 -05001770 # Exception in the user set custom exception handler.
1771 try:
1772 # Let's try default handler.
1773 self.default_exception_handler({
1774 'message': 'Unhandled error in exception handler',
1775 'exception': exc,
1776 'context': context,
1777 })
Yury Selivanov431b5402019-05-27 14:45:12 +02001778 except (SystemExit, KeyboardInterrupt):
1779 raise
1780 except BaseException:
Victor Stinneracdb7822014-07-14 18:33:40 +02001781 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001782 # overloaded.
1783 logger.error('Exception in default exception handler '
1784 'while handling an unexpected error '
1785 'in custom exception handler',
1786 exc_info=True)
1787
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001788 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001789 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001790 assert isinstance(handle, events.Handle), 'A Handle is required here'
1791 if handle._cancelled:
1792 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001793 assert not isinstance(handle, events.TimerHandle)
1794 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001795
1796 def _add_callback_signalsafe(self, handle):
1797 """Like _add_callback() but called from a signal handler."""
1798 self._add_callback(handle)
1799 self._write_to_self()
1800
Yury Selivanov592ada92014-09-25 12:07:56 -04001801 def _timer_handle_cancelled(self, handle):
1802 """Notification that a TimerHandle has been cancelled."""
1803 if handle._scheduled:
1804 self._timer_cancelled_count += 1
1805
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001806 def _run_once(self):
1807 """Run one full iteration of the event loop.
1808
1809 This calls all currently ready callbacks, polls for I/O,
1810 schedules the resulting callbacks, and finally schedules
1811 'call_later' callbacks.
1812 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001813
Yury Selivanov592ada92014-09-25 12:07:56 -04001814 sched_count = len(self._scheduled)
1815 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1816 self._timer_cancelled_count / sched_count >
1817 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001818 # Remove delayed calls that were cancelled if their number
1819 # is too high
1820 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001821 for handle in self._scheduled:
1822 if handle._cancelled:
1823 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001824 else:
1825 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001826
Victor Stinner68da8fc2014-09-30 18:08:36 +02001827 heapq.heapify(new_scheduled)
1828 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001829 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001830 else:
1831 # Remove delayed calls that were cancelled from head of queue.
1832 while self._scheduled and self._scheduled[0]._cancelled:
1833 self._timer_cancelled_count -= 1
1834 handle = heapq.heappop(self._scheduled)
1835 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001836
1837 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001838 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001839 timeout = 0
1840 elif self._scheduled:
1841 # Compute the desired timeout.
1842 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001843 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001844
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001845 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001846 self._process_events(event_list)
1847
1848 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001849 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001850 while self._scheduled:
1851 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001852 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001853 break
1854 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001855 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001856 self._ready.append(handle)
1857
1858 # This is the only place where callbacks are actually *called*.
1859 # All other places just add them to ready.
1860 # Note: We run all currently scheduled callbacks, but not any
1861 # callbacks scheduled by callbacks run this time around --
1862 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001863 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001864 ntodo = len(self._ready)
1865 for i in range(ntodo):
1866 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001867 if handle._cancelled:
1868 continue
1869 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001870 try:
1871 self._current_handle = handle
1872 t0 = self.time()
1873 handle._run()
1874 dt = self.time() - t0
1875 if dt >= self.slow_callback_duration:
1876 logger.warning('Executing %s took %.3f seconds',
1877 _format_handle(handle), dt)
1878 finally:
1879 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001880 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001881 handle._run()
1882 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001883
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001884 def _set_coroutine_origin_tracking(self, enabled):
1885 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001886 return
1887
Yury Selivanove8944cb2015-05-12 11:43:04 -04001888 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001889 self._coroutine_origin_tracking_saved_depth = (
1890 sys.get_coroutine_origin_tracking_depth())
1891 sys.set_coroutine_origin_tracking_depth(
1892 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001893 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001894 sys.set_coroutine_origin_tracking_depth(
1895 self._coroutine_origin_tracking_saved_depth)
1896
1897 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001898
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001899 def get_debug(self):
1900 return self._debug
1901
1902 def set_debug(self, enabled):
1903 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001904
Yury Selivanove8944cb2015-05-12 11:43:04 -04001905 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001906 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)