blob: c58906f8b4897f2f3a3984879425657c48f7909d [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
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070048from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049
50
Yury Selivanov6370f342017-12-10 18:36:12 -050051__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070052
53
Yury Selivanov592ada92014-09-25 12:07:56 -040054# Minimum number of _scheduled timer handles before cleanup of
55# cancelled handles is performed.
56_MIN_SCHEDULED_TIMER_HANDLES = 100
57
58# Minimum fraction of _scheduled timer handles that are cancelled
59# before cleanup of cancelled handles is performed.
60_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070061
Victor Stinnerc94a93a2016-04-01 21:43:39 +020062# Exceptions which must not call the exception handler in fatal error
63# methods (_fatal_error())
64_FATAL_ERROR_IGNORE = (BrokenPipeError,
65 ConnectionResetError, ConnectionAbortedError)
66
Andrew Svetlov0dd71802018-09-12 14:03:54 -070067if ssl is not None:
68 _FATAL_ERROR_IGNORE = _FATAL_ERROR_IGNORE + (ssl.SSLCertVerificationError,)
69
Yury Selivanovd904c232018-06-28 21:59:32 -040070_HAS_IPv6 = hasattr(socket, 'AF_INET6')
71
MartinAltmayer944451c2018-07-31 15:06:12 +010072# Maximum timeout passed to select to avoid OS limitations
73MAXIMUM_SELECT_TIMEOUT = 24 * 3600
74
Victor Stinnerc94a93a2016-04-01 21:43:39 +020075
Victor Stinner0e6f52a2014-06-20 17:34:15 +020076def _format_handle(handle):
77 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040078 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020079 # format the task
80 return repr(cb.__self__)
81 else:
82 return str(handle)
83
84
Victor Stinneracdb7822014-07-14 18:33:40 +020085def _format_pipe(fd):
86 if fd == subprocess.PIPE:
87 return '<pipe>'
88 elif fd == subprocess.STDOUT:
89 return '<stdout>'
90 else:
91 return repr(fd)
92
93
Yury Selivanov5587d7c2016-09-15 15:45:07 -040094def _set_reuseport(sock):
95 if not hasattr(socket, 'SO_REUSEPORT'):
96 raise ValueError('reuse_port not supported by socket module')
97 else:
98 try:
99 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
100 except OSError:
101 raise ValueError('reuse_port not supported by socket module, '
102 'SO_REUSEPORT defined but not implemented.')
103
104
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500105def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400106 # Try to skip getaddrinfo if "host" is already an IP. Users might have
107 # handled name resolution in their own code and pass in resolved IPs.
108 if not hasattr(socket, 'inet_pton'):
109 return
110
111 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
112 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500113 return None
114
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500115 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500116 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500117 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500118 proto = socket.IPPROTO_UDP
119 else:
120 return None
121
Yury Selivanova7146162016-06-02 16:51:07 -0400122 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400123 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700124 elif isinstance(port, bytes) and port == b'':
125 port = 0
126 elif isinstance(port, str) and port == '':
127 port = 0
128 else:
129 # If port's a service name like "http", don't skip getaddrinfo.
130 try:
131 port = int(port)
132 except (TypeError, ValueError):
133 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400134
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400135 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500136 afs = [socket.AF_INET]
Yury Selivanovd904c232018-06-28 21:59:32 -0400137 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500138 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400139 else:
140 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500141
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400142 if isinstance(host, bytes):
143 host = host.decode('idna')
144 if '%' in host:
145 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
146 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500147 return None
148
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400149 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500150 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 socket.inet_pton(af, host)
152 # The host has already been resolved.
Yury Selivanovd904c232018-06-28 21:59:32 -0400153 if _HAS_IPv6 and af == socket.AF_INET6:
154 return af, type, proto, '', (host, port, 0, 0)
155 else:
156 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400157 except OSError:
158 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500159
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400160 # "host" is not an IP address.
161 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500162
163
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800164def _interleave_addrinfos(addrinfos, first_address_family_count=1):
165 """Interleave list of addrinfo tuples by family."""
166 # Group addresses by family
167 addrinfos_by_family = collections.OrderedDict()
168 for addr in addrinfos:
169 family = addr[0]
170 if family not in addrinfos_by_family:
171 addrinfos_by_family[family] = []
172 addrinfos_by_family[family].append(addr)
173 addrinfos_lists = list(addrinfos_by_family.values())
174
175 reordered = []
176 if first_address_family_count > 1:
177 reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
178 del addrinfos_lists[0][:first_address_family_count - 1]
179 reordered.extend(
180 a for a in itertools.chain.from_iterable(
181 itertools.zip_longest(*addrinfos_lists)
182 ) if a is not None)
183 return reordered
184
185
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100186def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500187 if not fut.cancelled():
188 exc = fut.exception()
189 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
190 # Issue #22429: run_forever() already finished, no need to
191 # stop it.
192 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500193 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100194
195
Andrew Svetlov3bc0eba2018-12-03 21:08:13 +0200196if hasattr(socket, 'TCP_NODELAY'):
197 def _set_nodelay(sock):
198 if (sock.family in {socket.AF_INET, socket.AF_INET6} and
199 sock.type == socket.SOCK_STREAM and
200 sock.proto == socket.IPPROTO_TCP):
201 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
202else:
203 def _set_nodelay(sock):
204 pass
205
206
Andrew Svetlov7c684072018-01-27 21:22:47 +0200207class _SendfileFallbackProtocol(protocols.Protocol):
208 def __init__(self, transp):
209 if not isinstance(transp, transports._FlowControlMixin):
210 raise TypeError("transport should be _FlowControlMixin instance")
211 self._transport = transp
212 self._proto = transp.get_protocol()
213 self._should_resume_reading = transp.is_reading()
214 self._should_resume_writing = transp._protocol_paused
215 transp.pause_reading()
216 transp.set_protocol(self)
217 if self._should_resume_writing:
218 self._write_ready_fut = self._transport._loop.create_future()
219 else:
220 self._write_ready_fut = None
221
222 async def drain(self):
223 if self._transport.is_closing():
224 raise ConnectionError("Connection closed by peer")
225 fut = self._write_ready_fut
226 if fut is None:
227 return
228 await fut
229
230 def connection_made(self, transport):
231 raise RuntimeError("Invalid state: "
232 "connection should have been established already.")
233
234 def connection_lost(self, exc):
235 if self._write_ready_fut is not None:
236 # Never happens if peer disconnects after sending the whole content
237 # Thus disconnection is always an exception from user perspective
238 if exc is None:
239 self._write_ready_fut.set_exception(
240 ConnectionError("Connection is closed by peer"))
241 else:
242 self._write_ready_fut.set_exception(exc)
243 self._proto.connection_lost(exc)
244
245 def pause_writing(self):
246 if self._write_ready_fut is not None:
247 return
248 self._write_ready_fut = self._transport._loop.create_future()
249
250 def resume_writing(self):
251 if self._write_ready_fut is None:
252 return
253 self._write_ready_fut.set_result(False)
254 self._write_ready_fut = None
255
256 def data_received(self, data):
257 raise RuntimeError("Invalid state: reading should be paused")
258
259 def eof_received(self):
260 raise RuntimeError("Invalid state: reading should be paused")
261
262 async def restore(self):
263 self._transport.set_protocol(self._proto)
264 if self._should_resume_reading:
265 self._transport.resume_reading()
266 if self._write_ready_fut is not None:
267 # Cancel the future.
268 # Basically it has no effect because protocol is switched back,
269 # no code should wait for it anymore.
270 self._write_ready_fut.cancel()
271 if self._should_resume_writing:
272 self._proto.resume_writing()
273
274
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700275class Server(events.AbstractServer):
276
Yury Selivanovc9070d02018-01-25 18:08:09 -0500277 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
278 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200279 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500280 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200281 self._active_count = 0
282 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500283 self._protocol_factory = protocol_factory
284 self._backlog = backlog
285 self._ssl_context = ssl_context
286 self._ssl_handshake_timeout = ssl_handshake_timeout
287 self._serving = False
288 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700289
Victor Stinnere912e652014-07-12 03:11:53 +0200290 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500291 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200292
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200293 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500294 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200295 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700296
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200297 def _detach(self):
298 assert self._active_count > 0
299 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500300 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700301 self._wakeup()
302
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700303 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200304 waiters = self._waiters
305 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700306 for waiter in waiters:
307 if not waiter.done():
308 waiter.set_result(waiter)
309
Yury Selivanovc9070d02018-01-25 18:08:09 -0500310 def _start_serving(self):
311 if self._serving:
312 return
313 self._serving = True
314 for sock in self._sockets:
315 sock.listen(self._backlog)
316 self._loop._start_serving(
317 self._protocol_factory, sock, self._ssl_context,
318 self, self._backlog, self._ssl_handshake_timeout)
319
320 def get_loop(self):
321 return self._loop
322
323 def is_serving(self):
324 return self._serving
325
326 @property
327 def sockets(self):
328 if self._sockets is None:
329 return []
330 return list(self._sockets)
331
332 def close(self):
333 sockets = self._sockets
334 if sockets is None:
335 return
336 self._sockets = None
337
338 for sock in sockets:
339 self._loop._stop_serving(sock)
340
341 self._serving = False
342
343 if (self._serving_forever_fut is not None and
344 not self._serving_forever_fut.done()):
345 self._serving_forever_fut.cancel()
346 self._serving_forever_fut = None
347
348 if self._active_count == 0:
349 self._wakeup()
350
351 async def start_serving(self):
352 self._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -0400353 # Skip one loop iteration so that all 'loop.add_reader'
354 # go through.
355 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500356
357 async def serve_forever(self):
358 if self._serving_forever_fut is not None:
359 raise RuntimeError(
360 f'server {self!r} is already being awaited on serve_forever()')
361 if self._sockets is None:
362 raise RuntimeError(f'server {self!r} is closed')
363
364 self._start_serving()
365 self._serving_forever_fut = self._loop.create_future()
366
367 try:
368 await self._serving_forever_fut
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700369 except exceptions.CancelledError:
Yury Selivanovc9070d02018-01-25 18:08:09 -0500370 try:
371 self.close()
372 await self.wait_closed()
373 finally:
374 raise
375 finally:
376 self._serving_forever_fut = None
377
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200378 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500379 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400381 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200382 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200383 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700384
385
386class BaseEventLoop(events.AbstractEventLoop):
387
388 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400389 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200390 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800391 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700392 self._ready = collections.deque()
393 self._scheduled = []
394 self._default_executor = None
395 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100396 # Identifier of the thread running the event loop, or None if the
397 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100398 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100399 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500400 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800401 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200402 # In debug mode, if the execution of a callback or a step of a task
403 # exceed this duration in seconds, the slow callback/task is logged.
404 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100405 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400406 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800407 self._coroutine_origin_tracking_enabled = False
408 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700409
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500410 # A weak set of all asynchronous generators that are
411 # being iterated by the loop.
412 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700413 # Set to True when `loop.shutdown_asyncgens` is called.
414 self._asyncgens_shutdown_called = False
415
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
Yury Selivanoveb636452016-09-08 22:01:51 -0700512 def _asyncgen_finalizer_hook(self, agen):
513 self._asyncgens.discard(agen)
514 if not self.is_closed():
twisteroid ambassadorc880ffe2018-10-09 23:30:21 +0800515 self.call_soon_threadsafe(self.create_task, agen.aclose())
Yury Selivanoveb636452016-09-08 22:01:51 -0700516
517 def _asyncgen_firstiter_hook(self, agen):
518 if self._asyncgens_shutdown_called:
519 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500520 f"asynchronous generator {agen!r} was scheduled after "
521 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700522 ResourceWarning, source=self)
523
524 self._asyncgens.add(agen)
525
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200526 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700527 """Shutdown all active asynchronous generators."""
528 self._asyncgens_shutdown_called = True
529
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500530 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400531 # If Python version is <3.6 or we don't have any asynchronous
532 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700533 return
534
535 closing_agens = list(self._asyncgens)
536 self._asyncgens.clear()
537
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200538 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700539 *[ag.aclose() for ag in closing_agens],
540 return_exceptions=True,
541 loop=self)
542
Yury Selivanoveb636452016-09-08 22:01:51 -0700543 for result, agen in zip(results, closing_agens):
544 if isinstance(result, Exception):
545 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500546 'message': f'an error occurred during closing of '
547 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700548 'exception': result,
549 'asyncgen': agen
550 })
551
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552 def run_forever(self):
553 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200554 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100555 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400556 raise RuntimeError('This event loop is already running')
557 if events._get_running_loop() is not None:
558 raise RuntimeError(
559 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800560 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100561 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500562
563 old_agen_hooks = sys.get_asyncgen_hooks()
564 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
565 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400567 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700568 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800569 self._run_once()
570 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700571 break
572 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800573 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100574 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400575 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800576 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500577 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700578
579 def run_until_complete(self, future):
580 """Run until the Future is done.
581
582 If the argument is a coroutine, it is wrapped in a Task.
583
Victor Stinneracdb7822014-07-14 18:33:40 +0200584 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585 with the same coroutine twice -- it would wrap it in two
586 different Tasks and that can't be good.
587
588 Return the Future's result, or raise its exception.
589 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200590 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200591
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700592 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400593 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200594 if new_task:
595 # An exception is raised if the future didn't complete, so there
596 # is no need to log the "destroy pending task" message
597 future._log_destroy_pending = False
598
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100599 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200600 try:
601 self.run_forever()
602 except:
603 if new_task and future.done() and not future.cancelled():
604 # The coroutine raised a BaseException. Consume the exception
605 # to not log a warning, the caller doesn't have access to the
606 # local task.
607 future.exception()
608 raise
jimmylai21b3e042017-05-22 22:32:46 -0700609 finally:
610 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700611 if not future.done():
612 raise RuntimeError('Event loop stopped before Future completed.')
613
614 return future.result()
615
616 def stop(self):
617 """Stop running the event loop.
618
Guido van Rossum41f69f42015-11-19 13:28:47 -0800619 Every callback already scheduled will still run. This simply informs
620 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800622 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200624 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700625 """Close the event loop.
626
627 This clears the queues and shuts down the executor,
628 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200629
630 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700631 """
Victor Stinner956de692014-12-26 21:07:52 +0100632 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200633 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200634 if self._closed:
635 return
Victor Stinnere912e652014-07-12 03:11:53 +0200636 if self._debug:
637 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400638 self._closed = True
639 self._ready.clear()
640 self._scheduled.clear()
641 executor = self._default_executor
642 if executor is not None:
643 self._default_executor = None
644 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200645
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200646 def is_closed(self):
647 """Returns True if the event loop was closed."""
648 return self._closed
649
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100650 def __del__(self, _warn=warnings.warn):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900651 if not self.is_closed():
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100652 _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900653 if not self.is_running():
654 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100655
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700656 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200657 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100658 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700659
660 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200661 """Return the time according to the event loop's clock.
662
663 This is a float expressed in seconds since an epoch, but the
664 epoch, precision, accuracy and drift are unspecified and may
665 differ per event loop.
666 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700667 return time.monotonic()
668
Yury Selivanovf23746a2018-01-22 19:11:18 -0500669 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700670 """Arrange for a callback to be called at a given time.
671
672 Return a Handle: an opaque object with a cancel() method that
673 can be used to cancel the call.
674
675 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200676 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700677
678 Each callback will be called exactly once. If two callbacks
679 are scheduled for exactly the same time, it undefined which
680 will be called first.
681
682 Any positional arguments after the callback will be passed to
683 the callback when it is called.
684 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500685 timer = self.call_at(self.time() + delay, callback, *args,
686 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200687 if timer._source_traceback:
688 del timer._source_traceback[-1]
689 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700690
Yury Selivanovf23746a2018-01-22 19:11:18 -0500691 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200692 """Like call_later(), but uses an absolute time.
693
694 Absolute time corresponds to the event loop's time() method.
695 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100696 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100697 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100698 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700699 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500700 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200701 if timer._source_traceback:
702 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700703 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400704 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705 return timer
706
Yury Selivanovf23746a2018-01-22 19:11:18 -0500707 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700708 """Arrange for a callback to be called as soon as possible.
709
Victor Stinneracdb7822014-07-14 18:33:40 +0200710 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700711 order in which they are registered. Each callback will be
712 called exactly once.
713
714 Any positional arguments after the callback will be passed to
715 the callback when it is called.
716 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700717 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100718 if self._debug:
719 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700720 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500721 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200722 if handle._source_traceback:
723 del handle._source_traceback[-1]
724 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100725
Yury Selivanov491a9122016-11-03 15:09:24 -0700726 def _check_callback(self, callback, method):
727 if (coroutines.iscoroutine(callback) or
728 coroutines.iscoroutinefunction(callback)):
729 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500730 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700731 if not callable(callback):
732 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500733 f'a callable object was expected by {method}(), '
734 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700735
Yury Selivanovf23746a2018-01-22 19:11:18 -0500736 def _call_soon(self, callback, args, context):
737 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200738 if handle._source_traceback:
739 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700740 self._ready.append(handle)
741 return handle
742
Victor Stinner956de692014-12-26 21:07:52 +0100743 def _check_thread(self):
744 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100745
Victor Stinneracdb7822014-07-14 18:33:40 +0200746 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100747 likely behave incorrectly when the assumption is violated.
748
Victor Stinneracdb7822014-07-14 18:33:40 +0200749 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100750 responsible for checking this condition for performance reasons.
751 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100752 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200753 return
Victor Stinner956de692014-12-26 21:07:52 +0100754 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100755 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100756 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200757 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100758 "than the current one")
759
Yury Selivanovf23746a2018-01-22 19:11:18 -0500760 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200761 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700762 self._check_closed()
763 if self._debug:
764 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500765 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200766 if handle._source_traceback:
767 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700768 self._write_to_self()
769 return handle
770
Yury Selivanovbec23722018-01-28 14:09:40 -0500771 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100772 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700773 if self._debug:
774 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700775 if executor is None:
776 executor = self._default_executor
777 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400778 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700779 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500780 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500781 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700782
783 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100784 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
785 warnings.warn(
786 'Using the default executor that is not an instance of '
787 'ThreadPoolExecutor is deprecated and will be prohibited '
788 'in Python 3.9',
789 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700790 self._default_executor = executor
791
Victor Stinnere912e652014-07-12 03:11:53 +0200792 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500793 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200794 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500795 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200796 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500797 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200798 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500799 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200800 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500801 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200802 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200803 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200804
805 t0 = self.time()
806 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
807 dt = self.time() - t0
808
Yury Selivanov6370f342017-12-10 18:36:12 -0500809 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200810 if dt >= self.slow_callback_duration:
811 logger.info(msg)
812 else:
813 logger.debug(msg)
814 return addrinfo
815
Yury Selivanov19a44f62017-12-14 20:53:26 -0500816 async def getaddrinfo(self, host, port, *,
817 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400818 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500819 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200820 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500821 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700822
Yury Selivanov19a44f62017-12-14 20:53:26 -0500823 return await self.run_in_executor(
824 None, getaddr_func, host, port, family, type, proto, flags)
825
826 async def getnameinfo(self, sockaddr, flags=0):
827 return await self.run_in_executor(
828 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700829
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200830 async def sock_sendfile(self, sock, file, offset=0, count=None,
831 *, fallback=True):
832 if self._debug and sock.gettimeout() != 0:
833 raise ValueError("the socket must be non-blocking")
834 self._check_sendfile_params(sock, file, offset, count)
835 try:
836 return await self._sock_sendfile_native(sock, file,
837 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700838 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7464e872018-01-19 20:04:29 +0200839 if not fallback:
840 raise
841 return await self._sock_sendfile_fallback(sock, file,
842 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200843
844 async def _sock_sendfile_native(self, sock, file, offset, count):
845 # NB: sendfile syscall is not supported for SSL sockets and
846 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700847 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200848 f"syscall sendfile is not available for socket {sock!r} "
849 "and file {file!r} combination")
850
851 async def _sock_sendfile_fallback(self, sock, file, offset, count):
852 if offset:
853 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400854 blocksize = (
855 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
856 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
857 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200858 buf = bytearray(blocksize)
859 total_sent = 0
860 try:
861 while True:
862 if count:
863 blocksize = min(count - total_sent, blocksize)
864 if blocksize <= 0:
865 break
866 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400867 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200868 if not read:
869 break # EOF
870 await self.sock_sendall(sock, view)
871 total_sent += read
872 return total_sent
873 finally:
874 if total_sent > 0 and hasattr(file, 'seek'):
875 file.seek(offset + total_sent)
876
877 def _check_sendfile_params(self, sock, file, offset, count):
878 if 'b' not in getattr(file, 'mode', 'b'):
879 raise ValueError("file should be opened in binary mode")
880 if not sock.type == socket.SOCK_STREAM:
881 raise ValueError("only SOCK_STREAM type sockets are supported")
882 if count is not None:
883 if not isinstance(count, int):
884 raise TypeError(
885 "count must be a positive integer (got {!r})".format(count))
886 if count <= 0:
887 raise ValueError(
888 "count must be a positive integer (got {!r})".format(count))
889 if not isinstance(offset, int):
890 raise TypeError(
891 "offset must be a non-negative integer (got {!r})".format(
892 offset))
893 if offset < 0:
894 raise ValueError(
895 "offset must be a non-negative integer (got {!r})".format(
896 offset))
897
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800898 async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
899 """Create, bind and connect one socket."""
900 my_exceptions = []
901 exceptions.append(my_exceptions)
902 family, type_, proto, _, address = addr_info
903 sock = None
904 try:
905 sock = socket.socket(family=family, type=type_, proto=proto)
906 sock.setblocking(False)
907 if local_addr_infos is not None:
908 for _, _, _, _, laddr in local_addr_infos:
909 try:
910 sock.bind(laddr)
911 break
912 except OSError as exc:
913 msg = (
914 f'error while attempting to bind on '
915 f'address {laddr!r}: '
916 f'{exc.strerror.lower()}'
917 )
918 exc = OSError(exc.errno, msg)
919 my_exceptions.append(exc)
920 else: # all bind attempts failed
921 raise my_exceptions.pop()
922 await self.sock_connect(sock, address)
923 return sock
924 except OSError as exc:
925 my_exceptions.append(exc)
926 if sock is not None:
927 sock.close()
928 raise
929 except:
930 if sock is not None:
931 sock.close()
932 raise
933
Neil Aspinallf7686c12017-12-19 19:45:42 +0000934 async def create_connection(
935 self, protocol_factory, host=None, port=None,
936 *, ssl=None, family=0,
937 proto=0, flags=0, sock=None,
938 local_addr=None, server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800939 ssl_handshake_timeout=None,
940 happy_eyeballs_delay=None, interleave=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200941 """Connect to a TCP server.
942
943 Create a streaming transport connection to a given Internet host and
944 port: socket family AF_INET or socket.AF_INET6 depending on host (or
945 family if specified), socket type SOCK_STREAM. protocol_factory must be
946 a callable returning a protocol instance.
947
948 This method is a coroutine which will try to establish the connection
949 in the background. When successful, the coroutine returns a
950 (transport, protocol) pair.
951 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700952 if server_hostname is not None and not ssl:
953 raise ValueError('server_hostname is only meaningful with ssl')
954
955 if server_hostname is None and ssl:
956 # Use host as default for server_hostname. It is an error
957 # if host is empty or not set, e.g. when an
958 # already-connected socket was passed or when only a port
959 # is given. To avoid this error, you can pass
960 # server_hostname='' -- this will bypass the hostname
961 # check. (This also means that if host is a numeric
962 # IP/IPv6 address, we will attempt to verify that exact
963 # address; this will probably fail, but it is possible to
964 # create a certificate for a specific IP address, so we
965 # don't judge it here.)
966 if not host:
967 raise ValueError('You must set server_hostname '
968 'when using ssl without a host')
969 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700970
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200971 if ssl_handshake_timeout is not None and not ssl:
972 raise ValueError(
973 'ssl_handshake_timeout is only meaningful with ssl')
974
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800975 if happy_eyeballs_delay is not None and interleave is None:
976 # If using happy eyeballs, default to interleave addresses by family
977 interleave = 1
978
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700979 if host is not None or port is not None:
980 if sock is not None:
981 raise ValueError(
982 'host/port and sock can not be specified at the same time')
983
Yury Selivanov19a44f62017-12-14 20:53:26 -0500984 infos = await self._ensure_resolved(
985 (host, port), family=family,
986 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700987 if not infos:
988 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500989
990 if local_addr is not None:
991 laddr_infos = await self._ensure_resolved(
992 local_addr, family=family,
993 type=socket.SOCK_STREAM, proto=proto,
994 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700995 if not laddr_infos:
996 raise OSError('getaddrinfo() returned empty list')
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800997 else:
998 laddr_infos = None
999
1000 if interleave:
1001 infos = _interleave_addrinfos(infos, interleave)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001002
1003 exceptions = []
twisteroid ambassador88f07a82019-05-05 19:14:35 +08001004 if happy_eyeballs_delay is None:
1005 # not using happy eyeballs
1006 for addrinfo in infos:
1007 try:
1008 sock = await self._connect_sock(
1009 exceptions, addrinfo, laddr_infos)
1010 break
1011 except OSError:
1012 continue
1013 else: # using happy eyeballs
1014 sock, _, _ = await staggered.staggered_race(
1015 (functools.partial(self._connect_sock,
1016 exceptions, addrinfo, laddr_infos)
1017 for addrinfo in infos),
1018 happy_eyeballs_delay, loop=self)
1019
1020 if sock is None:
1021 exceptions = [exc for sub in exceptions for exc in sub]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001022 if len(exceptions) == 1:
1023 raise exceptions[0]
1024 else:
1025 # If they all have the same str(), raise one.
1026 model = str(exceptions[0])
1027 if all(str(exc) == model for exc in exceptions):
1028 raise exceptions[0]
1029 # Raise a combined exception so the user can see all
1030 # the various error messages.
1031 raise OSError('Multiple exceptions: {}'.format(
1032 ', '.join(str(exc) for exc in exceptions)))
1033
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001034 else:
1035 if sock is None:
1036 raise ValueError(
1037 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001038 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -05001039 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
1040 # are SOCK_STREAM.
1041 # We support passing AF_UNIX sockets even though we have
1042 # a dedicated API for that: create_unix_connection.
1043 # Disallowing AF_UNIX in this method, breaks backwards
1044 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001045 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001046 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001047
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001048 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001049 sock, protocol_factory, ssl, server_hostname,
1050 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001051 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +02001052 # Get the socket from the transport because SSL transport closes
1053 # the old socket and creates a new SSL socket
1054 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +02001055 logger.debug("%r connected to %s:%r: (%r, %r)",
1056 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -05001057 return transport, protocol
1058
Neil Aspinallf7686c12017-12-19 19:45:42 +00001059 async def _create_connection_transport(
1060 self, sock, protocol_factory, ssl,
1061 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001062 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001063
1064 sock.setblocking(False)
1065
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001066 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001067 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001068 if ssl:
1069 sslcontext = None if isinstance(ssl, bool) else ssl
1070 transport = self._make_ssl_transport(
1071 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001072 server_side=server_side, server_hostname=server_hostname,
1073 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001074 else:
1075 transport = self._make_socket_transport(sock, protocol, waiter)
1076
Victor Stinner29ad0112015-01-15 00:04:21 +01001077 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001078 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001079 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001080 transport.close()
1081 raise
1082
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001083 return transport, protocol
1084
Andrew Svetlov7c684072018-01-27 21:22:47 +02001085 async def sendfile(self, transport, file, offset=0, count=None,
1086 *, fallback=True):
1087 """Send a file to transport.
1088
1089 Return the total number of bytes which were sent.
1090
1091 The method uses high-performance os.sendfile if available.
1092
1093 file must be a regular file object opened in binary mode.
1094
1095 offset tells from where to start reading the file. If specified,
1096 count is the total number of bytes to transmit as opposed to
1097 sending the file until EOF is reached. File position is updated on
1098 return or also in case of error in which case file.tell()
1099 can be used to figure out the number of bytes
1100 which were sent.
1101
1102 fallback set to True makes asyncio to manually read and send
1103 the file when the platform does not support the sendfile syscall
1104 (e.g. Windows or SSL socket on Unix).
1105
1106 Raise SendfileNotAvailableError if the system does not support
1107 sendfile syscall and fallback is False.
1108 """
1109 if transport.is_closing():
1110 raise RuntimeError("Transport is closing")
1111 mode = getattr(transport, '_sendfile_compatible',
1112 constants._SendfileMode.UNSUPPORTED)
1113 if mode is constants._SendfileMode.UNSUPPORTED:
1114 raise RuntimeError(
1115 f"sendfile is not supported for transport {transport!r}")
1116 if mode is constants._SendfileMode.TRY_NATIVE:
1117 try:
1118 return await self._sendfile_native(transport, file,
1119 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001120 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7c684072018-01-27 21:22:47 +02001121 if not fallback:
1122 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001123
1124 if not fallback:
1125 raise RuntimeError(
1126 f"fallback is disabled and native sendfile is not "
1127 f"supported for transport {transport!r}")
1128
Andrew Svetlov7c684072018-01-27 21:22:47 +02001129 return await self._sendfile_fallback(transport, file,
1130 offset, count)
1131
1132 async def _sendfile_native(self, transp, file, offset, count):
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001133 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov7c684072018-01-27 21:22:47 +02001134 "sendfile syscall is not supported")
1135
1136 async def _sendfile_fallback(self, transp, file, offset, count):
1137 if offset:
1138 file.seek(offset)
1139 blocksize = min(count, 16384) if count else 16384
1140 buf = bytearray(blocksize)
1141 total_sent = 0
1142 proto = _SendfileFallbackProtocol(transp)
1143 try:
1144 while True:
1145 if count:
1146 blocksize = min(count - total_sent, blocksize)
1147 if blocksize <= 0:
1148 return total_sent
1149 view = memoryview(buf)[:blocksize]
1150 read = file.readinto(view)
1151 if not read:
1152 return total_sent # EOF
1153 await proto.drain()
1154 transp.write(view)
1155 total_sent += read
1156 finally:
1157 if total_sent > 0 and hasattr(file, 'seek'):
1158 file.seek(offset + total_sent)
1159 await proto.restore()
1160
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001161 async def start_tls(self, transport, protocol, sslcontext, *,
1162 server_side=False,
1163 server_hostname=None,
1164 ssl_handshake_timeout=None):
1165 """Upgrade transport to TLS.
1166
1167 Return a new transport that *protocol* should start using
1168 immediately.
1169 """
1170 if ssl is None:
1171 raise RuntimeError('Python ssl module is not available')
1172
1173 if not isinstance(sslcontext, ssl.SSLContext):
1174 raise TypeError(
1175 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1176 f'got {sslcontext!r}')
1177
1178 if not getattr(transport, '_start_tls_compatible', False):
1179 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001180 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001181
1182 waiter = self.create_future()
1183 ssl_protocol = sslproto.SSLProtocol(
1184 self, protocol, sslcontext, waiter,
1185 server_side, server_hostname,
1186 ssl_handshake_timeout=ssl_handshake_timeout,
1187 call_connection_made=False)
1188
Yury Selivanovf2955872018-05-29 01:00:12 -04001189 # Pause early so that "ssl_protocol.data_received()" doesn't
1190 # have a chance to get called before "ssl_protocol.connection_made()".
1191 transport.pause_reading()
1192
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001193 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001194 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1195 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001196
Yury Selivanov96026432018-06-04 11:32:35 -04001197 try:
1198 await waiter
1199 except Exception:
1200 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001201 conmade_cb.cancel()
1202 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001203 raise
1204
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001205 return ssl_protocol._app_transport
1206
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001207 async def create_datagram_endpoint(self, protocol_factory,
1208 local_addr=None, remote_addr=None, *,
1209 family=0, proto=0, flags=0,
1210 reuse_address=None, reuse_port=None,
1211 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001212 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001213 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001214 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001215 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001216 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001217 if (local_addr or remote_addr or
1218 family or proto or flags or
1219 reuse_address or reuse_port or allow_broadcast):
1220 # show the problematic kwargs in exception msg
1221 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1222 family=family, proto=proto, flags=flags,
1223 reuse_address=reuse_address, reuse_port=reuse_port,
1224 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001225 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001226 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001227 f'socket modifier keyword arguments can not be used '
1228 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001229 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001230 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001231 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001232 if not (local_addr or remote_addr):
1233 if family == 0:
1234 raise ValueError('unexpected address family')
1235 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001236 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1237 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001238 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001239 raise TypeError('string is expected')
Quentin Dawans56065d42019-04-09 15:40:59 +02001240
1241 if local_addr and local_addr[0] not in (0, '\x00'):
1242 try:
1243 if stat.S_ISSOCK(os.stat(local_addr).st_mode):
1244 os.remove(local_addr)
1245 except FileNotFoundError:
1246 pass
1247 except OSError as err:
1248 # Directory may have permissions only to create socket.
1249 logger.error('Unable to check or remove stale UNIX '
1250 'socket %r: %r',
1251 local_addr, err)
1252
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001253 addr_pairs_info = (((family, proto),
1254 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001255 else:
1256 # join address by (family, protocol)
Inada Naokif3451702019-02-05 17:04:40 +09001257 addr_infos = {} # Using order preserving dict
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001258 for idx, addr in ((0, local_addr), (1, remote_addr)):
1259 if addr is not None:
1260 assert isinstance(addr, tuple) and len(addr) == 2, (
1261 '2-tuple is expected')
1262
Yury Selivanov19a44f62017-12-14 20:53:26 -05001263 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001264 addr, family=family, type=socket.SOCK_DGRAM,
1265 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001266 if not infos:
1267 raise OSError('getaddrinfo() returned empty list')
1268
1269 for fam, _, pro, _, address in infos:
1270 key = (fam, pro)
1271 if key not in addr_infos:
1272 addr_infos[key] = [None, None]
1273 addr_infos[key][idx] = address
1274
1275 # each addr has to have info for each (family, proto) pair
1276 addr_pairs_info = [
1277 (key, addr_pair) for key, addr_pair in addr_infos.items()
1278 if not ((local_addr and addr_pair[0] is None) or
1279 (remote_addr and addr_pair[1] is None))]
1280
1281 if not addr_pairs_info:
1282 raise ValueError('can not get address information')
1283
1284 exceptions = []
1285
1286 if reuse_address is None:
1287 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1288
1289 for ((family, proto),
1290 (local_address, remote_address)) in addr_pairs_info:
1291 sock = None
1292 r_addr = None
1293 try:
1294 sock = socket.socket(
1295 family=family, type=socket.SOCK_DGRAM, proto=proto)
1296 if reuse_address:
1297 sock.setsockopt(
1298 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1299 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001300 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001301 if allow_broadcast:
1302 sock.setsockopt(
1303 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1304 sock.setblocking(False)
1305
1306 if local_addr:
1307 sock.bind(local_address)
1308 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001309 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001310 r_addr = remote_address
1311 except OSError as exc:
1312 if sock is not None:
1313 sock.close()
1314 exceptions.append(exc)
1315 except:
1316 if sock is not None:
1317 sock.close()
1318 raise
1319 else:
1320 break
1321 else:
1322 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323
1324 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001325 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001326 transport = self._make_datagram_transport(
1327 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001328 if self._debug:
1329 if local_addr:
1330 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1331 "created: (%r, %r)",
1332 local_addr, remote_addr, transport, protocol)
1333 else:
1334 logger.debug("Datagram endpoint remote_addr=%r created: "
1335 "(%r, %r)",
1336 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001337
1338 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001339 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001340 except:
1341 transport.close()
1342 raise
1343
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001344 return transport, protocol
1345
Yury Selivanov19a44f62017-12-14 20:53:26 -05001346 async def _ensure_resolved(self, address, *,
1347 family=0, type=socket.SOCK_STREAM,
1348 proto=0, flags=0, loop):
1349 host, port = address[:2]
1350 info = _ipaddr_info(host, port, family, type, proto)
1351 if info is not None:
1352 # "host" is already a resolved IP.
1353 return [info]
1354 else:
1355 return await loop.getaddrinfo(host, port, family=family, type=type,
1356 proto=proto, flags=flags)
1357
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001358 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001359 infos = await self._ensure_resolved((host, port), family=family,
1360 type=socket.SOCK_STREAM,
1361 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001362 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001363 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001364 return infos
1365
Neil Aspinallf7686c12017-12-19 19:45:42 +00001366 async def create_server(
1367 self, protocol_factory, host=None, port=None,
1368 *,
1369 family=socket.AF_UNSPEC,
1370 flags=socket.AI_PASSIVE,
1371 sock=None,
1372 backlog=100,
1373 ssl=None,
1374 reuse_address=None,
1375 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001376 ssl_handshake_timeout=None,
1377 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001378 """Create a TCP server.
1379
Yury Selivanov6370f342017-12-10 18:36:12 -05001380 The host parameter can be a string, in that case the TCP server is
1381 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001382
1383 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001384 the TCP server is bound to all hosts of the sequence. If a host
1385 appears multiple times (possibly indirectly e.g. when hostnames
1386 resolve to the same IP address), the server is only bound once to that
1387 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001388
Victor Stinneracdb7822014-07-14 18:33:40 +02001389 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001390
1391 This method is a coroutine.
1392 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001393 if isinstance(ssl, bool):
1394 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001395
1396 if ssl_handshake_timeout is not None and ssl is None:
1397 raise ValueError(
1398 'ssl_handshake_timeout is only meaningful with ssl')
1399
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001400 if host is not None or port is not None:
1401 if sock is not None:
1402 raise ValueError(
1403 'host/port and sock can not be specified at the same time')
1404
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001405 if reuse_address is None:
1406 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1407 sockets = []
1408 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001409 hosts = [None]
1410 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001411 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001412 hosts = [host]
1413 else:
1414 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001415
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001416 fs = [self._create_server_getaddrinfo(host, port, family=family,
1417 flags=flags)
1418 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001419 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001420 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001421
1422 completed = False
1423 try:
1424 for res in infos:
1425 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001426 try:
1427 sock = socket.socket(af, socktype, proto)
1428 except socket.error:
1429 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001430 if self._debug:
1431 logger.warning('create_server() failed to create '
1432 'socket.socket(%r, %r, %r)',
1433 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001434 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001435 sockets.append(sock)
1436 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001437 sock.setsockopt(
1438 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1439 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001440 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001441 # Disable IPv4/IPv6 dual stack support (enabled by
1442 # default on Linux) which makes a single socket
1443 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001444 if (_HAS_IPv6 and
1445 af == socket.AF_INET6 and
1446 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001447 sock.setsockopt(socket.IPPROTO_IPV6,
1448 socket.IPV6_V6ONLY,
1449 True)
1450 try:
1451 sock.bind(sa)
1452 except OSError as err:
1453 raise OSError(err.errno, 'error while attempting '
1454 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001455 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001456 completed = True
1457 finally:
1458 if not completed:
1459 for sock in sockets:
1460 sock.close()
1461 else:
1462 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001463 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001464 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001465 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001466 sockets = [sock]
1467
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001468 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001469 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001470
1471 server = Server(self, sockets, protocol_factory,
1472 ssl, backlog, ssl_handshake_timeout)
1473 if start_serving:
1474 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001475 # Skip one loop iteration so that all 'loop.add_reader'
1476 # go through.
1477 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001478
Victor Stinnere912e652014-07-12 03:11:53 +02001479 if self._debug:
1480 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001481 return server
1482
Neil Aspinallf7686c12017-12-19 19:45:42 +00001483 async def connect_accepted_socket(
1484 self, protocol_factory, sock,
1485 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001486 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001487 """Handle an accepted connection.
1488
1489 This is used by servers that accept connections outside of
1490 asyncio but that use asyncio to handle connections.
1491
1492 This method is a coroutine. When completed, the coroutine
1493 returns a (transport, protocol) pair.
1494 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001495 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001496 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001497
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001498 if ssl_handshake_timeout is not None and not ssl:
1499 raise ValueError(
1500 'ssl_handshake_timeout is only meaningful with ssl')
1501
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001502 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001503 sock, protocol_factory, ssl, '', server_side=True,
1504 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001505 if self._debug:
1506 # Get the socket from the transport because SSL transport closes
1507 # the old socket and creates a new SSL socket
1508 sock = transport.get_extra_info('socket')
1509 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1510 return transport, protocol
1511
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001512 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001513 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001514 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001515 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001516
1517 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001518 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001519 except:
1520 transport.close()
1521 raise
1522
Victor Stinneracdb7822014-07-14 18:33:40 +02001523 if self._debug:
1524 logger.debug('Read pipe %r connected: (%r, %r)',
1525 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001526 return transport, protocol
1527
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001528 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001529 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001530 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001531 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001532
1533 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001534 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001535 except:
1536 transport.close()
1537 raise
1538
Victor Stinneracdb7822014-07-14 18:33:40 +02001539 if self._debug:
1540 logger.debug('Write pipe %r connected: (%r, %r)',
1541 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001542 return transport, protocol
1543
Victor Stinneracdb7822014-07-14 18:33:40 +02001544 def _log_subprocess(self, msg, stdin, stdout, stderr):
1545 info = [msg]
1546 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001547 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001548 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001549 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001550 else:
1551 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001552 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001553 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001554 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001555 logger.debug(' '.join(info))
1556
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001557 async def subprocess_shell(self, protocol_factory, cmd, *,
1558 stdin=subprocess.PIPE,
1559 stdout=subprocess.PIPE,
1560 stderr=subprocess.PIPE,
1561 universal_newlines=False,
1562 shell=True, bufsize=0,
1563 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001564 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001565 raise ValueError("cmd must be a string")
1566 if universal_newlines:
1567 raise ValueError("universal_newlines must be False")
1568 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001569 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001570 if bufsize != 0:
1571 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001572 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001573 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001574 if self._debug:
1575 # don't log parameters: they may contain sensitive information
1576 # (password) and may be too long
1577 debug_log = 'run shell command %r' % cmd
1578 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001579 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001580 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001581 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001582 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001583 return transport, protocol
1584
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001585 async def subprocess_exec(self, protocol_factory, program, *args,
1586 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1587 stderr=subprocess.PIPE, universal_newlines=False,
1588 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001589 if universal_newlines:
1590 raise ValueError("universal_newlines must be False")
1591 if shell:
1592 raise ValueError("shell must be False")
1593 if bufsize != 0:
1594 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001595 popen_args = (program,) + args
1596 for arg in popen_args:
1597 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001598 raise TypeError(
1599 f"program arguments must be a bytes or text string, "
1600 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001601 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001602 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001603 if self._debug:
1604 # don't log parameters: they may contain sensitive information
1605 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001606 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001607 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001608 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001609 protocol, popen_args, False, stdin, stdout, stderr,
1610 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001611 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001612 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001613 return transport, protocol
1614
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001615 def get_exception_handler(self):
1616 """Return an exception handler, or None if the default one is in use.
1617 """
1618 return self._exception_handler
1619
Yury Selivanov569efa22014-02-18 18:02:19 -05001620 def set_exception_handler(self, handler):
1621 """Set handler as the new event loop exception handler.
1622
1623 If handler is None, the default exception handler will
1624 be set.
1625
1626 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001627 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001628 will be a reference to the active event loop, 'context'
1629 will be a dict object (see `call_exception_handler()`
1630 documentation for details about context).
1631 """
1632 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001633 raise TypeError(f'A callable object or None is expected, '
1634 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001635 self._exception_handler = handler
1636
1637 def default_exception_handler(self, context):
1638 """Default exception handler.
1639
1640 This is called when an exception occurs and no exception
1641 handler is set, and can be called by a custom exception
1642 handler that wants to defer to the default behavior.
1643
Antoine Pitrou921e9432017-11-07 17:23:29 +01001644 This default handler logs the error message and other
1645 context-dependent information. In debug mode, a truncated
1646 stack trace is also appended showing where the given object
1647 (e.g. a handle or future or task) was created, if any.
1648
Victor Stinneracdb7822014-07-14 18:33:40 +02001649 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001650 `call_exception_handler()`.
1651 """
1652 message = context.get('message')
1653 if not message:
1654 message = 'Unhandled exception in event loop'
1655
1656 exception = context.get('exception')
1657 if exception is not None:
1658 exc_info = (type(exception), exception, exception.__traceback__)
1659 else:
1660 exc_info = False
1661
Yury Selivanov6370f342017-12-10 18:36:12 -05001662 if ('source_traceback' not in context and
1663 self._current_handle is not None and
1664 self._current_handle._source_traceback):
1665 context['handle_traceback'] = \
1666 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001667
Yury Selivanov569efa22014-02-18 18:02:19 -05001668 log_lines = [message]
1669 for key in sorted(context):
1670 if key in {'message', 'exception'}:
1671 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001672 value = context[key]
1673 if key == 'source_traceback':
1674 tb = ''.join(traceback.format_list(value))
1675 value = 'Object created at (most recent call last):\n'
1676 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001677 elif key == 'handle_traceback':
1678 tb = ''.join(traceback.format_list(value))
1679 value = 'Handle created at (most recent call last):\n'
1680 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001681 else:
1682 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001683 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001684
1685 logger.error('\n'.join(log_lines), exc_info=exc_info)
1686
1687 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001688 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001689
Victor Stinneracdb7822014-07-14 18:33:40 +02001690 The context argument is a dict containing the following keys:
1691
Yury Selivanov569efa22014-02-18 18:02:19 -05001692 - 'message': Error message;
1693 - 'exception' (optional): Exception object;
1694 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001695 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001696 - 'handle' (optional): Handle instance;
1697 - 'protocol' (optional): Protocol instance;
1698 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001699 - 'socket' (optional): Socket instance;
1700 - 'asyncgen' (optional): Asynchronous generator that caused
1701 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001702
Victor Stinneracdb7822014-07-14 18:33:40 +02001703 New keys maybe introduced in the future.
1704
1705 Note: do not overload this method in an event loop subclass.
1706 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001707 `set_exception_handler()` method.
1708 """
1709 if self._exception_handler is None:
1710 try:
1711 self.default_exception_handler(context)
1712 except Exception:
1713 # Second protection layer for unexpected errors
1714 # in the default implementation, as well as for subclassed
1715 # event loops with overloaded "default_exception_handler".
1716 logger.error('Exception in default exception handler',
1717 exc_info=True)
1718 else:
1719 try:
1720 self._exception_handler(self, context)
1721 except Exception as exc:
1722 # Exception in the user set custom exception handler.
1723 try:
1724 # Let's try default handler.
1725 self.default_exception_handler({
1726 'message': 'Unhandled error in exception handler',
1727 'exception': exc,
1728 'context': context,
1729 })
1730 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001731 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001732 # overloaded.
1733 logger.error('Exception in default exception handler '
1734 'while handling an unexpected error '
1735 'in custom exception handler',
1736 exc_info=True)
1737
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001738 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001739 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001740 assert isinstance(handle, events.Handle), 'A Handle is required here'
1741 if handle._cancelled:
1742 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001743 assert not isinstance(handle, events.TimerHandle)
1744 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001745
1746 def _add_callback_signalsafe(self, handle):
1747 """Like _add_callback() but called from a signal handler."""
1748 self._add_callback(handle)
1749 self._write_to_self()
1750
Yury Selivanov592ada92014-09-25 12:07:56 -04001751 def _timer_handle_cancelled(self, handle):
1752 """Notification that a TimerHandle has been cancelled."""
1753 if handle._scheduled:
1754 self._timer_cancelled_count += 1
1755
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001756 def _run_once(self):
1757 """Run one full iteration of the event loop.
1758
1759 This calls all currently ready callbacks, polls for I/O,
1760 schedules the resulting callbacks, and finally schedules
1761 'call_later' callbacks.
1762 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001763
Yury Selivanov592ada92014-09-25 12:07:56 -04001764 sched_count = len(self._scheduled)
1765 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1766 self._timer_cancelled_count / sched_count >
1767 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001768 # Remove delayed calls that were cancelled if their number
1769 # is too high
1770 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001771 for handle in self._scheduled:
1772 if handle._cancelled:
1773 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001774 else:
1775 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001776
Victor Stinner68da8fc2014-09-30 18:08:36 +02001777 heapq.heapify(new_scheduled)
1778 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001779 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001780 else:
1781 # Remove delayed calls that were cancelled from head of queue.
1782 while self._scheduled and self._scheduled[0]._cancelled:
1783 self._timer_cancelled_count -= 1
1784 handle = heapq.heappop(self._scheduled)
1785 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001786
1787 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001788 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001789 timeout = 0
1790 elif self._scheduled:
1791 # Compute the desired timeout.
1792 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001793 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001794
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001795 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001796 self._process_events(event_list)
1797
1798 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001799 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001800 while self._scheduled:
1801 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001802 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001803 break
1804 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001805 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001806 self._ready.append(handle)
1807
1808 # This is the only place where callbacks are actually *called*.
1809 # All other places just add them to ready.
1810 # Note: We run all currently scheduled callbacks, but not any
1811 # callbacks scheduled by callbacks run this time around --
1812 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001813 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001814 ntodo = len(self._ready)
1815 for i in range(ntodo):
1816 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001817 if handle._cancelled:
1818 continue
1819 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001820 try:
1821 self._current_handle = handle
1822 t0 = self.time()
1823 handle._run()
1824 dt = self.time() - t0
1825 if dt >= self.slow_callback_duration:
1826 logger.warning('Executing %s took %.3f seconds',
1827 _format_handle(handle), dt)
1828 finally:
1829 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001830 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001831 handle._run()
1832 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001833
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001834 def _set_coroutine_origin_tracking(self, enabled):
1835 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001836 return
1837
Yury Selivanove8944cb2015-05-12 11:43:04 -04001838 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001839 self._coroutine_origin_tracking_saved_depth = (
1840 sys.get_coroutine_origin_tracking_depth())
1841 sys.set_coroutine_origin_tracking_depth(
1842 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001843 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001844 sys.set_coroutine_origin_tracking_depth(
1845 self._coroutine_origin_tracking_saved_depth)
1846
1847 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001848
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001849 def get_debug(self):
1850 return self._debug
1851
1852 def set_debug(self, enabled):
1853 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001854
Yury Selivanove8944cb2015-05-12 11:43:04 -04001855 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001856 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)