blob: 90de8587a3bb98b61b217c2a5b57ac7e5148e537 [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Base implementation of event loop.
2
3The event loop can be broken up into a multiplexer (the part
Victor Stinneracdb7822014-07-14 18:33:40 +02004responsible for notifying us of I/O events) and the event loop proper,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07005which wraps a multiplexer with functionality for scheduling callbacks,
6immediately or at a given time in the future.
7
8Whenever a public API takes a callback, subsequent positional
9arguments will be passed to the callback if/when it is called. This
10avoids the proliferation of trivial lambdas implementing closures.
11Keyword arguments for the callback are not supported; this is a
12conscious design decision, leaving the door open for keyword arguments
13to modify the meaning of the API call itself.
14"""
15
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import collections
Serhiy Storchaka2e576f52017-04-24 09:05:00 +030017import collections.abc
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import concurrent.futures
twisteroid ambassador88f07a82019-05-05 19:14:35 +080019import functools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070020import heapq
Victor Stinner5e4a7d82015-09-21 18:33:43 +020021import itertools
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
Quentin Dawans56065d42019-04-09 15:40:59 +020024import stat
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010026import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070027import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020028import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070029import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010030import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070031import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032
Yury Selivanovf111b3d2017-12-30 00:35:36 -050033try:
34 import ssl
35except ImportError: # pragma: no cover
36 ssl = None
37
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020039from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040from . import events
Andrew Svetlov0baa72f2018-09-11 10:13:04 -070041from . import exceptions
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042from . import futures
Andrew Svetlov7c684072018-01-27 21:22:47 +020043from . import protocols
Yury Selivanovf111b3d2017-12-30 00:35:36 -050044from . import sslproto
twisteroid ambassador88f07a82019-05-05 19:14:35 +080045from . import staggered
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046from . import tasks
Andrew Svetlov7c684072018-01-27 21:22:47 +020047from . import transports
Yury Selivanov8cd51652019-05-27 15:57:20 +020048from . import trsock
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070049from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070050
51
Yury Selivanov6370f342017-12-10 18:36:12 -050052__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070053
54
Yury Selivanov592ada92014-09-25 12:07:56 -040055# Minimum number of _scheduled timer handles before cleanup of
56# cancelled handles is performed.
57_MIN_SCHEDULED_TIMER_HANDLES = 100
58
59# Minimum fraction of _scheduled timer handles that are cancelled
60# before cleanup of cancelled handles is performed.
61_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070062
Andrew Svetlov0dd71802018-09-12 14:03:54 -070063
Yury Selivanovd904c232018-06-28 21:59:32 -040064_HAS_IPv6 = hasattr(socket, 'AF_INET6')
65
MartinAltmayer944451c2018-07-31 15:06:12 +010066# Maximum timeout passed to select to avoid OS limitations
67MAXIMUM_SELECT_TIMEOUT = 24 * 3600
68
Victor Stinnerc94a93a2016-04-01 21:43:39 +020069
Victor Stinner0e6f52a2014-06-20 17:34:15 +020070def _format_handle(handle):
71 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040072 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020073 # format the task
74 return repr(cb.__self__)
75 else:
76 return str(handle)
77
78
Victor Stinneracdb7822014-07-14 18:33:40 +020079def _format_pipe(fd):
80 if fd == subprocess.PIPE:
81 return '<pipe>'
82 elif fd == subprocess.STDOUT:
83 return '<stdout>'
84 else:
85 return repr(fd)
86
87
Yury Selivanov5587d7c2016-09-15 15:45:07 -040088def _set_reuseport(sock):
89 if not hasattr(socket, 'SO_REUSEPORT'):
90 raise ValueError('reuse_port not supported by socket module')
91 else:
92 try:
93 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
94 except OSError:
95 raise ValueError('reuse_port not supported by socket module, '
96 'SO_REUSEPORT defined but not implemented.')
97
98
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +020099def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400100 # Try to skip getaddrinfo if "host" is already an IP. Users might have
101 # handled name resolution in their own code and pass in resolved IPs.
102 if not hasattr(socket, 'inet_pton'):
103 return
104
105 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
106 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 return None
108
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500109 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500110 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500111 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500112 proto = socket.IPPROTO_UDP
113 else:
114 return None
115
Yury Selivanova7146162016-06-02 16:51:07 -0400116 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400117 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700118 elif isinstance(port, bytes) and port == b'':
119 port = 0
120 elif isinstance(port, str) and port == '':
121 port = 0
122 else:
123 # If port's a service name like "http", don't skip getaddrinfo.
124 try:
125 port = int(port)
126 except (TypeError, ValueError):
127 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400128
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400129 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500130 afs = [socket.AF_INET]
Yury Selivanovd904c232018-06-28 21:59:32 -0400131 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500132 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400133 else:
134 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500135
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 if isinstance(host, bytes):
137 host = host.decode('idna')
138 if '%' in host:
139 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
140 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500141 return None
142
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400143 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500144 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400145 socket.inet_pton(af, host)
146 # The host has already been resolved.
Yury Selivanovd904c232018-06-28 21:59:32 -0400147 if _HAS_IPv6 and af == socket.AF_INET6:
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +0200148 return af, type, proto, '', (host, port, flowinfo, scopeid)
Yury Selivanovd904c232018-06-28 21:59:32 -0400149 else:
150 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 except OSError:
152 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500153
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400154 # "host" is not an IP address.
155 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500156
157
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800158def _interleave_addrinfos(addrinfos, first_address_family_count=1):
159 """Interleave list of addrinfo tuples by family."""
160 # Group addresses by family
161 addrinfos_by_family = collections.OrderedDict()
162 for addr in addrinfos:
163 family = addr[0]
164 if family not in addrinfos_by_family:
165 addrinfos_by_family[family] = []
166 addrinfos_by_family[family].append(addr)
167 addrinfos_lists = list(addrinfos_by_family.values())
168
169 reordered = []
170 if first_address_family_count > 1:
171 reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
172 del addrinfos_lists[0][:first_address_family_count - 1]
173 reordered.extend(
174 a for a in itertools.chain.from_iterable(
175 itertools.zip_longest(*addrinfos_lists)
176 ) if a is not None)
177 return reordered
178
179
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100180def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500181 if not fut.cancelled():
182 exc = fut.exception()
Yury Selivanov431b5402019-05-27 14:45:12 +0200183 if isinstance(exc, (SystemExit, KeyboardInterrupt)):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500184 # Issue #22429: run_forever() already finished, no need to
185 # stop it.
186 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500187 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100188
189
Andrew Svetlov3bc0eba2018-12-03 21:08:13 +0200190if hasattr(socket, 'TCP_NODELAY'):
191 def _set_nodelay(sock):
192 if (sock.family in {socket.AF_INET, socket.AF_INET6} and
193 sock.type == socket.SOCK_STREAM and
194 sock.proto == socket.IPPROTO_TCP):
195 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
196else:
197 def _set_nodelay(sock):
198 pass
199
200
Andrew Svetlov7c684072018-01-27 21:22:47 +0200201class _SendfileFallbackProtocol(protocols.Protocol):
202 def __init__(self, transp):
203 if not isinstance(transp, transports._FlowControlMixin):
204 raise TypeError("transport should be _FlowControlMixin instance")
205 self._transport = transp
206 self._proto = transp.get_protocol()
207 self._should_resume_reading = transp.is_reading()
208 self._should_resume_writing = transp._protocol_paused
209 transp.pause_reading()
210 transp.set_protocol(self)
211 if self._should_resume_writing:
212 self._write_ready_fut = self._transport._loop.create_future()
213 else:
214 self._write_ready_fut = None
215
216 async def drain(self):
217 if self._transport.is_closing():
218 raise ConnectionError("Connection closed by peer")
219 fut = self._write_ready_fut
220 if fut is None:
221 return
222 await fut
223
224 def connection_made(self, transport):
225 raise RuntimeError("Invalid state: "
226 "connection should have been established already.")
227
228 def connection_lost(self, exc):
229 if self._write_ready_fut is not None:
230 # Never happens if peer disconnects after sending the whole content
231 # Thus disconnection is always an exception from user perspective
232 if exc is None:
233 self._write_ready_fut.set_exception(
234 ConnectionError("Connection is closed by peer"))
235 else:
236 self._write_ready_fut.set_exception(exc)
237 self._proto.connection_lost(exc)
238
239 def pause_writing(self):
240 if self._write_ready_fut is not None:
241 return
242 self._write_ready_fut = self._transport._loop.create_future()
243
244 def resume_writing(self):
245 if self._write_ready_fut is None:
246 return
247 self._write_ready_fut.set_result(False)
248 self._write_ready_fut = None
249
250 def data_received(self, data):
251 raise RuntimeError("Invalid state: reading should be paused")
252
253 def eof_received(self):
254 raise RuntimeError("Invalid state: reading should be paused")
255
256 async def restore(self):
257 self._transport.set_protocol(self._proto)
258 if self._should_resume_reading:
259 self._transport.resume_reading()
260 if self._write_ready_fut is not None:
261 # Cancel the future.
262 # Basically it has no effect because protocol is switched back,
263 # no code should wait for it anymore.
264 self._write_ready_fut.cancel()
265 if self._should_resume_writing:
266 self._proto.resume_writing()
267
268
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700269class Server(events.AbstractServer):
270
Yury Selivanovc9070d02018-01-25 18:08:09 -0500271 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
272 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200273 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500274 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200275 self._active_count = 0
276 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500277 self._protocol_factory = protocol_factory
278 self._backlog = backlog
279 self._ssl_context = ssl_context
280 self._ssl_handshake_timeout = ssl_handshake_timeout
281 self._serving = False
282 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700283
Victor Stinnere912e652014-07-12 03:11:53 +0200284 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500285 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200286
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200287 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500288 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200289 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700290
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200291 def _detach(self):
292 assert self._active_count > 0
293 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500294 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700295 self._wakeup()
296
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200298 waiters = self._waiters
299 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700300 for waiter in waiters:
301 if not waiter.done():
302 waiter.set_result(waiter)
303
Yury Selivanovc9070d02018-01-25 18:08:09 -0500304 def _start_serving(self):
305 if self._serving:
306 return
307 self._serving = True
308 for sock in self._sockets:
309 sock.listen(self._backlog)
310 self._loop._start_serving(
311 self._protocol_factory, sock, self._ssl_context,
312 self, self._backlog, self._ssl_handshake_timeout)
313
314 def get_loop(self):
315 return self._loop
316
317 def is_serving(self):
318 return self._serving
319
320 @property
321 def sockets(self):
322 if self._sockets is None:
Yury Selivanov8cd51652019-05-27 15:57:20 +0200323 return ()
324 return tuple(trsock.TransportSocket(s) for s in self._sockets)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500325
326 def close(self):
327 sockets = self._sockets
328 if sockets is None:
329 return
330 self._sockets = None
331
332 for sock in sockets:
333 self._loop._stop_serving(sock)
334
335 self._serving = False
336
337 if (self._serving_forever_fut is not None and
338 not self._serving_forever_fut.done()):
339 self._serving_forever_fut.cancel()
340 self._serving_forever_fut = None
341
342 if self._active_count == 0:
343 self._wakeup()
344
345 async def start_serving(self):
346 self._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -0400347 # Skip one loop iteration so that all 'loop.add_reader'
348 # go through.
349 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500350
351 async def serve_forever(self):
352 if self._serving_forever_fut is not None:
353 raise RuntimeError(
354 f'server {self!r} is already being awaited on serve_forever()')
355 if self._sockets is None:
356 raise RuntimeError(f'server {self!r} is closed')
357
358 self._start_serving()
359 self._serving_forever_fut = self._loop.create_future()
360
361 try:
362 await self._serving_forever_fut
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700363 except exceptions.CancelledError:
Yury Selivanovc9070d02018-01-25 18:08:09 -0500364 try:
365 self.close()
366 await self.wait_closed()
367 finally:
368 raise
369 finally:
370 self._serving_forever_fut = None
371
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200372 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500373 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700374 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400375 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200376 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200377 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700378
379
380class BaseEventLoop(events.AbstractEventLoop):
381
382 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400383 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200384 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800385 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700386 self._ready = collections.deque()
387 self._scheduled = []
388 self._default_executor = None
389 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100390 # Identifier of the thread running the event loop, or None if the
391 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100392 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100393 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500394 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800395 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200396 # In debug mode, if the execution of a callback or a step of a task
397 # exceed this duration in seconds, the slow callback/task is logged.
398 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100399 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400400 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800401 self._coroutine_origin_tracking_enabled = False
402 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700403
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500404 # A weak set of all asynchronous generators that are
405 # being iterated by the loop.
406 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700407 # Set to True when `loop.shutdown_asyncgens` is called.
408 self._asyncgens_shutdown_called = False
409
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200410 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500411 return (
412 f'<{self.__class__.__name__} running={self.is_running()} '
413 f'closed={self.is_closed()} debug={self.get_debug()}>'
414 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200415
Yury Selivanov7661db62016-05-16 15:38:39 -0400416 def create_future(self):
417 """Create a Future object attached to the loop."""
418 return futures.Future(loop=self)
419
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300420 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200421 """Schedule a coroutine object.
422
Victor Stinneracdb7822014-07-14 18:33:40 +0200423 Return a task object.
424 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100425 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400426 if self._task_factory is None:
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300427 task = tasks.Task(coro, loop=self, name=name)
Yury Selivanov740169c2015-05-11 14:23:38 -0400428 if task._source_traceback:
429 del task._source_traceback[-1]
430 else:
431 task = self._task_factory(self, coro)
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300432 tasks._set_task_name(task, name)
433
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200434 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200435
Yury Selivanov740169c2015-05-11 14:23:38 -0400436 def set_task_factory(self, factory):
437 """Set a task factory that will be used by loop.create_task().
438
439 If factory is None the default task factory will be set.
440
441 If factory is a callable, it should have a signature matching
442 '(loop, coro)', where 'loop' will be a reference to the active
443 event loop, 'coro' will be a coroutine object. The callable
444 must return a Future.
445 """
446 if factory is not None and not callable(factory):
447 raise TypeError('task factory must be a callable or None')
448 self._task_factory = factory
449
450 def get_task_factory(self):
451 """Return a task factory, or None if the default one is in use."""
452 return self._task_factory
453
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700454 def _make_socket_transport(self, sock, protocol, waiter=None, *,
455 extra=None, server=None):
456 """Create socket transport."""
457 raise NotImplementedError
458
Neil Aspinallf7686c12017-12-19 19:45:42 +0000459 def _make_ssl_transport(
460 self, rawsock, protocol, sslcontext, waiter=None,
461 *, server_side=False, server_hostname=None,
462 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500463 ssl_handshake_timeout=None,
464 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700465 """Create SSL transport."""
466 raise NotImplementedError
467
468 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200469 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700470 """Create datagram transport."""
471 raise NotImplementedError
472
473 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
474 extra=None):
475 """Create read pipe transport."""
476 raise NotImplementedError
477
478 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
479 extra=None):
480 """Create write pipe transport."""
481 raise NotImplementedError
482
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200483 async def _make_subprocess_transport(self, protocol, args, shell,
484 stdin, stdout, stderr, bufsize,
485 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700486 """Create subprocess transport."""
487 raise NotImplementedError
488
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700489 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200490 """Write a byte to self-pipe, to wake up the event loop.
491
492 This may be called from a different thread.
493
494 The subclass is responsible for implementing the self-pipe.
495 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700496 raise NotImplementedError
497
498 def _process_events(self, event_list):
499 """Process selector events."""
500 raise NotImplementedError
501
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200502 def _check_closed(self):
503 if self._closed:
504 raise RuntimeError('Event loop is closed')
505
Yury Selivanoveb636452016-09-08 22:01:51 -0700506 def _asyncgen_finalizer_hook(self, agen):
507 self._asyncgens.discard(agen)
508 if not self.is_closed():
twisteroid ambassadorc880ffe2018-10-09 23:30:21 +0800509 self.call_soon_threadsafe(self.create_task, agen.aclose())
Yury Selivanoveb636452016-09-08 22:01:51 -0700510
511 def _asyncgen_firstiter_hook(self, agen):
512 if self._asyncgens_shutdown_called:
513 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500514 f"asynchronous generator {agen!r} was scheduled after "
515 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700516 ResourceWarning, source=self)
517
518 self._asyncgens.add(agen)
519
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200520 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700521 """Shutdown all active asynchronous generators."""
522 self._asyncgens_shutdown_called = True
523
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500524 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400525 # If Python version is <3.6 or we don't have any asynchronous
526 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700527 return
528
529 closing_agens = list(self._asyncgens)
530 self._asyncgens.clear()
531
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200532 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700533 *[ag.aclose() for ag in closing_agens],
534 return_exceptions=True,
535 loop=self)
536
Yury Selivanoveb636452016-09-08 22:01:51 -0700537 for result, agen in zip(results, closing_agens):
538 if isinstance(result, Exception):
539 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500540 'message': f'an error occurred during closing of '
541 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700542 'exception': result,
543 'asyncgen': agen
544 })
545
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700546 def run_forever(self):
547 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200548 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100549 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400550 raise RuntimeError('This event loop is already running')
551 if events._get_running_loop() is not None:
552 raise RuntimeError(
553 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800554 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100555 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500556
557 old_agen_hooks = sys.get_asyncgen_hooks()
558 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
559 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400561 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800563 self._run_once()
564 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700565 break
566 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800567 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100568 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400569 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800570 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500571 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700572
573 def run_until_complete(self, future):
574 """Run until the Future is done.
575
576 If the argument is a coroutine, it is wrapped in a Task.
577
Victor Stinneracdb7822014-07-14 18:33:40 +0200578 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700579 with the same coroutine twice -- it would wrap it in two
580 different Tasks and that can't be good.
581
582 Return the Future's result, or raise its exception.
583 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200584 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200585
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700586 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400587 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200588 if new_task:
589 # An exception is raised if the future didn't complete, so there
590 # is no need to log the "destroy pending task" message
591 future._log_destroy_pending = False
592
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100593 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200594 try:
595 self.run_forever()
596 except:
597 if new_task and future.done() and not future.cancelled():
598 # The coroutine raised a BaseException. Consume the exception
599 # to not log a warning, the caller doesn't have access to the
600 # local task.
601 future.exception()
602 raise
jimmylai21b3e042017-05-22 22:32:46 -0700603 finally:
604 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605 if not future.done():
606 raise RuntimeError('Event loop stopped before Future completed.')
607
608 return future.result()
609
610 def stop(self):
611 """Stop running the event loop.
612
Guido van Rossum41f69f42015-11-19 13:28:47 -0800613 Every callback already scheduled will still run. This simply informs
614 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700615 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800616 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700617
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200618 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700619 """Close the event loop.
620
621 This clears the queues and shuts down the executor,
622 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200623
624 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700625 """
Victor Stinner956de692014-12-26 21:07:52 +0100626 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200627 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200628 if self._closed:
629 return
Victor Stinnere912e652014-07-12 03:11:53 +0200630 if self._debug:
631 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400632 self._closed = True
633 self._ready.clear()
634 self._scheduled.clear()
635 executor = self._default_executor
636 if executor is not None:
637 self._default_executor = None
Łukasz Langa7f9a2ae2019-06-04 13:03:20 +0200638 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200639
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200640 def is_closed(self):
641 """Returns True if the event loop was closed."""
642 return self._closed
643
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100644 def __del__(self, _warn=warnings.warn):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900645 if not self.is_closed():
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100646 _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900647 if not self.is_running():
648 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100649
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700650 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200651 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100652 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700653
654 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200655 """Return the time according to the event loop's clock.
656
657 This is a float expressed in seconds since an epoch, but the
658 epoch, precision, accuracy and drift are unspecified and may
659 differ per event loop.
660 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700661 return time.monotonic()
662
Yury Selivanovf23746a2018-01-22 19:11:18 -0500663 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664 """Arrange for a callback to be called at a given time.
665
666 Return a Handle: an opaque object with a cancel() method that
667 can be used to cancel the call.
668
669 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200670 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700671
672 Each callback will be called exactly once. If two callbacks
673 are scheduled for exactly the same time, it undefined which
674 will be called first.
675
676 Any positional arguments after the callback will be passed to
677 the callback when it is called.
678 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500679 timer = self.call_at(self.time() + delay, callback, *args,
680 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200681 if timer._source_traceback:
682 del timer._source_traceback[-1]
683 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700684
Yury Selivanovf23746a2018-01-22 19:11:18 -0500685 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200686 """Like call_later(), but uses an absolute time.
687
688 Absolute time corresponds to the event loop's time() method.
689 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100690 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100691 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100692 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700693 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500694 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200695 if timer._source_traceback:
696 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700697 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400698 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700699 return timer
700
Yury Selivanovf23746a2018-01-22 19:11:18 -0500701 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700702 """Arrange for a callback to be called as soon as possible.
703
Victor Stinneracdb7822014-07-14 18:33:40 +0200704 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705 order in which they are registered. Each callback will be
706 called exactly once.
707
708 Any positional arguments after the callback will be passed to
709 the callback when it is called.
710 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700711 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100712 if self._debug:
713 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700714 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500715 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200716 if handle._source_traceback:
717 del handle._source_traceback[-1]
718 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100719
Yury Selivanov491a9122016-11-03 15:09:24 -0700720 def _check_callback(self, callback, method):
721 if (coroutines.iscoroutine(callback) or
722 coroutines.iscoroutinefunction(callback)):
723 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500724 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700725 if not callable(callback):
726 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500727 f'a callable object was expected by {method}(), '
728 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700729
Yury Selivanovf23746a2018-01-22 19:11:18 -0500730 def _call_soon(self, callback, args, context):
731 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200732 if handle._source_traceback:
733 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 self._ready.append(handle)
735 return handle
736
Victor Stinner956de692014-12-26 21:07:52 +0100737 def _check_thread(self):
738 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100739
Victor Stinneracdb7822014-07-14 18:33:40 +0200740 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100741 likely behave incorrectly when the assumption is violated.
742
Victor Stinneracdb7822014-07-14 18:33:40 +0200743 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100744 responsible for checking this condition for performance reasons.
745 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100746 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200747 return
Victor Stinner956de692014-12-26 21:07:52 +0100748 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100749 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100750 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200751 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100752 "than the current one")
753
Yury Selivanovf23746a2018-01-22 19:11:18 -0500754 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200755 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700756 self._check_closed()
757 if self._debug:
758 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500759 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200760 if handle._source_traceback:
761 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700762 self._write_to_self()
763 return handle
764
Yury Selivanovbec23722018-01-28 14:09:40 -0500765 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100766 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700767 if self._debug:
768 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700769 if executor is None:
770 executor = self._default_executor
771 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400772 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700773 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500774 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500775 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700776
777 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100778 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
779 warnings.warn(
780 'Using the default executor that is not an instance of '
781 'ThreadPoolExecutor is deprecated and will be prohibited '
782 'in Python 3.9',
783 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700784 self._default_executor = executor
785
Victor Stinnere912e652014-07-12 03:11:53 +0200786 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500787 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200788 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500789 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200790 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500791 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200792 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500793 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200794 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500795 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200796 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200797 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200798
799 t0 = self.time()
800 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
801 dt = self.time() - t0
802
Yury Selivanov6370f342017-12-10 18:36:12 -0500803 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200804 if dt >= self.slow_callback_duration:
805 logger.info(msg)
806 else:
807 logger.debug(msg)
808 return addrinfo
809
Yury Selivanov19a44f62017-12-14 20:53:26 -0500810 async def getaddrinfo(self, host, port, *,
811 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400812 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500813 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200814 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500815 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700816
Yury Selivanov19a44f62017-12-14 20:53:26 -0500817 return await self.run_in_executor(
818 None, getaddr_func, host, port, family, type, proto, flags)
819
820 async def getnameinfo(self, sockaddr, flags=0):
821 return await self.run_in_executor(
822 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700823
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200824 async def sock_sendfile(self, sock, file, offset=0, count=None,
825 *, fallback=True):
826 if self._debug and sock.gettimeout() != 0:
827 raise ValueError("the socket must be non-blocking")
828 self._check_sendfile_params(sock, file, offset, count)
829 try:
830 return await self._sock_sendfile_native(sock, file,
831 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700832 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7464e872018-01-19 20:04:29 +0200833 if not fallback:
834 raise
835 return await self._sock_sendfile_fallback(sock, file,
836 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200837
838 async def _sock_sendfile_native(self, sock, file, offset, count):
839 # NB: sendfile syscall is not supported for SSL sockets and
840 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700841 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200842 f"syscall sendfile is not available for socket {sock!r} "
843 "and file {file!r} combination")
844
845 async def _sock_sendfile_fallback(self, sock, file, offset, count):
846 if offset:
847 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400848 blocksize = (
849 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
850 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
851 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200852 buf = bytearray(blocksize)
853 total_sent = 0
854 try:
855 while True:
856 if count:
857 blocksize = min(count - total_sent, blocksize)
858 if blocksize <= 0:
859 break
860 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400861 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200862 if not read:
863 break # EOF
Andrew Svetlovef215232019-06-15 14:05:08 +0300864 await self.sock_sendall(sock, view[:read])
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200865 total_sent += read
866 return total_sent
867 finally:
868 if total_sent > 0 and hasattr(file, 'seek'):
869 file.seek(offset + total_sent)
870
871 def _check_sendfile_params(self, sock, file, offset, count):
872 if 'b' not in getattr(file, 'mode', 'b'):
873 raise ValueError("file should be opened in binary mode")
874 if not sock.type == socket.SOCK_STREAM:
875 raise ValueError("only SOCK_STREAM type sockets are supported")
876 if count is not None:
877 if not isinstance(count, int):
878 raise TypeError(
879 "count must be a positive integer (got {!r})".format(count))
880 if count <= 0:
881 raise ValueError(
882 "count must be a positive integer (got {!r})".format(count))
883 if not isinstance(offset, int):
884 raise TypeError(
885 "offset must be a non-negative integer (got {!r})".format(
886 offset))
887 if offset < 0:
888 raise ValueError(
889 "offset must be a non-negative integer (got {!r})".format(
890 offset))
891
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800892 async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
893 """Create, bind and connect one socket."""
894 my_exceptions = []
895 exceptions.append(my_exceptions)
896 family, type_, proto, _, address = addr_info
897 sock = None
898 try:
899 sock = socket.socket(family=family, type=type_, proto=proto)
900 sock.setblocking(False)
901 if local_addr_infos is not None:
902 for _, _, _, _, laddr in local_addr_infos:
903 try:
904 sock.bind(laddr)
905 break
906 except OSError as exc:
907 msg = (
908 f'error while attempting to bind on '
909 f'address {laddr!r}: '
910 f'{exc.strerror.lower()}'
911 )
912 exc = OSError(exc.errno, msg)
913 my_exceptions.append(exc)
914 else: # all bind attempts failed
915 raise my_exceptions.pop()
916 await self.sock_connect(sock, address)
917 return sock
918 except OSError as exc:
919 my_exceptions.append(exc)
920 if sock is not None:
921 sock.close()
922 raise
923 except:
924 if sock is not None:
925 sock.close()
926 raise
927
Neil Aspinallf7686c12017-12-19 19:45:42 +0000928 async def create_connection(
929 self, protocol_factory, host=None, port=None,
930 *, ssl=None, family=0,
931 proto=0, flags=0, sock=None,
932 local_addr=None, server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800933 ssl_handshake_timeout=None,
934 happy_eyeballs_delay=None, interleave=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200935 """Connect to a TCP server.
936
937 Create a streaming transport connection to a given Internet host and
938 port: socket family AF_INET or socket.AF_INET6 depending on host (or
939 family if specified), socket type SOCK_STREAM. protocol_factory must be
940 a callable returning a protocol instance.
941
942 This method is a coroutine which will try to establish the connection
943 in the background. When successful, the coroutine returns a
944 (transport, protocol) pair.
945 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700946 if server_hostname is not None and not ssl:
947 raise ValueError('server_hostname is only meaningful with ssl')
948
949 if server_hostname is None and ssl:
950 # Use host as default for server_hostname. It is an error
951 # if host is empty or not set, e.g. when an
952 # already-connected socket was passed or when only a port
953 # is given. To avoid this error, you can pass
954 # server_hostname='' -- this will bypass the hostname
955 # check. (This also means that if host is a numeric
956 # IP/IPv6 address, we will attempt to verify that exact
957 # address; this will probably fail, but it is possible to
958 # create a certificate for a specific IP address, so we
959 # don't judge it here.)
960 if not host:
961 raise ValueError('You must set server_hostname '
962 'when using ssl without a host')
963 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700964
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200965 if ssl_handshake_timeout is not None and not ssl:
966 raise ValueError(
967 'ssl_handshake_timeout is only meaningful with ssl')
968
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800969 if happy_eyeballs_delay is not None and interleave is None:
970 # If using happy eyeballs, default to interleave addresses by family
971 interleave = 1
972
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700973 if host is not None or port is not None:
974 if sock is not None:
975 raise ValueError(
976 'host/port and sock can not be specified at the same time')
977
Yury Selivanov19a44f62017-12-14 20:53:26 -0500978 infos = await self._ensure_resolved(
979 (host, port), family=family,
980 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700981 if not infos:
982 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500983
984 if local_addr is not None:
985 laddr_infos = await self._ensure_resolved(
986 local_addr, family=family,
987 type=socket.SOCK_STREAM, proto=proto,
988 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700989 if not laddr_infos:
990 raise OSError('getaddrinfo() returned empty list')
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800991 else:
992 laddr_infos = None
993
994 if interleave:
995 infos = _interleave_addrinfos(infos, interleave)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700996
997 exceptions = []
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800998 if happy_eyeballs_delay is None:
999 # not using happy eyeballs
1000 for addrinfo in infos:
1001 try:
1002 sock = await self._connect_sock(
1003 exceptions, addrinfo, laddr_infos)
1004 break
1005 except OSError:
1006 continue
1007 else: # using happy eyeballs
1008 sock, _, _ = await staggered.staggered_race(
1009 (functools.partial(self._connect_sock,
1010 exceptions, addrinfo, laddr_infos)
1011 for addrinfo in infos),
1012 happy_eyeballs_delay, loop=self)
1013
1014 if sock is None:
1015 exceptions = [exc for sub in exceptions for exc in sub]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001016 if len(exceptions) == 1:
1017 raise exceptions[0]
1018 else:
1019 # If they all have the same str(), raise one.
1020 model = str(exceptions[0])
1021 if all(str(exc) == model for exc in exceptions):
1022 raise exceptions[0]
1023 # Raise a combined exception so the user can see all
1024 # the various error messages.
1025 raise OSError('Multiple exceptions: {}'.format(
1026 ', '.join(str(exc) for exc in exceptions)))
1027
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001028 else:
1029 if sock is None:
1030 raise ValueError(
1031 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001032 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -05001033 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
1034 # are SOCK_STREAM.
1035 # We support passing AF_UNIX sockets even though we have
1036 # a dedicated API for that: create_unix_connection.
1037 # Disallowing AF_UNIX in this method, breaks backwards
1038 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001039 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001040 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001041
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001042 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001043 sock, protocol_factory, ssl, server_hostname,
1044 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001045 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +02001046 # Get the socket from the transport because SSL transport closes
1047 # the old socket and creates a new SSL socket
1048 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +02001049 logger.debug("%r connected to %s:%r: (%r, %r)",
1050 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -05001051 return transport, protocol
1052
Neil Aspinallf7686c12017-12-19 19:45:42 +00001053 async def _create_connection_transport(
1054 self, sock, protocol_factory, ssl,
1055 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001056 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001057
1058 sock.setblocking(False)
1059
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001060 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001061 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001062 if ssl:
1063 sslcontext = None if isinstance(ssl, bool) else ssl
1064 transport = self._make_ssl_transport(
1065 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001066 server_side=server_side, server_hostname=server_hostname,
1067 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001068 else:
1069 transport = self._make_socket_transport(sock, protocol, waiter)
1070
Victor Stinner29ad0112015-01-15 00:04:21 +01001071 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001072 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001073 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001074 transport.close()
1075 raise
1076
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001077 return transport, protocol
1078
Andrew Svetlov7c684072018-01-27 21:22:47 +02001079 async def sendfile(self, transport, file, offset=0, count=None,
1080 *, fallback=True):
1081 """Send a file to transport.
1082
1083 Return the total number of bytes which were sent.
1084
1085 The method uses high-performance os.sendfile if available.
1086
1087 file must be a regular file object opened in binary mode.
1088
1089 offset tells from where to start reading the file. If specified,
1090 count is the total number of bytes to transmit as opposed to
1091 sending the file until EOF is reached. File position is updated on
1092 return or also in case of error in which case file.tell()
1093 can be used to figure out the number of bytes
1094 which were sent.
1095
1096 fallback set to True makes asyncio to manually read and send
1097 the file when the platform does not support the sendfile syscall
1098 (e.g. Windows or SSL socket on Unix).
1099
1100 Raise SendfileNotAvailableError if the system does not support
1101 sendfile syscall and fallback is False.
1102 """
1103 if transport.is_closing():
1104 raise RuntimeError("Transport is closing")
1105 mode = getattr(transport, '_sendfile_compatible',
1106 constants._SendfileMode.UNSUPPORTED)
1107 if mode is constants._SendfileMode.UNSUPPORTED:
1108 raise RuntimeError(
1109 f"sendfile is not supported for transport {transport!r}")
1110 if mode is constants._SendfileMode.TRY_NATIVE:
1111 try:
1112 return await self._sendfile_native(transport, file,
1113 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001114 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7c684072018-01-27 21:22:47 +02001115 if not fallback:
1116 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001117
1118 if not fallback:
1119 raise RuntimeError(
1120 f"fallback is disabled and native sendfile is not "
1121 f"supported for transport {transport!r}")
1122
Andrew Svetlov7c684072018-01-27 21:22:47 +02001123 return await self._sendfile_fallback(transport, file,
1124 offset, count)
1125
1126 async def _sendfile_native(self, transp, file, offset, count):
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001127 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov7c684072018-01-27 21:22:47 +02001128 "sendfile syscall is not supported")
1129
1130 async def _sendfile_fallback(self, transp, file, offset, count):
1131 if offset:
1132 file.seek(offset)
1133 blocksize = min(count, 16384) if count else 16384
1134 buf = bytearray(blocksize)
1135 total_sent = 0
1136 proto = _SendfileFallbackProtocol(transp)
1137 try:
1138 while True:
1139 if count:
1140 blocksize = min(count - total_sent, blocksize)
1141 if blocksize <= 0:
1142 return total_sent
1143 view = memoryview(buf)[:blocksize]
1144 read = file.readinto(view)
1145 if not read:
1146 return total_sent # EOF
1147 await proto.drain()
Andrew Svetlovef215232019-06-15 14:05:08 +03001148 transp.write(view[:read])
Andrew Svetlov7c684072018-01-27 21:22:47 +02001149 total_sent += read
1150 finally:
1151 if total_sent > 0 and hasattr(file, 'seek'):
1152 file.seek(offset + total_sent)
1153 await proto.restore()
1154
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001155 async def start_tls(self, transport, protocol, sslcontext, *,
1156 server_side=False,
1157 server_hostname=None,
1158 ssl_handshake_timeout=None):
1159 """Upgrade transport to TLS.
1160
1161 Return a new transport that *protocol* should start using
1162 immediately.
1163 """
1164 if ssl is None:
1165 raise RuntimeError('Python ssl module is not available')
1166
1167 if not isinstance(sslcontext, ssl.SSLContext):
1168 raise TypeError(
1169 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1170 f'got {sslcontext!r}')
1171
1172 if not getattr(transport, '_start_tls_compatible', False):
1173 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001174 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001175
1176 waiter = self.create_future()
1177 ssl_protocol = sslproto.SSLProtocol(
1178 self, protocol, sslcontext, waiter,
1179 server_side, server_hostname,
1180 ssl_handshake_timeout=ssl_handshake_timeout,
1181 call_connection_made=False)
1182
Yury Selivanovf2955872018-05-29 01:00:12 -04001183 # Pause early so that "ssl_protocol.data_received()" doesn't
1184 # have a chance to get called before "ssl_protocol.connection_made()".
1185 transport.pause_reading()
1186
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001187 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001188 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1189 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001190
Yury Selivanov96026432018-06-04 11:32:35 -04001191 try:
1192 await waiter
Yury Selivanov431b5402019-05-27 14:45:12 +02001193 except BaseException:
Yury Selivanov96026432018-06-04 11:32:35 -04001194 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001195 conmade_cb.cancel()
1196 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001197 raise
1198
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001199 return ssl_protocol._app_transport
1200
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001201 async def create_datagram_endpoint(self, protocol_factory,
1202 local_addr=None, remote_addr=None, *,
1203 family=0, proto=0, flags=0,
1204 reuse_address=None, reuse_port=None,
1205 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001206 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001207 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001208 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001209 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001210 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001211 if (local_addr or remote_addr or
1212 family or proto or flags or
1213 reuse_address or reuse_port or allow_broadcast):
1214 # show the problematic kwargs in exception msg
1215 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1216 family=family, proto=proto, flags=flags,
1217 reuse_address=reuse_address, reuse_port=reuse_port,
1218 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001219 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001220 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001221 f'socket modifier keyword arguments can not be used '
1222 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001223 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001224 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001225 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001226 if not (local_addr or remote_addr):
1227 if family == 0:
1228 raise ValueError('unexpected address family')
1229 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001230 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1231 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001232 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001233 raise TypeError('string is expected')
Quentin Dawans56065d42019-04-09 15:40:59 +02001234
1235 if local_addr and local_addr[0] not in (0, '\x00'):
1236 try:
1237 if stat.S_ISSOCK(os.stat(local_addr).st_mode):
1238 os.remove(local_addr)
1239 except FileNotFoundError:
1240 pass
1241 except OSError as err:
1242 # Directory may have permissions only to create socket.
1243 logger.error('Unable to check or remove stale UNIX '
1244 'socket %r: %r',
1245 local_addr, err)
1246
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001247 addr_pairs_info = (((family, proto),
1248 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001249 else:
1250 # join address by (family, protocol)
Inada Naokif3451702019-02-05 17:04:40 +09001251 addr_infos = {} # Using order preserving dict
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001252 for idx, addr in ((0, local_addr), (1, remote_addr)):
1253 if addr is not None:
1254 assert isinstance(addr, tuple) and len(addr) == 2, (
1255 '2-tuple is expected')
1256
Yury Selivanov19a44f62017-12-14 20:53:26 -05001257 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001258 addr, family=family, type=socket.SOCK_DGRAM,
1259 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001260 if not infos:
1261 raise OSError('getaddrinfo() returned empty list')
1262
1263 for fam, _, pro, _, address in infos:
1264 key = (fam, pro)
1265 if key not in addr_infos:
1266 addr_infos[key] = [None, None]
1267 addr_infos[key][idx] = address
1268
1269 # each addr has to have info for each (family, proto) pair
1270 addr_pairs_info = [
1271 (key, addr_pair) for key, addr_pair in addr_infos.items()
1272 if not ((local_addr and addr_pair[0] is None) or
1273 (remote_addr and addr_pair[1] is None))]
1274
1275 if not addr_pairs_info:
1276 raise ValueError('can not get address information')
1277
1278 exceptions = []
1279
1280 if reuse_address is None:
1281 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1282
1283 for ((family, proto),
1284 (local_address, remote_address)) in addr_pairs_info:
1285 sock = None
1286 r_addr = None
1287 try:
1288 sock = socket.socket(
1289 family=family, type=socket.SOCK_DGRAM, proto=proto)
1290 if reuse_address:
1291 sock.setsockopt(
1292 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1293 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001294 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001295 if allow_broadcast:
1296 sock.setsockopt(
1297 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1298 sock.setblocking(False)
1299
1300 if local_addr:
1301 sock.bind(local_address)
1302 if remote_addr:
Vincent Michel63deaa52019-05-07 19:18:49 +02001303 if not allow_broadcast:
1304 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001305 r_addr = remote_address
1306 except OSError as exc:
1307 if sock is not None:
1308 sock.close()
1309 exceptions.append(exc)
1310 except:
1311 if sock is not None:
1312 sock.close()
1313 raise
1314 else:
1315 break
1316 else:
1317 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001318
1319 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001320 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001321 transport = self._make_datagram_transport(
1322 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001323 if self._debug:
1324 if local_addr:
1325 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1326 "created: (%r, %r)",
1327 local_addr, remote_addr, transport, protocol)
1328 else:
1329 logger.debug("Datagram endpoint remote_addr=%r created: "
1330 "(%r, %r)",
1331 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001332
1333 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001334 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001335 except:
1336 transport.close()
1337 raise
1338
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001339 return transport, protocol
1340
Yury Selivanov19a44f62017-12-14 20:53:26 -05001341 async def _ensure_resolved(self, address, *,
1342 family=0, type=socket.SOCK_STREAM,
1343 proto=0, flags=0, loop):
1344 host, port = address[:2]
Erwan Le Papeac8eb8f2019-05-17 10:28:39 +02001345 info = _ipaddr_info(host, port, family, type, proto, *address[2:])
Yury Selivanov19a44f62017-12-14 20:53:26 -05001346 if info is not None:
1347 # "host" is already a resolved IP.
1348 return [info]
1349 else:
1350 return await loop.getaddrinfo(host, port, family=family, type=type,
1351 proto=proto, flags=flags)
1352
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001353 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001354 infos = await self._ensure_resolved((host, port), family=family,
1355 type=socket.SOCK_STREAM,
1356 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001357 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001358 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001359 return infos
1360
Neil Aspinallf7686c12017-12-19 19:45:42 +00001361 async def create_server(
1362 self, protocol_factory, host=None, port=None,
1363 *,
1364 family=socket.AF_UNSPEC,
1365 flags=socket.AI_PASSIVE,
1366 sock=None,
1367 backlog=100,
1368 ssl=None,
1369 reuse_address=None,
1370 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001371 ssl_handshake_timeout=None,
1372 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001373 """Create a TCP server.
1374
Yury Selivanov6370f342017-12-10 18:36:12 -05001375 The host parameter can be a string, in that case the TCP server is
1376 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001377
1378 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001379 the TCP server is bound to all hosts of the sequence. If a host
1380 appears multiple times (possibly indirectly e.g. when hostnames
1381 resolve to the same IP address), the server is only bound once to that
1382 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001383
Victor Stinneracdb7822014-07-14 18:33:40 +02001384 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001385
1386 This method is a coroutine.
1387 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001388 if isinstance(ssl, bool):
1389 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001390
1391 if ssl_handshake_timeout is not None and ssl is None:
1392 raise ValueError(
1393 'ssl_handshake_timeout is only meaningful with ssl')
1394
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001395 if host is not None or port is not None:
1396 if sock is not None:
1397 raise ValueError(
1398 'host/port and sock can not be specified at the same time')
1399
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001400 if reuse_address is None:
1401 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1402 sockets = []
1403 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001404 hosts = [None]
1405 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001406 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001407 hosts = [host]
1408 else:
1409 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001410
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001411 fs = [self._create_server_getaddrinfo(host, port, family=family,
1412 flags=flags)
1413 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001414 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001415 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001416
1417 completed = False
1418 try:
1419 for res in infos:
1420 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001421 try:
1422 sock = socket.socket(af, socktype, proto)
1423 except socket.error:
1424 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001425 if self._debug:
1426 logger.warning('create_server() failed to create '
1427 'socket.socket(%r, %r, %r)',
1428 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001429 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001430 sockets.append(sock)
1431 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001432 sock.setsockopt(
1433 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1434 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001435 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001436 # Disable IPv4/IPv6 dual stack support (enabled by
1437 # default on Linux) which makes a single socket
1438 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001439 if (_HAS_IPv6 and
1440 af == socket.AF_INET6 and
1441 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001442 sock.setsockopt(socket.IPPROTO_IPV6,
1443 socket.IPV6_V6ONLY,
1444 True)
1445 try:
1446 sock.bind(sa)
1447 except OSError as err:
1448 raise OSError(err.errno, 'error while attempting '
1449 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001450 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001451 completed = True
1452 finally:
1453 if not completed:
1454 for sock in sockets:
1455 sock.close()
1456 else:
1457 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001458 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001459 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001460 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001461 sockets = [sock]
1462
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001463 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001464 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001465
1466 server = Server(self, sockets, protocol_factory,
1467 ssl, backlog, ssl_handshake_timeout)
1468 if start_serving:
1469 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001470 # Skip one loop iteration so that all 'loop.add_reader'
1471 # go through.
1472 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001473
Victor Stinnere912e652014-07-12 03:11:53 +02001474 if self._debug:
1475 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001476 return server
1477
Neil Aspinallf7686c12017-12-19 19:45:42 +00001478 async def connect_accepted_socket(
1479 self, protocol_factory, sock,
1480 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001481 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001482 """Handle an accepted connection.
1483
1484 This is used by servers that accept connections outside of
1485 asyncio but that use asyncio to handle connections.
1486
1487 This method is a coroutine. When completed, the coroutine
1488 returns a (transport, protocol) pair.
1489 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001490 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001491 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001492
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001493 if ssl_handshake_timeout is not None and not ssl:
1494 raise ValueError(
1495 'ssl_handshake_timeout is only meaningful with ssl')
1496
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001497 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001498 sock, protocol_factory, ssl, '', server_side=True,
1499 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001500 if self._debug:
1501 # Get the socket from the transport because SSL transport closes
1502 # the old socket and creates a new SSL socket
1503 sock = transport.get_extra_info('socket')
1504 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1505 return transport, protocol
1506
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001507 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001508 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001509 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001510 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001511
1512 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001513 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001514 except:
1515 transport.close()
1516 raise
1517
Victor Stinneracdb7822014-07-14 18:33:40 +02001518 if self._debug:
1519 logger.debug('Read pipe %r connected: (%r, %r)',
1520 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001521 return transport, protocol
1522
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001523 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001524 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001525 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001526 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001527
1528 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001529 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001530 except:
1531 transport.close()
1532 raise
1533
Victor Stinneracdb7822014-07-14 18:33:40 +02001534 if self._debug:
1535 logger.debug('Write pipe %r connected: (%r, %r)',
1536 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001537 return transport, protocol
1538
Victor Stinneracdb7822014-07-14 18:33:40 +02001539 def _log_subprocess(self, msg, stdin, stdout, stderr):
1540 info = [msg]
1541 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001542 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001543 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001544 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001545 else:
1546 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001547 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001548 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001549 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001550 logger.debug(' '.join(info))
1551
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001552 async def subprocess_shell(self, protocol_factory, cmd, *,
1553 stdin=subprocess.PIPE,
1554 stdout=subprocess.PIPE,
1555 stderr=subprocess.PIPE,
1556 universal_newlines=False,
1557 shell=True, bufsize=0,
sbstpf0d4c642019-05-27 19:51:19 -04001558 encoding=None, errors=None, text=None,
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001559 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001560 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001561 raise ValueError("cmd must be a string")
1562 if universal_newlines:
1563 raise ValueError("universal_newlines must be False")
1564 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001565 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001566 if bufsize != 0:
1567 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001568 if text:
1569 raise ValueError("text must be False")
1570 if encoding is not None:
1571 raise ValueError("encoding must be None")
1572 if errors is not None:
1573 raise ValueError("errors must be None")
1574
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001575 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001576 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001577 if self._debug:
1578 # don't log parameters: they may contain sensitive information
1579 # (password) and may be too long
1580 debug_log = 'run shell command %r' % cmd
1581 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001582 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001583 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001584 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001585 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001586 return transport, protocol
1587
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001588 async def subprocess_exec(self, protocol_factory, program, *args,
1589 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1590 stderr=subprocess.PIPE, universal_newlines=False,
sbstpf0d4c642019-05-27 19:51:19 -04001591 shell=False, bufsize=0,
1592 encoding=None, errors=None, text=None,
1593 **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001594 if universal_newlines:
1595 raise ValueError("universal_newlines must be False")
1596 if shell:
1597 raise ValueError("shell must be False")
1598 if bufsize != 0:
1599 raise ValueError("bufsize must be 0")
sbstpf0d4c642019-05-27 19:51:19 -04001600 if text:
1601 raise ValueError("text must be False")
1602 if encoding is not None:
1603 raise ValueError("encoding must be None")
1604 if errors is not None:
1605 raise ValueError("errors must be None")
1606
Victor Stinner20e07432014-02-11 11:44:56 +01001607 popen_args = (program,) + args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001608 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001609 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001610 if self._debug:
1611 # don't log parameters: they may contain sensitive information
1612 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001613 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001614 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001615 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001616 protocol, popen_args, False, stdin, stdout, stderr,
1617 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001618 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001619 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001620 return transport, protocol
1621
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001622 def get_exception_handler(self):
1623 """Return an exception handler, or None if the default one is in use.
1624 """
1625 return self._exception_handler
1626
Yury Selivanov569efa22014-02-18 18:02:19 -05001627 def set_exception_handler(self, handler):
1628 """Set handler as the new event loop exception handler.
1629
1630 If handler is None, the default exception handler will
1631 be set.
1632
1633 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001634 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001635 will be a reference to the active event loop, 'context'
1636 will be a dict object (see `call_exception_handler()`
1637 documentation for details about context).
1638 """
1639 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001640 raise TypeError(f'A callable object or None is expected, '
1641 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001642 self._exception_handler = handler
1643
1644 def default_exception_handler(self, context):
1645 """Default exception handler.
1646
1647 This is called when an exception occurs and no exception
1648 handler is set, and can be called by a custom exception
1649 handler that wants to defer to the default behavior.
1650
Antoine Pitrou921e9432017-11-07 17:23:29 +01001651 This default handler logs the error message and other
1652 context-dependent information. In debug mode, a truncated
1653 stack trace is also appended showing where the given object
1654 (e.g. a handle or future or task) was created, if any.
1655
Victor Stinneracdb7822014-07-14 18:33:40 +02001656 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001657 `call_exception_handler()`.
1658 """
1659 message = context.get('message')
1660 if not message:
1661 message = 'Unhandled exception in event loop'
1662
1663 exception = context.get('exception')
1664 if exception is not None:
1665 exc_info = (type(exception), exception, exception.__traceback__)
1666 else:
1667 exc_info = False
1668
Yury Selivanov6370f342017-12-10 18:36:12 -05001669 if ('source_traceback' not in context and
1670 self._current_handle is not None and
1671 self._current_handle._source_traceback):
1672 context['handle_traceback'] = \
1673 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001674
Yury Selivanov569efa22014-02-18 18:02:19 -05001675 log_lines = [message]
1676 for key in sorted(context):
1677 if key in {'message', 'exception'}:
1678 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001679 value = context[key]
1680 if key == 'source_traceback':
1681 tb = ''.join(traceback.format_list(value))
1682 value = 'Object created at (most recent call last):\n'
1683 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001684 elif key == 'handle_traceback':
1685 tb = ''.join(traceback.format_list(value))
1686 value = 'Handle created at (most recent call last):\n'
1687 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001688 else:
1689 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001690 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001691
1692 logger.error('\n'.join(log_lines), exc_info=exc_info)
1693
1694 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001695 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001696
Victor Stinneracdb7822014-07-14 18:33:40 +02001697 The context argument is a dict containing the following keys:
1698
Yury Selivanov569efa22014-02-18 18:02:19 -05001699 - 'message': Error message;
1700 - 'exception' (optional): Exception object;
1701 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001702 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001703 - 'handle' (optional): Handle instance;
1704 - 'protocol' (optional): Protocol instance;
1705 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001706 - 'socket' (optional): Socket instance;
1707 - 'asyncgen' (optional): Asynchronous generator that caused
1708 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001709
Victor Stinneracdb7822014-07-14 18:33:40 +02001710 New keys maybe introduced in the future.
1711
1712 Note: do not overload this method in an event loop subclass.
1713 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001714 `set_exception_handler()` method.
1715 """
1716 if self._exception_handler is None:
1717 try:
1718 self.default_exception_handler(context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001719 except (SystemExit, KeyboardInterrupt):
1720 raise
1721 except BaseException:
Yury Selivanov569efa22014-02-18 18:02:19 -05001722 # Second protection layer for unexpected errors
1723 # in the default implementation, as well as for subclassed
1724 # event loops with overloaded "default_exception_handler".
1725 logger.error('Exception in default exception handler',
1726 exc_info=True)
1727 else:
1728 try:
1729 self._exception_handler(self, context)
Yury Selivanov431b5402019-05-27 14:45:12 +02001730 except (SystemExit, KeyboardInterrupt):
1731 raise
1732 except BaseException as exc:
Yury Selivanov569efa22014-02-18 18:02:19 -05001733 # Exception in the user set custom exception handler.
1734 try:
1735 # Let's try default handler.
1736 self.default_exception_handler({
1737 'message': 'Unhandled error in exception handler',
1738 'exception': exc,
1739 'context': context,
1740 })
Yury Selivanov431b5402019-05-27 14:45:12 +02001741 except (SystemExit, KeyboardInterrupt):
1742 raise
1743 except BaseException:
Victor Stinneracdb7822014-07-14 18:33:40 +02001744 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001745 # overloaded.
1746 logger.error('Exception in default exception handler '
1747 'while handling an unexpected error '
1748 'in custom exception handler',
1749 exc_info=True)
1750
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001751 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001752 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001753 assert isinstance(handle, events.Handle), 'A Handle is required here'
1754 if handle._cancelled:
1755 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001756 assert not isinstance(handle, events.TimerHandle)
1757 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001758
1759 def _add_callback_signalsafe(self, handle):
1760 """Like _add_callback() but called from a signal handler."""
1761 self._add_callback(handle)
1762 self._write_to_self()
1763
Yury Selivanov592ada92014-09-25 12:07:56 -04001764 def _timer_handle_cancelled(self, handle):
1765 """Notification that a TimerHandle has been cancelled."""
1766 if handle._scheduled:
1767 self._timer_cancelled_count += 1
1768
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001769 def _run_once(self):
1770 """Run one full iteration of the event loop.
1771
1772 This calls all currently ready callbacks, polls for I/O,
1773 schedules the resulting callbacks, and finally schedules
1774 'call_later' callbacks.
1775 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001776
Yury Selivanov592ada92014-09-25 12:07:56 -04001777 sched_count = len(self._scheduled)
1778 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1779 self._timer_cancelled_count / sched_count >
1780 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001781 # Remove delayed calls that were cancelled if their number
1782 # is too high
1783 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001784 for handle in self._scheduled:
1785 if handle._cancelled:
1786 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001787 else:
1788 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001789
Victor Stinner68da8fc2014-09-30 18:08:36 +02001790 heapq.heapify(new_scheduled)
1791 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001792 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001793 else:
1794 # Remove delayed calls that were cancelled from head of queue.
1795 while self._scheduled and self._scheduled[0]._cancelled:
1796 self._timer_cancelled_count -= 1
1797 handle = heapq.heappop(self._scheduled)
1798 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001799
1800 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001801 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001802 timeout = 0
1803 elif self._scheduled:
1804 # Compute the desired timeout.
1805 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001806 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001807
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001808 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001809 self._process_events(event_list)
1810
1811 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001812 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001813 while self._scheduled:
1814 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001815 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001816 break
1817 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001818 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001819 self._ready.append(handle)
1820
1821 # This is the only place where callbacks are actually *called*.
1822 # All other places just add them to ready.
1823 # Note: We run all currently scheduled callbacks, but not any
1824 # callbacks scheduled by callbacks run this time around --
1825 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001826 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001827 ntodo = len(self._ready)
1828 for i in range(ntodo):
1829 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001830 if handle._cancelled:
1831 continue
1832 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001833 try:
1834 self._current_handle = handle
1835 t0 = self.time()
1836 handle._run()
1837 dt = self.time() - t0
1838 if dt >= self.slow_callback_duration:
1839 logger.warning('Executing %s took %.3f seconds',
1840 _format_handle(handle), dt)
1841 finally:
1842 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001843 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001844 handle._run()
1845 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001846
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001847 def _set_coroutine_origin_tracking(self, enabled):
1848 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001849 return
1850
Yury Selivanove8944cb2015-05-12 11:43:04 -04001851 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001852 self._coroutine_origin_tracking_saved_depth = (
1853 sys.get_coroutine_origin_tracking_depth())
1854 sys.set_coroutine_origin_tracking_depth(
1855 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001856 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001857 sys.set_coroutine_origin_tracking_depth(
1858 self._coroutine_origin_tracking_saved_depth)
1859
1860 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001861
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001862 def get_debug(self):
1863 return self._debug
1864
1865 def set_debug(self, enabled):
1866 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001867
Yury Selivanove8944cb2015-05-12 11:43:04 -04001868 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001869 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)