blob: e53ca738034635c66bd86fca11fd1815078084e4 [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,
276 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,
316 self, self._backlog, self._ssl_handshake_timeout)
317
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.
353 await tasks.sleep(0, loop=self._loop)
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],
544 return_exceptions=True,
545 loop=self)
546
Yury Selivanoveb636452016-09-08 22:01:51 -0700547 for result, agen in zip(results, closing_agens):
548 if isinstance(result, Exception):
549 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500550 'message': f'an error occurred during closing of '
551 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700552 'exception': result,
553 'asyncgen': agen
554 })
555
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400556 async def shutdown_default_executor(self):
557 """Schedule the shutdown of the default executor."""
558 self._executor_shutdown_called = True
559 if self._default_executor is None:
560 return
561 future = self.create_future()
562 thread = threading.Thread(target=self._do_shutdown, args=(future,))
563 thread.start()
564 try:
565 await future
566 finally:
567 thread.join()
568
569 def _do_shutdown(self, future):
570 try:
571 self._default_executor.shutdown(wait=True)
572 self.call_soon_threadsafe(future.set_result, None)
573 except Exception as ex:
574 self.call_soon_threadsafe(future.set_exception, ex)
575
Andrew Svetlov3a5de512020-01-04 11:10:14 +0200576 def _check_runnung(self):
Victor Stinner956de692014-12-26 21:07:52 +0100577 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400578 raise RuntimeError('This event loop is already running')
579 if events._get_running_loop() is not None:
580 raise RuntimeError(
581 'Cannot run the event loop while another loop is running')
Andrew Svetlov3a5de512020-01-04 11:10:14 +0200582
583 def run_forever(self):
584 """Run until stop() is called."""
585 self._check_closed()
586 self._check_runnung()
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800587 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100588 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500589
590 old_agen_hooks = sys.get_asyncgen_hooks()
591 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
592 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700593 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400594 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700595 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800596 self._run_once()
597 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 break
599 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800600 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100601 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400602 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800603 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500604 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605
606 def run_until_complete(self, future):
607 """Run until the Future is done.
608
609 If the argument is a coroutine, it is wrapped in a Task.
610
Victor Stinneracdb7822014-07-14 18:33:40 +0200611 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700612 with the same coroutine twice -- it would wrap it in two
613 different Tasks and that can't be good.
614
615 Return the Future's result, or raise its exception.
616 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200617 self._check_closed()
Andrew Svetlov3a5de512020-01-04 11:10:14 +0200618 self._check_runnung()
Victor Stinner98b63912014-06-30 14:51:04 +0200619
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700620 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400621 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200622 if new_task:
623 # An exception is raised if the future didn't complete, so there
624 # is no need to log the "destroy pending task" message
625 future._log_destroy_pending = False
626
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100627 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200628 try:
629 self.run_forever()
630 except:
631 if new_task and future.done() and not future.cancelled():
632 # The coroutine raised a BaseException. Consume the exception
633 # to not log a warning, the caller doesn't have access to the
634 # local task.
635 future.exception()
636 raise
jimmylai21b3e042017-05-22 22:32:46 -0700637 finally:
638 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700639 if not future.done():
640 raise RuntimeError('Event loop stopped before Future completed.')
641
642 return future.result()
643
644 def stop(self):
645 """Stop running the event loop.
646
Guido van Rossum41f69f42015-11-19 13:28:47 -0800647 Every callback already scheduled will still run. This simply informs
648 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700649 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800650 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700651
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200652 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700653 """Close the event loop.
654
655 This clears the queues and shuts down the executor,
656 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200657
658 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700659 """
Victor Stinner956de692014-12-26 21:07:52 +0100660 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200661 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200662 if self._closed:
663 return
Victor Stinnere912e652014-07-12 03:11:53 +0200664 if self._debug:
665 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400666 self._closed = True
667 self._ready.clear()
668 self._scheduled.clear()
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400669 self._executor_shutdown_called = True
Yury Selivanove8944cb2015-05-12 11:43:04 -0400670 executor = self._default_executor
671 if executor is not None:
672 self._default_executor = None
Łukasz Langa7f9a2ae2019-06-04 13:03:20 +0200673 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200674
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200675 def is_closed(self):
676 """Returns True if the event loop was closed."""
677 return self._closed
678
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100679 def __del__(self, _warn=warnings.warn):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900680 if not self.is_closed():
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100681 _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900682 if not self.is_running():
683 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100684
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700685 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200686 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100687 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700688
689 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200690 """Return the time according to the event loop's clock.
691
692 This is a float expressed in seconds since an epoch, but the
693 epoch, precision, accuracy and drift are unspecified and may
694 differ per event loop.
695 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700696 return time.monotonic()
697
Yury Selivanovf23746a2018-01-22 19:11:18 -0500698 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700699 """Arrange for a callback to be called at a given time.
700
701 Return a Handle: an opaque object with a cancel() method that
702 can be used to cancel the call.
703
704 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200705 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700706
707 Each callback will be called exactly once. If two callbacks
708 are scheduled for exactly the same time, it undefined which
709 will be called first.
710
711 Any positional arguments after the callback will be passed to
712 the callback when it is called.
713 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500714 timer = self.call_at(self.time() + delay, callback, *args,
715 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200716 if timer._source_traceback:
717 del timer._source_traceback[-1]
718 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700719
Yury Selivanovf23746a2018-01-22 19:11:18 -0500720 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200721 """Like call_later(), but uses an absolute time.
722
723 Absolute time corresponds to the event loop's time() method.
724 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100725 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100726 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100727 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700728 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500729 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200730 if timer._source_traceback:
731 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700732 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400733 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 return timer
735
Yury Selivanovf23746a2018-01-22 19:11:18 -0500736 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700737 """Arrange for a callback to be called as soon as possible.
738
Victor Stinneracdb7822014-07-14 18:33:40 +0200739 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700740 order in which they are registered. Each callback will be
741 called exactly once.
742
743 Any positional arguments after the callback will be passed to
744 the callback when it is called.
745 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700746 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100747 if self._debug:
748 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700749 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500750 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200751 if handle._source_traceback:
752 del handle._source_traceback[-1]
753 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100754
Yury Selivanov491a9122016-11-03 15:09:24 -0700755 def _check_callback(self, callback, method):
756 if (coroutines.iscoroutine(callback) or
757 coroutines.iscoroutinefunction(callback)):
758 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500759 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700760 if not callable(callback):
761 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500762 f'a callable object was expected by {method}(), '
763 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700764
Yury Selivanovf23746a2018-01-22 19:11:18 -0500765 def _call_soon(self, callback, args, context):
766 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200767 if handle._source_traceback:
768 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700769 self._ready.append(handle)
770 return handle
771
Victor Stinner956de692014-12-26 21:07:52 +0100772 def _check_thread(self):
773 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100774
Victor Stinneracdb7822014-07-14 18:33:40 +0200775 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100776 likely behave incorrectly when the assumption is violated.
777
Victor Stinneracdb7822014-07-14 18:33:40 +0200778 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100779 responsible for checking this condition for performance reasons.
780 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100781 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200782 return
Victor Stinner956de692014-12-26 21:07:52 +0100783 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100784 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100785 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200786 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100787 "than the current one")
788
Yury Selivanovf23746a2018-01-22 19:11:18 -0500789 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200790 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700791 self._check_closed()
792 if self._debug:
793 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500794 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200795 if handle._source_traceback:
796 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700797 self._write_to_self()
798 return handle
799
Yury Selivanovbec23722018-01-28 14:09:40 -0500800 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100801 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700802 if self._debug:
803 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700804 if executor is None:
805 executor = self._default_executor
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400806 # Only check when the default executor is being used
807 self._check_default_executor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700808 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400809 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700810 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500811 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500812 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700813
814 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100815 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
816 warnings.warn(
817 'Using the default executor that is not an instance of '
818 'ThreadPoolExecutor is deprecated and will be prohibited '
819 'in Python 3.9',
820 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700821 self._default_executor = executor
822
Victor Stinnere912e652014-07-12 03:11:53 +0200823 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500824 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200825 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500826 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200827 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500828 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200829 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500830 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200831 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500832 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200833 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200834 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200835
836 t0 = self.time()
837 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
838 dt = self.time() - t0
839
Yury Selivanov6370f342017-12-10 18:36:12 -0500840 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200841 if dt >= self.slow_callback_duration:
842 logger.info(msg)
843 else:
844 logger.debug(msg)
845 return addrinfo
846
Yury Selivanov19a44f62017-12-14 20:53:26 -0500847 async def getaddrinfo(self, host, port, *,
848 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400849 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500850 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200851 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500852 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700853
Yury Selivanov19a44f62017-12-14 20:53:26 -0500854 return await self.run_in_executor(
855 None, getaddr_func, host, port, family, type, proto, flags)
856
857 async def getnameinfo(self, sockaddr, flags=0):
858 return await self.run_in_executor(
859 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700860
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200861 async def sock_sendfile(self, sock, file, offset=0, count=None,
862 *, fallback=True):
863 if self._debug and sock.gettimeout() != 0:
864 raise ValueError("the socket must be non-blocking")
865 self._check_sendfile_params(sock, file, offset, count)
866 try:
867 return await self._sock_sendfile_native(sock, file,
868 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700869 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7464e872018-01-19 20:04:29 +0200870 if not fallback:
871 raise
872 return await self._sock_sendfile_fallback(sock, file,
873 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200874
875 async def _sock_sendfile_native(self, sock, file, offset, count):
876 # NB: sendfile syscall is not supported for SSL sockets and
877 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700878 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200879 f"syscall sendfile is not available for socket {sock!r} "
880 "and file {file!r} combination")
881
882 async def _sock_sendfile_fallback(self, sock, file, offset, count):
883 if offset:
884 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400885 blocksize = (
886 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
887 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
888 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200889 buf = bytearray(blocksize)
890 total_sent = 0
891 try:
892 while True:
893 if count:
894 blocksize = min(count - total_sent, blocksize)
895 if blocksize <= 0:
896 break
897 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400898 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200899 if not read:
900 break # EOF
Andrew Svetlovef215232019-06-15 14:05:08 +0300901 await self.sock_sendall(sock, view[:read])
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200902 total_sent += read
903 return total_sent
904 finally:
905 if total_sent > 0 and hasattr(file, 'seek'):
906 file.seek(offset + total_sent)
907
908 def _check_sendfile_params(self, sock, file, offset, count):
909 if 'b' not in getattr(file, 'mode', 'b'):
910 raise ValueError("file should be opened in binary mode")
911 if not sock.type == socket.SOCK_STREAM:
912 raise ValueError("only SOCK_STREAM type sockets are supported")
913 if count is not None:
914 if not isinstance(count, int):
915 raise TypeError(
916 "count must be a positive integer (got {!r})".format(count))
917 if count <= 0:
918 raise ValueError(
919 "count must be a positive integer (got {!r})".format(count))
920 if not isinstance(offset, int):
921 raise TypeError(
922 "offset must be a non-negative integer (got {!r})".format(
923 offset))
924 if offset < 0:
925 raise ValueError(
926 "offset must be a non-negative integer (got {!r})".format(
927 offset))
928
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800929 async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
930 """Create, bind and connect one socket."""
931 my_exceptions = []
932 exceptions.append(my_exceptions)
933 family, type_, proto, _, address = addr_info
934 sock = None
935 try:
936 sock = socket.socket(family=family, type=type_, proto=proto)
937 sock.setblocking(False)
938 if local_addr_infos is not None:
939 for _, _, _, _, laddr in local_addr_infos:
940 try:
941 sock.bind(laddr)
942 break
943 except OSError as exc:
944 msg = (
945 f'error while attempting to bind on '
946 f'address {laddr!r}: '
947 f'{exc.strerror.lower()}'
948 )
949 exc = OSError(exc.errno, msg)
950 my_exceptions.append(exc)
951 else: # all bind attempts failed
952 raise my_exceptions.pop()
953 await self.sock_connect(sock, address)
954 return sock
955 except OSError as exc:
956 my_exceptions.append(exc)
957 if sock is not None:
958 sock.close()
959 raise
960 except:
961 if sock is not None:
962 sock.close()
963 raise
964
Neil Aspinallf7686c12017-12-19 19:45:42 +0000965 async def create_connection(
966 self, protocol_factory, host=None, port=None,
967 *, ssl=None, family=0,
968 proto=0, flags=0, sock=None,
969 local_addr=None, server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800970 ssl_handshake_timeout=None,
971 happy_eyeballs_delay=None, interleave=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200972 """Connect to a TCP server.
973
974 Create a streaming transport connection to a given Internet host and
975 port: socket family AF_INET or socket.AF_INET6 depending on host (or
976 family if specified), socket type SOCK_STREAM. protocol_factory must be
977 a callable returning a protocol instance.
978
979 This method is a coroutine which will try to establish the connection
980 in the background. When successful, the coroutine returns a
981 (transport, protocol) pair.
982 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700983 if server_hostname is not None and not ssl:
984 raise ValueError('server_hostname is only meaningful with ssl')
985
986 if server_hostname is None and ssl:
987 # Use host as default for server_hostname. It is an error
988 # if host is empty or not set, e.g. when an
989 # already-connected socket was passed or when only a port
990 # is given. To avoid this error, you can pass
991 # server_hostname='' -- this will bypass the hostname
992 # check. (This also means that if host is a numeric
993 # IP/IPv6 address, we will attempt to verify that exact
994 # address; this will probably fail, but it is possible to
995 # create a certificate for a specific IP address, so we
996 # don't judge it here.)
997 if not host:
998 raise ValueError('You must set server_hostname '
999 'when using ssl without a host')
1000 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -07001001
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001002 if ssl_handshake_timeout is not None and not ssl:
1003 raise ValueError(
1004 'ssl_handshake_timeout is only meaningful with ssl')
1005
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001006 if happy_eyeballs_delay is not None and interleave is None:
1007 # If using happy eyeballs, default to interleave addresses by family
1008 interleave = 1
1009
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001010 if host is not None or port is not None:
1011 if sock is not None:
1012 raise ValueError(
1013 'host/port and sock can not be specified at the same time')
1014
Yury Selivanov19a44f62017-12-14 20:53:26 -05001015 infos = await self._ensure_resolved(
1016 (host, port), family=family,
1017 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001018 if not infos:
1019 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -05001020
1021 if local_addr is not None:
1022 laddr_infos = await self._ensure_resolved(
1023 local_addr, family=family,
1024 type=socket.SOCK_STREAM, proto=proto,
1025 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001026 if not laddr_infos:
1027 raise OSError('getaddrinfo() returned empty list')
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001028 else:
1029 laddr_infos = None
1030
1031 if interleave:
1032 infos = _interleave_addrinfos(infos, interleave)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001033
1034 exceptions = []
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001035 if happy_eyeballs_delay is None:
1036 # not using happy eyeballs
1037 for addrinfo in infos:
1038 try:
1039 sock = await self._connect_sock(
1040 exceptions, addrinfo, laddr_infos)
1041 break
1042 except OSError:
1043 continue
1044 else: # using happy eyeballs
1045 sock, _, _ = await staggered.staggered_race(
1046 (functools.partial(self._connect_sock,
1047 exceptions, addrinfo, laddr_infos)
1048 for addrinfo in infos),
1049 happy_eyeballs_delay, loop=self)
1050
1051 if sock is None:
1052 exceptions = [exc for sub in exceptions for exc in sub]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001053 if len(exceptions) == 1:
1054 raise exceptions[0]
1055 else:
1056 # If they all have the same str(), raise one.
1057 model = str(exceptions[0])
1058 if all(str(exc) == model for exc in exceptions):
1059 raise exceptions[0]
1060 # Raise a combined exception so the user can see all
1061 # the various error messages.
1062 raise OSError('Multiple exceptions: {}'.format(
1063 ', '.join(str(exc) for exc in exceptions)))
1064
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001065 else:
1066 if sock is None:
1067 raise ValueError(
1068 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001069 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -05001070 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
1071 # are SOCK_STREAM.
1072 # We support passing AF_UNIX sockets even though we have
1073 # a dedicated API for that: create_unix_connection.
1074 # Disallowing AF_UNIX in this method, breaks backwards
1075 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001076 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001077 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001079 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001080 sock, protocol_factory, ssl, server_hostname,
1081 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001082 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +02001083 # Get the socket from the transport because SSL transport closes
1084 # the old socket and creates a new SSL socket
1085 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +02001086 logger.debug("%r connected to %s:%r: (%r, %r)",
1087 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -05001088 return transport, protocol
1089
Neil Aspinallf7686c12017-12-19 19:45:42 +00001090 async def _create_connection_transport(
1091 self, sock, protocol_factory, ssl,
1092 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001093 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001094
1095 sock.setblocking(False)
1096
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001097 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001098 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001099 if ssl:
1100 sslcontext = None if isinstance(ssl, bool) else ssl
1101 transport = self._make_ssl_transport(
1102 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001103 server_side=server_side, server_hostname=server_hostname,
1104 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001105 else:
1106 transport = self._make_socket_transport(sock, protocol, waiter)
1107
Victor Stinner29ad0112015-01-15 00:04:21 +01001108 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001109 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001110 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001111 transport.close()
1112 raise
1113
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001114 return transport, protocol
1115
Andrew Svetlov7c684072018-01-27 21:22:47 +02001116 async def sendfile(self, transport, file, offset=0, count=None,
1117 *, fallback=True):
1118 """Send a file to transport.
1119
1120 Return the total number of bytes which were sent.
1121
1122 The method uses high-performance os.sendfile if available.
1123
1124 file must be a regular file object opened in binary mode.
1125
1126 offset tells from where to start reading the file. If specified,
1127 count is the total number of bytes to transmit as opposed to
1128 sending the file until EOF is reached. File position is updated on
1129 return or also in case of error in which case file.tell()
1130 can be used to figure out the number of bytes
1131 which were sent.
1132
1133 fallback set to True makes asyncio to manually read and send
1134 the file when the platform does not support the sendfile syscall
1135 (e.g. Windows or SSL socket on Unix).
1136
1137 Raise SendfileNotAvailableError if the system does not support
1138 sendfile syscall and fallback is False.
1139 """
1140 if transport.is_closing():
1141 raise RuntimeError("Transport is closing")
1142 mode = getattr(transport, '_sendfile_compatible',
1143 constants._SendfileMode.UNSUPPORTED)
1144 if mode is constants._SendfileMode.UNSUPPORTED:
1145 raise RuntimeError(
1146 f"sendfile is not supported for transport {transport!r}")
1147 if mode is constants._SendfileMode.TRY_NATIVE:
1148 try:
1149 return await self._sendfile_native(transport, file,
1150 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001151 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7c684072018-01-27 21:22:47 +02001152 if not fallback:
1153 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001154
1155 if not fallback:
1156 raise RuntimeError(
1157 f"fallback is disabled and native sendfile is not "
1158 f"supported for transport {transport!r}")
1159
Andrew Svetlov7c684072018-01-27 21:22:47 +02001160 return await self._sendfile_fallback(transport, file,
1161 offset, count)
1162
1163 async def _sendfile_native(self, transp, file, offset, count):
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001164 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov7c684072018-01-27 21:22:47 +02001165 "sendfile syscall is not supported")
1166
1167 async def _sendfile_fallback(self, transp, file, offset, count):
1168 if offset:
1169 file.seek(offset)
1170 blocksize = min(count, 16384) if count else 16384
1171 buf = bytearray(blocksize)
1172 total_sent = 0
1173 proto = _SendfileFallbackProtocol(transp)
1174 try:
1175 while True:
1176 if count:
1177 blocksize = min(count - total_sent, blocksize)
1178 if blocksize <= 0:
1179 return total_sent
1180 view = memoryview(buf)[:blocksize]
Andrew Svetlov02372652019-06-15 14:05:35 +03001181 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov7c684072018-01-27 21:22:47 +02001182 if not read:
1183 return total_sent # EOF
1184 await proto.drain()
Andrew Svetlovef215232019-06-15 14:05:08 +03001185 transp.write(view[:read])
Andrew Svetlov7c684072018-01-27 21:22:47 +02001186 total_sent += read
1187 finally:
1188 if total_sent > 0 and hasattr(file, 'seek'):
1189 file.seek(offset + total_sent)
1190 await proto.restore()
1191
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001192 async def start_tls(self, transport, protocol, sslcontext, *,
1193 server_side=False,
1194 server_hostname=None,
1195 ssl_handshake_timeout=None):
1196 """Upgrade transport to TLS.
1197
1198 Return a new transport that *protocol* should start using
1199 immediately.
1200 """
1201 if ssl is None:
1202 raise RuntimeError('Python ssl module is not available')
1203
1204 if not isinstance(sslcontext, ssl.SSLContext):
1205 raise TypeError(
1206 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1207 f'got {sslcontext!r}')
1208
1209 if not getattr(transport, '_start_tls_compatible', False):
1210 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001211 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001212
1213 waiter = self.create_future()
1214 ssl_protocol = sslproto.SSLProtocol(
1215 self, protocol, sslcontext, waiter,
1216 server_side, server_hostname,
1217 ssl_handshake_timeout=ssl_handshake_timeout,
1218 call_connection_made=False)
1219
Yury Selivanovf2955872018-05-29 01:00:12 -04001220 # Pause early so that "ssl_protocol.data_received()" doesn't
1221 # have a chance to get called before "ssl_protocol.connection_made()".
1222 transport.pause_reading()
1223
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001224 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001225 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1226 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001227
Yury Selivanov96026432018-06-04 11:32:35 -04001228 try:
1229 await waiter
Yury Selivanov431b5402019-05-27 14:45:12 +02001230 except BaseException:
Yury Selivanov96026432018-06-04 11:32:35 -04001231 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001232 conmade_cb.cancel()
1233 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001234 raise
1235
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001236 return ssl_protocol._app_transport
1237
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001238 async def create_datagram_endpoint(self, protocol_factory,
1239 local_addr=None, remote_addr=None, *,
1240 family=0, proto=0, flags=0,
Kyle Stanleyab513a32019-12-09 09:21:10 -05001241 reuse_address=_unset, reuse_port=None,
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001242 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001243 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001244 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001245 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001246 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001247 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001248 if (local_addr or remote_addr or
1249 family or proto or flags or
Kyle Stanleyab513a32019-12-09 09:21:10 -05001250 reuse_port or allow_broadcast):
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001251 # show the problematic kwargs in exception msg
1252 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1253 family=family, proto=proto, flags=flags,
1254 reuse_address=reuse_address, reuse_port=reuse_port,
1255 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001256 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001257 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001258 f'socket modifier keyword arguments can not be used '
1259 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001260 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001261 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001262 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001263 if not (local_addr or remote_addr):
1264 if family == 0:
1265 raise ValueError('unexpected address family')
1266 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001267 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1268 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001269 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001270 raise TypeError('string is expected')
Quentin Dawans56065d42019-04-09 15:40:59 +02001271
1272 if local_addr and local_addr[0] not in (0, '\x00'):
1273 try:
1274 if stat.S_ISSOCK(os.stat(local_addr).st_mode):
1275 os.remove(local_addr)
1276 except FileNotFoundError:
1277 pass
1278 except OSError as err:
1279 # Directory may have permissions only to create socket.
1280 logger.error('Unable to check or remove stale UNIX '
1281 'socket %r: %r',
1282 local_addr, err)
1283
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001284 addr_pairs_info = (((family, proto),
1285 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001286 else:
1287 # join address by (family, protocol)
Inada Naokif3451702019-02-05 17:04:40 +09001288 addr_infos = {} # Using order preserving dict
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001289 for idx, addr in ((0, local_addr), (1, remote_addr)):
1290 if addr is not None:
1291 assert isinstance(addr, tuple) and len(addr) == 2, (
1292 '2-tuple is expected')
1293
Yury Selivanov19a44f62017-12-14 20:53:26 -05001294 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001295 addr, family=family, type=socket.SOCK_DGRAM,
1296 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001297 if not infos:
1298 raise OSError('getaddrinfo() returned empty list')
1299
1300 for fam, _, pro, _, address in infos:
1301 key = (fam, pro)
1302 if key not in addr_infos:
1303 addr_infos[key] = [None, None]
1304 addr_infos[key][idx] = address
1305
1306 # each addr has to have info for each (family, proto) pair
1307 addr_pairs_info = [
1308 (key, addr_pair) for key, addr_pair in addr_infos.items()
1309 if not ((local_addr and addr_pair[0] is None) or
1310 (remote_addr and addr_pair[1] is None))]
1311
1312 if not addr_pairs_info:
1313 raise ValueError('can not get address information')
1314
1315 exceptions = []
1316
Kyle Stanleyab513a32019-12-09 09:21:10 -05001317 # bpo-37228
1318 if reuse_address is not _unset:
1319 if reuse_address:
1320 raise ValueError("Passing `reuse_address=True` is no "
1321 "longer supported, as the usage of "
1322 "SO_REUSEPORT in UDP poses a significant "
1323 "security concern.")
1324 else:
1325 warnings.warn("The *reuse_address* parameter has been "
1326 "deprecated as of 3.5.10 and is scheduled "
1327 "for removal in 3.11.", DeprecationWarning,
1328 stacklevel=2)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001329
1330 for ((family, proto),
1331 (local_address, remote_address)) in addr_pairs_info:
1332 sock = None
1333 r_addr = None
1334 try:
1335 sock = socket.socket(
1336 family=family, type=socket.SOCK_DGRAM, proto=proto)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001337 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001338 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001339 if allow_broadcast:
1340 sock.setsockopt(
1341 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1342 sock.setblocking(False)
1343
1344 if local_addr:
1345 sock.bind(local_address)
1346 if remote_addr:
Vincent Michel63deaa52019-05-07 19:18:49 +02001347 if not allow_broadcast:
1348 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001349 r_addr = remote_address
1350 except OSError as exc:
1351 if sock is not None:
1352 sock.close()
1353 exceptions.append(exc)
1354 except:
1355 if sock is not None:
1356 sock.close()
1357 raise
1358 else:
1359 break
1360 else:
1361 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001362
1363 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001364 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001365 transport = self._make_datagram_transport(
1366 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001367 if self._debug:
1368 if local_addr:
1369 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1370 "created: (%r, %r)",
1371 local_addr, remote_addr, transport, protocol)
1372 else:
1373 logger.debug("Datagram endpoint remote_addr=%r created: "
1374 "(%r, %r)",
1375 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001376
1377 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001378 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001379 except:
1380 transport.close()
1381 raise
1382
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001383 return transport, protocol
1384
Yury Selivanov19a44f62017-12-14 20:53:26 -05001385 async def _ensure_resolved(self, address, *,
1386 family=0, type=socket.SOCK_STREAM,
1387 proto=0, flags=0, loop):
1388 host, port = address[:2]
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +02001389 info = _ipaddr_info(host, port, family, type, proto, *address[2:])
Yury Selivanov19a44f62017-12-14 20:53:26 -05001390 if info is not None:
1391 # "host" is already a resolved IP.
1392 return [info]
1393 else:
1394 return await loop.getaddrinfo(host, port, family=family, type=type,
1395 proto=proto, flags=flags)
1396
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001397 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001398 infos = await self._ensure_resolved((host, port), family=family,
1399 type=socket.SOCK_STREAM,
1400 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001401 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001402 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001403 return infos
1404
Neil Aspinallf7686c12017-12-19 19:45:42 +00001405 async def create_server(
1406 self, protocol_factory, host=None, port=None,
1407 *,
1408 family=socket.AF_UNSPEC,
1409 flags=socket.AI_PASSIVE,
1410 sock=None,
1411 backlog=100,
1412 ssl=None,
1413 reuse_address=None,
1414 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001415 ssl_handshake_timeout=None,
1416 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001417 """Create a TCP server.
1418
Yury Selivanov6370f342017-12-10 18:36:12 -05001419 The host parameter can be a string, in that case the TCP server is
1420 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001421
1422 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001423 the TCP server is bound to all hosts of the sequence. If a host
1424 appears multiple times (possibly indirectly e.g. when hostnames
1425 resolve to the same IP address), the server is only bound once to that
1426 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001427
Victor Stinneracdb7822014-07-14 18:33:40 +02001428 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001429
1430 This method is a coroutine.
1431 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001432 if isinstance(ssl, bool):
1433 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001434
1435 if ssl_handshake_timeout is not None and ssl is None:
1436 raise ValueError(
1437 'ssl_handshake_timeout is only meaningful with ssl')
1438
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001439 if host is not None or port is not None:
1440 if sock is not None:
1441 raise ValueError(
1442 'host/port and sock can not be specified at the same time')
1443
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001444 if reuse_address is None:
1445 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1446 sockets = []
1447 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001448 hosts = [None]
1449 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001450 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001451 hosts = [host]
1452 else:
1453 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001454
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001455 fs = [self._create_server_getaddrinfo(host, port, family=family,
1456 flags=flags)
1457 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001458 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001459 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001460
1461 completed = False
1462 try:
1463 for res in infos:
1464 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001465 try:
1466 sock = socket.socket(af, socktype, proto)
1467 except socket.error:
1468 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001469 if self._debug:
1470 logger.warning('create_server() failed to create '
1471 'socket.socket(%r, %r, %r)',
1472 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001473 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001474 sockets.append(sock)
1475 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001476 sock.setsockopt(
1477 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1478 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001479 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001480 # Disable IPv4/IPv6 dual stack support (enabled by
1481 # default on Linux) which makes a single socket
1482 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001483 if (_HAS_IPv6 and
1484 af == socket.AF_INET6 and
1485 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001486 sock.setsockopt(socket.IPPROTO_IPV6,
1487 socket.IPV6_V6ONLY,
1488 True)
1489 try:
1490 sock.bind(sa)
1491 except OSError as err:
1492 raise OSError(err.errno, 'error while attempting '
1493 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001494 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001495 completed = True
1496 finally:
1497 if not completed:
1498 for sock in sockets:
1499 sock.close()
1500 else:
1501 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001502 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001503 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001504 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001505 sockets = [sock]
1506
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001507 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001508 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001509
1510 server = Server(self, sockets, protocol_factory,
1511 ssl, backlog, ssl_handshake_timeout)
1512 if start_serving:
1513 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001514 # Skip one loop iteration so that all 'loop.add_reader'
1515 # go through.
1516 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001517
Victor Stinnere912e652014-07-12 03:11:53 +02001518 if self._debug:
1519 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001520 return server
1521
Neil Aspinallf7686c12017-12-19 19:45:42 +00001522 async def connect_accepted_socket(
1523 self, protocol_factory, sock,
1524 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001525 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001526 """Handle an accepted connection.
1527
1528 This is used by servers that accept connections outside of
1529 asyncio but that use asyncio to handle connections.
1530
1531 This method is a coroutine. When completed, the coroutine
1532 returns a (transport, protocol) pair.
1533 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001534 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001535 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001536
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001537 if ssl_handshake_timeout is not None and not ssl:
1538 raise ValueError(
1539 'ssl_handshake_timeout is only meaningful with ssl')
1540
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001541 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001542 sock, protocol_factory, ssl, '', server_side=True,
1543 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001544 if self._debug:
1545 # Get the socket from the transport because SSL transport closes
1546 # the old socket and creates a new SSL socket
1547 sock = transport.get_extra_info('socket')
1548 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1549 return transport, protocol
1550
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001551 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001552 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001553 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001554 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001555
1556 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001557 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001558 except:
1559 transport.close()
1560 raise
1561
Victor Stinneracdb7822014-07-14 18:33:40 +02001562 if self._debug:
1563 logger.debug('Read pipe %r connected: (%r, %r)',
1564 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001565 return transport, protocol
1566
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001567 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001568 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001569 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001570 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001571
1572 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001573 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001574 except:
1575 transport.close()
1576 raise
1577
Victor Stinneracdb7822014-07-14 18:33:40 +02001578 if self._debug:
1579 logger.debug('Write pipe %r connected: (%r, %r)',
1580 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001581 return transport, protocol
1582
Victor Stinneracdb7822014-07-14 18:33:40 +02001583 def _log_subprocess(self, msg, stdin, stdout, stderr):
1584 info = [msg]
1585 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001586 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001587 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001588 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001589 else:
1590 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001591 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001592 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001593 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001594 logger.debug(' '.join(info))
1595
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001596 async def subprocess_shell(self, protocol_factory, cmd, *,
1597 stdin=subprocess.PIPE,
1598 stdout=subprocess.PIPE,
1599 stderr=subprocess.PIPE,
1600 universal_newlines=False,
1601 shell=True, bufsize=0,
sbstpf0d4c642019-05-27 19:51:19 -04001602 encoding=None, errors=None, text=None,
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001603 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001604 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001605 raise ValueError("cmd must be a string")
1606 if universal_newlines:
1607 raise ValueError("universal_newlines must be False")
1608 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001609 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001610 if bufsize != 0:
1611 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001612 if text:
1613 raise ValueError("text must be False")
1614 if encoding is not None:
1615 raise ValueError("encoding must be None")
1616 if errors is not None:
1617 raise ValueError("errors must be None")
1618
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001619 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001620 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001621 if self._debug:
1622 # don't log parameters: they may contain sensitive information
1623 # (password) and may be too long
1624 debug_log = 'run shell command %r' % cmd
1625 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001626 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001627 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001628 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001629 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001630 return transport, protocol
1631
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001632 async def subprocess_exec(self, protocol_factory, program, *args,
1633 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1634 stderr=subprocess.PIPE, universal_newlines=False,
sbstpf0d4c642019-05-27 19:51:19 -04001635 shell=False, bufsize=0,
1636 encoding=None, errors=None, text=None,
1637 **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001638 if universal_newlines:
1639 raise ValueError("universal_newlines must be False")
1640 if shell:
1641 raise ValueError("shell must be False")
1642 if bufsize != 0:
1643 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001644 if text:
1645 raise ValueError("text must be False")
1646 if encoding is not None:
1647 raise ValueError("encoding must be None")
1648 if errors is not None:
1649 raise ValueError("errors must be None")
1650
Victor Stinner20e07432014-02-11 11:44:56 +01001651 popen_args = (program,) + args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001652 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001653 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001654 if self._debug:
1655 # don't log parameters: they may contain sensitive information
1656 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001657 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001658 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001659 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001660 protocol, popen_args, False, stdin, stdout, stderr,
1661 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001662 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001663 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001664 return transport, protocol
1665
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001666 def get_exception_handler(self):
1667 """Return an exception handler, or None if the default one is in use.
1668 """
1669 return self._exception_handler
1670
Yury Selivanov569efa22014-02-18 18:02:19 -05001671 def set_exception_handler(self, handler):
1672 """Set handler as the new event loop exception handler.
1673
1674 If handler is None, the default exception handler will
1675 be set.
1676
1677 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001678 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001679 will be a reference to the active event loop, 'context'
1680 will be a dict object (see `call_exception_handler()`
1681 documentation for details about context).
1682 """
1683 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001684 raise TypeError(f'A callable object or None is expected, '
1685 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001686 self._exception_handler = handler
1687
1688 def default_exception_handler(self, context):
1689 """Default exception handler.
1690
1691 This is called when an exception occurs and no exception
1692 handler is set, and can be called by a custom exception
1693 handler that wants to defer to the default behavior.
1694
Antoine Pitrou921e9432017-11-07 17:23:29 +01001695 This default handler logs the error message and other
1696 context-dependent information. In debug mode, a truncated
1697 stack trace is also appended showing where the given object
1698 (e.g. a handle or future or task) was created, if any.
1699
Victor Stinneracdb7822014-07-14 18:33:40 +02001700 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001701 `call_exception_handler()`.
1702 """
1703 message = context.get('message')
1704 if not message:
1705 message = 'Unhandled exception in event loop'
1706
1707 exception = context.get('exception')
1708 if exception is not None:
1709 exc_info = (type(exception), exception, exception.__traceback__)
1710 else:
1711 exc_info = False
1712
Yury Selivanov6370f342017-12-10 18:36:12 -05001713 if ('source_traceback' not in context and
1714 self._current_handle is not None and
1715 self._current_handle._source_traceback):
1716 context['handle_traceback'] = \
1717 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001718
Yury Selivanov569efa22014-02-18 18:02:19 -05001719 log_lines = [message]
1720 for key in sorted(context):
1721 if key in {'message', 'exception'}:
1722 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001723 value = context[key]
1724 if key == 'source_traceback':
1725 tb = ''.join(traceback.format_list(value))
1726 value = 'Object created at (most recent call last):\n'
1727 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001728 elif key == 'handle_traceback':
1729 tb = ''.join(traceback.format_list(value))
1730 value = 'Handle created at (most recent call last):\n'
1731 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001732 else:
1733 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001734 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001735
1736 logger.error('\n'.join(log_lines), exc_info=exc_info)
1737
1738 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001739 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001740
Victor Stinneracdb7822014-07-14 18:33:40 +02001741 The context argument is a dict containing the following keys:
1742
Yury Selivanov569efa22014-02-18 18:02:19 -05001743 - 'message': Error message;
1744 - 'exception' (optional): Exception object;
1745 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001746 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001747 - 'handle' (optional): Handle instance;
1748 - 'protocol' (optional): Protocol instance;
1749 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001750 - 'socket' (optional): Socket instance;
1751 - 'asyncgen' (optional): Asynchronous generator that caused
1752 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001753
Victor Stinneracdb7822014-07-14 18:33:40 +02001754 New keys maybe introduced in the future.
1755
1756 Note: do not overload this method in an event loop subclass.
1757 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001758 `set_exception_handler()` method.
1759 """
1760 if self._exception_handler is None:
1761 try:
1762 self.default_exception_handler(context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001763 except (SystemExit, KeyboardInterrupt):
1764 raise
1765 except BaseException:
Yury Selivanov569efa22014-02-18 18:02:19 -05001766 # Second protection layer for unexpected errors
1767 # in the default implementation, as well as for subclassed
1768 # event loops with overloaded "default_exception_handler".
1769 logger.error('Exception in default exception handler',
1770 exc_info=True)
1771 else:
1772 try:
1773 self._exception_handler(self, context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001774 except (SystemExit, KeyboardInterrupt):
1775 raise
1776 except BaseException as exc:
Yury Selivanov569efa22014-02-18 18:02:19 -05001777 # Exception in the user set custom exception handler.
1778 try:
1779 # Let's try default handler.
1780 self.default_exception_handler({
1781 'message': 'Unhandled error in exception handler',
1782 'exception': exc,
1783 'context': context,
1784 })
Yury Selivanov431b5402019-05-27 14:45:12 +02001785 except (SystemExit, KeyboardInterrupt):
1786 raise
1787 except BaseException:
Victor Stinneracdb7822014-07-14 18:33:40 +02001788 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001789 # overloaded.
1790 logger.error('Exception in default exception handler '
1791 'while handling an unexpected error '
1792 'in custom exception handler',
1793 exc_info=True)
1794
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001795 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001796 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001797 assert isinstance(handle, events.Handle), 'A Handle is required here'
1798 if handle._cancelled:
1799 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001800 assert not isinstance(handle, events.TimerHandle)
1801 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001802
1803 def _add_callback_signalsafe(self, handle):
1804 """Like _add_callback() but called from a signal handler."""
1805 self._add_callback(handle)
1806 self._write_to_self()
1807
Yury Selivanov592ada92014-09-25 12:07:56 -04001808 def _timer_handle_cancelled(self, handle):
1809 """Notification that a TimerHandle has been cancelled."""
1810 if handle._scheduled:
1811 self._timer_cancelled_count += 1
1812
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001813 def _run_once(self):
1814 """Run one full iteration of the event loop.
1815
1816 This calls all currently ready callbacks, polls for I/O,
1817 schedules the resulting callbacks, and finally schedules
1818 'call_later' callbacks.
1819 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001820
Yury Selivanov592ada92014-09-25 12:07:56 -04001821 sched_count = len(self._scheduled)
1822 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1823 self._timer_cancelled_count / sched_count >
1824 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001825 # Remove delayed calls that were cancelled if their number
1826 # is too high
1827 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001828 for handle in self._scheduled:
1829 if handle._cancelled:
1830 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001831 else:
1832 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001833
Victor Stinner68da8fc2014-09-30 18:08:36 +02001834 heapq.heapify(new_scheduled)
1835 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001836 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001837 else:
1838 # Remove delayed calls that were cancelled from head of queue.
1839 while self._scheduled and self._scheduled[0]._cancelled:
1840 self._timer_cancelled_count -= 1
1841 handle = heapq.heappop(self._scheduled)
1842 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001843
1844 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001845 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001846 timeout = 0
1847 elif self._scheduled:
1848 # Compute the desired timeout.
1849 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001850 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001851
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001852 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001853 self._process_events(event_list)
1854
1855 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001856 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001857 while self._scheduled:
1858 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001859 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001860 break
1861 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001862 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001863 self._ready.append(handle)
1864
1865 # This is the only place where callbacks are actually *called*.
1866 # All other places just add them to ready.
1867 # Note: We run all currently scheduled callbacks, but not any
1868 # callbacks scheduled by callbacks run this time around --
1869 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001870 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001871 ntodo = len(self._ready)
1872 for i in range(ntodo):
1873 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001874 if handle._cancelled:
1875 continue
1876 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001877 try:
1878 self._current_handle = handle
1879 t0 = self.time()
1880 handle._run()
1881 dt = self.time() - t0
1882 if dt >= self.slow_callback_duration:
1883 logger.warning('Executing %s took %.3f seconds',
1884 _format_handle(handle), dt)
1885 finally:
1886 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001887 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001888 handle._run()
1889 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001890
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001891 def _set_coroutine_origin_tracking(self, enabled):
1892 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001893 return
1894
Yury Selivanove8944cb2015-05-12 11:43:04 -04001895 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001896 self._coroutine_origin_tracking_saved_depth = (
1897 sys.get_coroutine_origin_tracking_depth())
1898 sys.set_coroutine_origin_tracking_depth(
1899 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001900 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001901 sys.set_coroutine_origin_tracking_depth(
1902 self._coroutine_origin_tracking_saved_depth)
1903
1904 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001905
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001906 def get_debug(self):
1907 return self._debug
1908
1909 def set_debug(self, enabled):
1910 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001911
Yury Selivanove8944cb2015-05-12 11:43:04 -04001912 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001913 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)