blob: de9fa4f4f7f3b6bb0868dbaf49cf43ca777ef7cc [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
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +0200105def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
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:
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +0200154 return af, type, proto, '', (host, port, flowinfo, scopeid)
Yury Selivanovd904c232018-06-28 21:59:32 -0400155 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:
Vincent Michel63deaa52019-05-07 19:18:49 +02001309 if not allow_broadcast:
1310 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001311 r_addr = remote_address
1312 except OSError as exc:
1313 if sock is not None:
1314 sock.close()
1315 exceptions.append(exc)
1316 except:
1317 if sock is not None:
1318 sock.close()
1319 raise
1320 else:
1321 break
1322 else:
1323 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001324
1325 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001326 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001327 transport = self._make_datagram_transport(
1328 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001329 if self._debug:
1330 if local_addr:
1331 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1332 "created: (%r, %r)",
1333 local_addr, remote_addr, transport, protocol)
1334 else:
1335 logger.debug("Datagram endpoint remote_addr=%r created: "
1336 "(%r, %r)",
1337 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001338
1339 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001340 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001341 except:
1342 transport.close()
1343 raise
1344
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001345 return transport, protocol
1346
Yury Selivanov19a44f62017-12-14 20:53:26 -05001347 async def _ensure_resolved(self, address, *,
1348 family=0, type=socket.SOCK_STREAM,
1349 proto=0, flags=0, loop):
1350 host, port = address[:2]
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +02001351 info = _ipaddr_info(host, port, family, type, proto, *address[2:])
Yury Selivanov19a44f62017-12-14 20:53:26 -05001352 if info is not None:
1353 # "host" is already a resolved IP.
1354 return [info]
1355 else:
1356 return await loop.getaddrinfo(host, port, family=family, type=type,
1357 proto=proto, flags=flags)
1358
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001359 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001360 infos = await self._ensure_resolved((host, port), family=family,
1361 type=socket.SOCK_STREAM,
1362 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001363 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001364 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001365 return infos
1366
Neil Aspinallf7686c12017-12-19 19:45:42 +00001367 async def create_server(
1368 self, protocol_factory, host=None, port=None,
1369 *,
1370 family=socket.AF_UNSPEC,
1371 flags=socket.AI_PASSIVE,
1372 sock=None,
1373 backlog=100,
1374 ssl=None,
1375 reuse_address=None,
1376 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001377 ssl_handshake_timeout=None,
1378 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001379 """Create a TCP server.
1380
Yury Selivanov6370f342017-12-10 18:36:12 -05001381 The host parameter can be a string, in that case the TCP server is
1382 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001383
1384 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001385 the TCP server is bound to all hosts of the sequence. If a host
1386 appears multiple times (possibly indirectly e.g. when hostnames
1387 resolve to the same IP address), the server is only bound once to that
1388 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001389
Victor Stinneracdb7822014-07-14 18:33:40 +02001390 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001391
1392 This method is a coroutine.
1393 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001394 if isinstance(ssl, bool):
1395 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001396
1397 if ssl_handshake_timeout is not None and ssl is None:
1398 raise ValueError(
1399 'ssl_handshake_timeout is only meaningful with ssl')
1400
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001401 if host is not None or port is not None:
1402 if sock is not None:
1403 raise ValueError(
1404 'host/port and sock can not be specified at the same time')
1405
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001406 if reuse_address is None:
1407 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1408 sockets = []
1409 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001410 hosts = [None]
1411 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001412 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001413 hosts = [host]
1414 else:
1415 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001416
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001417 fs = [self._create_server_getaddrinfo(host, port, family=family,
1418 flags=flags)
1419 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001420 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001421 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001422
1423 completed = False
1424 try:
1425 for res in infos:
1426 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001427 try:
1428 sock = socket.socket(af, socktype, proto)
1429 except socket.error:
1430 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001431 if self._debug:
1432 logger.warning('create_server() failed to create '
1433 'socket.socket(%r, %r, %r)',
1434 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001435 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001436 sockets.append(sock)
1437 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001438 sock.setsockopt(
1439 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1440 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001441 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001442 # Disable IPv4/IPv6 dual stack support (enabled by
1443 # default on Linux) which makes a single socket
1444 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001445 if (_HAS_IPv6 and
1446 af == socket.AF_INET6 and
1447 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001448 sock.setsockopt(socket.IPPROTO_IPV6,
1449 socket.IPV6_V6ONLY,
1450 True)
1451 try:
1452 sock.bind(sa)
1453 except OSError as err:
1454 raise OSError(err.errno, 'error while attempting '
1455 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001456 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001457 completed = True
1458 finally:
1459 if not completed:
1460 for sock in sockets:
1461 sock.close()
1462 else:
1463 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001464 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001465 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001466 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001467 sockets = [sock]
1468
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001469 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001470 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001471
1472 server = Server(self, sockets, protocol_factory,
1473 ssl, backlog, ssl_handshake_timeout)
1474 if start_serving:
1475 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001476 # Skip one loop iteration so that all 'loop.add_reader'
1477 # go through.
1478 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001479
Victor Stinnere912e652014-07-12 03:11:53 +02001480 if self._debug:
1481 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001482 return server
1483
Neil Aspinallf7686c12017-12-19 19:45:42 +00001484 async def connect_accepted_socket(
1485 self, protocol_factory, sock,
1486 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001487 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001488 """Handle an accepted connection.
1489
1490 This is used by servers that accept connections outside of
1491 asyncio but that use asyncio to handle connections.
1492
1493 This method is a coroutine. When completed, the coroutine
1494 returns a (transport, protocol) pair.
1495 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001496 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001497 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001498
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001499 if ssl_handshake_timeout is not None and not ssl:
1500 raise ValueError(
1501 'ssl_handshake_timeout is only meaningful with ssl')
1502
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001503 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001504 sock, protocol_factory, ssl, '', server_side=True,
1505 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001506 if self._debug:
1507 # Get the socket from the transport because SSL transport closes
1508 # the old socket and creates a new SSL socket
1509 sock = transport.get_extra_info('socket')
1510 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1511 return transport, protocol
1512
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001513 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001514 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001515 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001516 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001517
1518 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001519 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001520 except:
1521 transport.close()
1522 raise
1523
Victor Stinneracdb7822014-07-14 18:33:40 +02001524 if self._debug:
1525 logger.debug('Read pipe %r connected: (%r, %r)',
1526 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001527 return transport, protocol
1528
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001529 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001530 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001531 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001532 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001533
1534 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001535 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001536 except:
1537 transport.close()
1538 raise
1539
Victor Stinneracdb7822014-07-14 18:33:40 +02001540 if self._debug:
1541 logger.debug('Write pipe %r connected: (%r, %r)',
1542 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001543 return transport, protocol
1544
Victor Stinneracdb7822014-07-14 18:33:40 +02001545 def _log_subprocess(self, msg, stdin, stdout, stderr):
1546 info = [msg]
1547 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001548 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001549 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001550 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001551 else:
1552 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001553 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001554 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001555 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001556 logger.debug(' '.join(info))
1557
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001558 async def subprocess_shell(self, protocol_factory, cmd, *,
1559 stdin=subprocess.PIPE,
1560 stdout=subprocess.PIPE,
1561 stderr=subprocess.PIPE,
1562 universal_newlines=False,
1563 shell=True, bufsize=0,
1564 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001565 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001566 raise ValueError("cmd must be a string")
1567 if universal_newlines:
1568 raise ValueError("universal_newlines must be False")
1569 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001570 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001571 if bufsize != 0:
1572 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001573 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001574 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001575 if self._debug:
1576 # don't log parameters: they may contain sensitive information
1577 # (password) and may be too long
1578 debug_log = 'run shell command %r' % cmd
1579 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001580 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001581 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001582 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001583 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001584 return transport, protocol
1585
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001586 async def subprocess_exec(self, protocol_factory, program, *args,
1587 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1588 stderr=subprocess.PIPE, universal_newlines=False,
1589 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001590 if universal_newlines:
1591 raise ValueError("universal_newlines must be False")
1592 if shell:
1593 raise ValueError("shell must be False")
1594 if bufsize != 0:
1595 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001596 popen_args = (program,) + args
1597 for arg in popen_args:
1598 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001599 raise TypeError(
1600 f"program arguments must be a bytes or text string, "
1601 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001602 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001603 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001604 if self._debug:
1605 # don't log parameters: they may contain sensitive information
1606 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001607 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001608 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001609 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001610 protocol, popen_args, False, stdin, stdout, stderr,
1611 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001612 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001613 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001614 return transport, protocol
1615
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001616 def get_exception_handler(self):
1617 """Return an exception handler, or None if the default one is in use.
1618 """
1619 return self._exception_handler
1620
Yury Selivanov569efa22014-02-18 18:02:19 -05001621 def set_exception_handler(self, handler):
1622 """Set handler as the new event loop exception handler.
1623
1624 If handler is None, the default exception handler will
1625 be set.
1626
1627 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001628 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001629 will be a reference to the active event loop, 'context'
1630 will be a dict object (see `call_exception_handler()`
1631 documentation for details about context).
1632 """
1633 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001634 raise TypeError(f'A callable object or None is expected, '
1635 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001636 self._exception_handler = handler
1637
1638 def default_exception_handler(self, context):
1639 """Default exception handler.
1640
1641 This is called when an exception occurs and no exception
1642 handler is set, and can be called by a custom exception
1643 handler that wants to defer to the default behavior.
1644
Antoine Pitrou921e9432017-11-07 17:23:29 +01001645 This default handler logs the error message and other
1646 context-dependent information. In debug mode, a truncated
1647 stack trace is also appended showing where the given object
1648 (e.g. a handle or future or task) was created, if any.
1649
Victor Stinneracdb7822014-07-14 18:33:40 +02001650 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001651 `call_exception_handler()`.
1652 """
1653 message = context.get('message')
1654 if not message:
1655 message = 'Unhandled exception in event loop'
1656
1657 exception = context.get('exception')
1658 if exception is not None:
1659 exc_info = (type(exception), exception, exception.__traceback__)
1660 else:
1661 exc_info = False
1662
Yury Selivanov6370f342017-12-10 18:36:12 -05001663 if ('source_traceback' not in context and
1664 self._current_handle is not None and
1665 self._current_handle._source_traceback):
1666 context['handle_traceback'] = \
1667 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001668
Yury Selivanov569efa22014-02-18 18:02:19 -05001669 log_lines = [message]
1670 for key in sorted(context):
1671 if key in {'message', 'exception'}:
1672 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001673 value = context[key]
1674 if key == 'source_traceback':
1675 tb = ''.join(traceback.format_list(value))
1676 value = 'Object created at (most recent call last):\n'
1677 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001678 elif key == 'handle_traceback':
1679 tb = ''.join(traceback.format_list(value))
1680 value = 'Handle created at (most recent call last):\n'
1681 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001682 else:
1683 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001684 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001685
1686 logger.error('\n'.join(log_lines), exc_info=exc_info)
1687
1688 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001689 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001690
Victor Stinneracdb7822014-07-14 18:33:40 +02001691 The context argument is a dict containing the following keys:
1692
Yury Selivanov569efa22014-02-18 18:02:19 -05001693 - 'message': Error message;
1694 - 'exception' (optional): Exception object;
1695 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001696 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001697 - 'handle' (optional): Handle instance;
1698 - 'protocol' (optional): Protocol instance;
1699 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001700 - 'socket' (optional): Socket instance;
1701 - 'asyncgen' (optional): Asynchronous generator that caused
1702 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001703
Victor Stinneracdb7822014-07-14 18:33:40 +02001704 New keys maybe introduced in the future.
1705
1706 Note: do not overload this method in an event loop subclass.
1707 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001708 `set_exception_handler()` method.
1709 """
1710 if self._exception_handler is None:
1711 try:
1712 self.default_exception_handler(context)
1713 except Exception:
1714 # Second protection layer for unexpected errors
1715 # in the default implementation, as well as for subclassed
1716 # event loops with overloaded "default_exception_handler".
1717 logger.error('Exception in default exception handler',
1718 exc_info=True)
1719 else:
1720 try:
1721 self._exception_handler(self, context)
1722 except Exception as exc:
1723 # Exception in the user set custom exception handler.
1724 try:
1725 # Let's try default handler.
1726 self.default_exception_handler({
1727 'message': 'Unhandled error in exception handler',
1728 'exception': exc,
1729 'context': context,
1730 })
1731 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001732 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001733 # overloaded.
1734 logger.error('Exception in default exception handler '
1735 'while handling an unexpected error '
1736 'in custom exception handler',
1737 exc_info=True)
1738
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001739 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001740 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001741 assert isinstance(handle, events.Handle), 'A Handle is required here'
1742 if handle._cancelled:
1743 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001744 assert not isinstance(handle, events.TimerHandle)
1745 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001746
1747 def _add_callback_signalsafe(self, handle):
1748 """Like _add_callback() but called from a signal handler."""
1749 self._add_callback(handle)
1750 self._write_to_self()
1751
Yury Selivanov592ada92014-09-25 12:07:56 -04001752 def _timer_handle_cancelled(self, handle):
1753 """Notification that a TimerHandle has been cancelled."""
1754 if handle._scheduled:
1755 self._timer_cancelled_count += 1
1756
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001757 def _run_once(self):
1758 """Run one full iteration of the event loop.
1759
1760 This calls all currently ready callbacks, polls for I/O,
1761 schedules the resulting callbacks, and finally schedules
1762 'call_later' callbacks.
1763 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001764
Yury Selivanov592ada92014-09-25 12:07:56 -04001765 sched_count = len(self._scheduled)
1766 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1767 self._timer_cancelled_count / sched_count >
1768 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001769 # Remove delayed calls that were cancelled if their number
1770 # is too high
1771 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001772 for handle in self._scheduled:
1773 if handle._cancelled:
1774 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001775 else:
1776 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001777
Victor Stinner68da8fc2014-09-30 18:08:36 +02001778 heapq.heapify(new_scheduled)
1779 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001780 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001781 else:
1782 # Remove delayed calls that were cancelled from head of queue.
1783 while self._scheduled and self._scheduled[0]._cancelled:
1784 self._timer_cancelled_count -= 1
1785 handle = heapq.heappop(self._scheduled)
1786 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001787
1788 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001789 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001790 timeout = 0
1791 elif self._scheduled:
1792 # Compute the desired timeout.
1793 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001794 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001795
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001796 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001797 self._process_events(event_list)
1798
1799 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001800 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001801 while self._scheduled:
1802 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001803 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001804 break
1805 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001806 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001807 self._ready.append(handle)
1808
1809 # This is the only place where callbacks are actually *called*.
1810 # All other places just add them to ready.
1811 # Note: We run all currently scheduled callbacks, but not any
1812 # callbacks scheduled by callbacks run this time around --
1813 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001814 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001815 ntodo = len(self._ready)
1816 for i in range(ntodo):
1817 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001818 if handle._cancelled:
1819 continue
1820 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001821 try:
1822 self._current_handle = handle
1823 t0 = self.time()
1824 handle._run()
1825 dt = self.time() - t0
1826 if dt >= self.slow_callback_duration:
1827 logger.warning('Executing %s took %.3f seconds',
1828 _format_handle(handle), dt)
1829 finally:
1830 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001831 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001832 handle._run()
1833 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001834
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001835 def _set_coroutine_origin_tracking(self, enabled):
1836 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001837 return
1838
Yury Selivanove8944cb2015-05-12 11:43:04 -04001839 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001840 self._coroutine_origin_tracking_saved_depth = (
1841 sys.get_coroutine_origin_tracking_depth())
1842 sys.set_coroutine_origin_tracking_depth(
1843 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001844 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001845 sys.set_coroutine_origin_tracking_depth(
1846 self._coroutine_origin_tracking_saved_depth)
1847
1848 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001849
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001850 def get_debug(self):
1851 return self._debug
1852
1853 def set_debug(self, enabled):
1854 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001855
Yury Selivanove8944cb2015-05-12 11:43:04 -04001856 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001857 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)