blob: ca9eee765e3531a54df5934fb7c02db59c6f6c11 [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
19import heapq
Victor Stinner5e4a7d82015-09-21 18:33:43 +020020import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
24import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010025import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020027import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070028import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010029import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070030import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanovf111b3d2017-12-30 00:35:36 -050032try:
33 import ssl
34except ImportError: # pragma: no cover
35 ssl = None
36
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020038from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039from . import events
40from . import futures
Yury Selivanovf111b3d2017-12-30 00:35:36 -050041from . import sslproto
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042from . import tasks
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070043from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044
45
Yury Selivanov6370f342017-12-10 18:36:12 -050046__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070047
48
Yury Selivanov592ada92014-09-25 12:07:56 -040049# Minimum number of _scheduled timer handles before cleanup of
50# cancelled handles is performed.
51_MIN_SCHEDULED_TIMER_HANDLES = 100
52
53# Minimum fraction of _scheduled timer handles that are cancelled
54# before cleanup of cancelled handles is performed.
55_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070056
Victor Stinnerc94a93a2016-04-01 21:43:39 +020057# Exceptions which must not call the exception handler in fatal error
58# methods (_fatal_error())
59_FATAL_ERROR_IGNORE = (BrokenPipeError,
60 ConnectionResetError, ConnectionAbortedError)
61
62
Victor Stinner0e6f52a2014-06-20 17:34:15 +020063def _format_handle(handle):
64 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040065 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020066 # format the task
67 return repr(cb.__self__)
68 else:
69 return str(handle)
70
71
Victor Stinneracdb7822014-07-14 18:33:40 +020072def _format_pipe(fd):
73 if fd == subprocess.PIPE:
74 return '<pipe>'
75 elif fd == subprocess.STDOUT:
76 return '<stdout>'
77 else:
78 return repr(fd)
79
80
Yury Selivanov5587d7c2016-09-15 15:45:07 -040081def _set_reuseport(sock):
82 if not hasattr(socket, 'SO_REUSEPORT'):
83 raise ValueError('reuse_port not supported by socket module')
84 else:
85 try:
86 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
87 except OSError:
88 raise ValueError('reuse_port not supported by socket module, '
89 'SO_REUSEPORT defined but not implemented.')
90
91
Yury Selivanovd5c2a622015-12-16 19:31:17 -050092def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040093 # Try to skip getaddrinfo if "host" is already an IP. Users might have
94 # handled name resolution in their own code and pass in resolved IPs.
95 if not hasattr(socket, 'inet_pton'):
96 return
97
98 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
99 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500100 return None
101
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500102 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500103 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500104 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500105 proto = socket.IPPROTO_UDP
106 else:
107 return None
108
Yury Selivanova7146162016-06-02 16:51:07 -0400109 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400110 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700111 elif isinstance(port, bytes) and port == b'':
112 port = 0
113 elif isinstance(port, str) and port == '':
114 port = 0
115 else:
116 # If port's a service name like "http", don't skip getaddrinfo.
117 try:
118 port = int(port)
119 except (TypeError, ValueError):
120 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400121
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400122 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500123 afs = [socket.AF_INET]
124 if hasattr(socket, 'AF_INET6'):
125 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 else:
127 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500128
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400129 if isinstance(host, bytes):
130 host = host.decode('idna')
131 if '%' in host:
132 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
133 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500134 return None
135
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500137 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 socket.inet_pton(af, host)
139 # The host has already been resolved.
140 return af, type, proto, '', (host, port)
141 except OSError:
142 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500143
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400144 # "host" is not an IP address.
145 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500146
147
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100148def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500149 if not fut.cancelled():
150 exc = fut.exception()
151 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
152 # Issue #22429: run_forever() already finished, no need to
153 # stop it.
154 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500155 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100156
157
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700158class Server(events.AbstractServer):
159
160 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200161 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200163 self._active_count = 0
164 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700165
Victor Stinnere912e652014-07-12 03:11:53 +0200166 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500167 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200168
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200169 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200171 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700172
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200173 def _detach(self):
174 assert self._active_count > 0
175 self._active_count -= 1
176 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700177 self._wakeup()
178
179 def close(self):
180 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200181 if sockets is None:
182 return
183 self.sockets = None
184 for sock in sockets:
185 self._loop._stop_serving(sock)
186 if self._active_count == 0:
187 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530189 def get_loop(self):
190 return self._loop
191
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700192 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200193 waiters = self._waiters
194 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195 for waiter in waiters:
196 if not waiter.done():
197 waiter.set_result(waiter)
198
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200199 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200200 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700201 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400202 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200203 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200204 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700205
206
207class BaseEventLoop(events.AbstractEventLoop):
208
209 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400210 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200211 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800212 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 self._ready = collections.deque()
214 self._scheduled = []
215 self._default_executor = None
216 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100217 # Identifier of the thread running the event loop, or None if the
218 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100219 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100220 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500221 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800222 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200223 # In debug mode, if the execution of a callback or a step of a task
224 # exceed this duration in seconds, the slow callback/task is logged.
225 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100226 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400227 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800228 self._coroutine_origin_tracking_enabled = False
229 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700230
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500231 # A weak set of all asynchronous generators that are
232 # being iterated by the loop.
233 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700234 # Set to True when `loop.shutdown_asyncgens` is called.
235 self._asyncgens_shutdown_called = False
236
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200237 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500238 return (
239 f'<{self.__class__.__name__} running={self.is_running()} '
240 f'closed={self.is_closed()} debug={self.get_debug()}>'
241 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200242
Yury Selivanov7661db62016-05-16 15:38:39 -0400243 def create_future(self):
244 """Create a Future object attached to the loop."""
245 return futures.Future(loop=self)
246
Victor Stinner896a25a2014-07-08 11:29:25 +0200247 def create_task(self, coro):
248 """Schedule a coroutine object.
249
Victor Stinneracdb7822014-07-14 18:33:40 +0200250 Return a task object.
251 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100252 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400253 if self._task_factory is None:
254 task = tasks.Task(coro, loop=self)
255 if task._source_traceback:
256 del task._source_traceback[-1]
257 else:
258 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200259 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200260
Yury Selivanov740169c2015-05-11 14:23:38 -0400261 def set_task_factory(self, factory):
262 """Set a task factory that will be used by loop.create_task().
263
264 If factory is None the default task factory will be set.
265
266 If factory is a callable, it should have a signature matching
267 '(loop, coro)', where 'loop' will be a reference to the active
268 event loop, 'coro' will be a coroutine object. The callable
269 must return a Future.
270 """
271 if factory is not None and not callable(factory):
272 raise TypeError('task factory must be a callable or None')
273 self._task_factory = factory
274
275 def get_task_factory(self):
276 """Return a task factory, or None if the default one is in use."""
277 return self._task_factory
278
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279 def _make_socket_transport(self, sock, protocol, waiter=None, *,
280 extra=None, server=None):
281 """Create socket transport."""
282 raise NotImplementedError
283
Neil Aspinallf7686c12017-12-19 19:45:42 +0000284 def _make_ssl_transport(
285 self, rawsock, protocol, sslcontext, waiter=None,
286 *, server_side=False, server_hostname=None,
287 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500288 ssl_handshake_timeout=None,
289 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700290 """Create SSL transport."""
291 raise NotImplementedError
292
293 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200294 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700295 """Create datagram transport."""
296 raise NotImplementedError
297
298 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
299 extra=None):
300 """Create read pipe transport."""
301 raise NotImplementedError
302
303 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
304 extra=None):
305 """Create write pipe transport."""
306 raise NotImplementedError
307
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200308 async def _make_subprocess_transport(self, protocol, args, shell,
309 stdin, stdout, stderr, bufsize,
310 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311 """Create subprocess transport."""
312 raise NotImplementedError
313
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700314 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200315 """Write a byte to self-pipe, to wake up the event loop.
316
317 This may be called from a different thread.
318
319 The subclass is responsible for implementing the self-pipe.
320 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700321 raise NotImplementedError
322
323 def _process_events(self, event_list):
324 """Process selector events."""
325 raise NotImplementedError
326
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200327 def _check_closed(self):
328 if self._closed:
329 raise RuntimeError('Event loop is closed')
330
Yury Selivanoveb636452016-09-08 22:01:51 -0700331 def _asyncgen_finalizer_hook(self, agen):
332 self._asyncgens.discard(agen)
333 if not self.is_closed():
334 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400335 # Wake up the loop if the finalizer was called from
336 # a different thread.
337 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700338
339 def _asyncgen_firstiter_hook(self, agen):
340 if self._asyncgens_shutdown_called:
341 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500342 f"asynchronous generator {agen!r} was scheduled after "
343 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700344 ResourceWarning, source=self)
345
346 self._asyncgens.add(agen)
347
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200348 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700349 """Shutdown all active asynchronous generators."""
350 self._asyncgens_shutdown_called = True
351
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500352 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400353 # If Python version is <3.6 or we don't have any asynchronous
354 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700355 return
356
357 closing_agens = list(self._asyncgens)
358 self._asyncgens.clear()
359
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200360 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700361 *[ag.aclose() for ag in closing_agens],
362 return_exceptions=True,
363 loop=self)
364
Yury Selivanoveb636452016-09-08 22:01:51 -0700365 for result, agen in zip(results, closing_agens):
366 if isinstance(result, Exception):
367 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500368 'message': f'an error occurred during closing of '
369 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700370 'exception': result,
371 'asyncgen': agen
372 })
373
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700374 def run_forever(self):
375 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200376 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100377 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400378 raise RuntimeError('This event loop is already running')
379 if events._get_running_loop() is not None:
380 raise RuntimeError(
381 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800382 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100383 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500384
385 old_agen_hooks = sys.get_asyncgen_hooks()
386 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
387 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700388 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400389 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700390 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800391 self._run_once()
392 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700393 break
394 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800395 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100396 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400397 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800398 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500399 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700400
401 def run_until_complete(self, future):
402 """Run until the Future is done.
403
404 If the argument is a coroutine, it is wrapped in a Task.
405
Victor Stinneracdb7822014-07-14 18:33:40 +0200406 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700407 with the same coroutine twice -- it would wrap it in two
408 different Tasks and that can't be good.
409
410 Return the Future's result, or raise its exception.
411 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200412 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200413
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700414 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400415 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200416 if new_task:
417 # An exception is raised if the future didn't complete, so there
418 # is no need to log the "destroy pending task" message
419 future._log_destroy_pending = False
420
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100421 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200422 try:
423 self.run_forever()
424 except:
425 if new_task and future.done() and not future.cancelled():
426 # The coroutine raised a BaseException. Consume the exception
427 # to not log a warning, the caller doesn't have access to the
428 # local task.
429 future.exception()
430 raise
jimmylai21b3e042017-05-22 22:32:46 -0700431 finally:
432 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700433 if not future.done():
434 raise RuntimeError('Event loop stopped before Future completed.')
435
436 return future.result()
437
438 def stop(self):
439 """Stop running the event loop.
440
Guido van Rossum41f69f42015-11-19 13:28:47 -0800441 Every callback already scheduled will still run. This simply informs
442 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700443 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800444 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700445
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200446 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700447 """Close the event loop.
448
449 This clears the queues and shuts down the executor,
450 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200451
452 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700453 """
Victor Stinner956de692014-12-26 21:07:52 +0100454 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200455 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200456 if self._closed:
457 return
Victor Stinnere912e652014-07-12 03:11:53 +0200458 if self._debug:
459 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400460 self._closed = True
461 self._ready.clear()
462 self._scheduled.clear()
463 executor = self._default_executor
464 if executor is not None:
465 self._default_executor = None
466 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200467
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200468 def is_closed(self):
469 """Returns True if the event loop was closed."""
470 return self._closed
471
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900472 def __del__(self):
473 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500474 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900475 source=self)
476 if not self.is_running():
477 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100478
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200480 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100481 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700482
483 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200484 """Return the time according to the event loop's clock.
485
486 This is a float expressed in seconds since an epoch, but the
487 epoch, precision, accuracy and drift are unspecified and may
488 differ per event loop.
489 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 return time.monotonic()
491
492 def call_later(self, delay, callback, *args):
493 """Arrange for a callback to be called at a given time.
494
495 Return a Handle: an opaque object with a cancel() method that
496 can be used to cancel the call.
497
498 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200499 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500
501 Each callback will be called exactly once. If two callbacks
502 are scheduled for exactly the same time, it undefined which
503 will be called first.
504
505 Any positional arguments after the callback will be passed to
506 the callback when it is called.
507 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200508 timer = self.call_at(self.time() + delay, callback, *args)
509 if timer._source_traceback:
510 del timer._source_traceback[-1]
511 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700512
513 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200514 """Like call_later(), but uses an absolute time.
515
516 Absolute time corresponds to the event loop's time() method.
517 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100518 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100519 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100520 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700521 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500522 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200523 if timer._source_traceback:
524 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400526 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700527 return timer
528
529 def call_soon(self, callback, *args):
530 """Arrange for a callback to be called as soon as possible.
531
Victor Stinneracdb7822014-07-14 18:33:40 +0200532 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 order in which they are registered. Each callback will be
534 called exactly once.
535
536 Any positional arguments after the callback will be passed to
537 the callback when it is called.
538 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700539 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100540 if self._debug:
541 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700542 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100543 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200544 if handle._source_traceback:
545 del handle._source_traceback[-1]
546 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100547
Yury Selivanov491a9122016-11-03 15:09:24 -0700548 def _check_callback(self, callback, method):
549 if (coroutines.iscoroutine(callback) or
550 coroutines.iscoroutinefunction(callback)):
551 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500552 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700553 if not callable(callback):
554 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500555 f'a callable object was expected by {method}(), '
556 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700557
Victor Stinner956de692014-12-26 21:07:52 +0100558 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500559 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200560 if handle._source_traceback:
561 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562 self._ready.append(handle)
563 return handle
564
Victor Stinner956de692014-12-26 21:07:52 +0100565 def _check_thread(self):
566 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100567
Victor Stinneracdb7822014-07-14 18:33:40 +0200568 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100569 likely behave incorrectly when the assumption is violated.
570
Victor Stinneracdb7822014-07-14 18:33:40 +0200571 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100572 responsible for checking this condition for performance reasons.
573 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100574 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200575 return
Victor Stinner956de692014-12-26 21:07:52 +0100576 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100577 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100578 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200579 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100580 "than the current one")
581
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700582 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200583 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700584 self._check_closed()
585 if self._debug:
586 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100587 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200588 if handle._source_traceback:
589 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700590 self._write_to_self()
591 return handle
592
Yury Selivanov19a44f62017-12-14 20:53:26 -0500593 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100594 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700595 if self._debug:
596 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700597 if executor is None:
598 executor = self._default_executor
599 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400600 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500602 return await futures.wrap_future(
603 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700604
605 def set_default_executor(self, executor):
606 self._default_executor = executor
607
Victor Stinnere912e652014-07-12 03:11:53 +0200608 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500609 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200610 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500611 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200612 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500613 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200614 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500615 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200616 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500617 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200618 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200619 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200620
621 t0 = self.time()
622 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
623 dt = self.time() - t0
624
Yury Selivanov6370f342017-12-10 18:36:12 -0500625 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200626 if dt >= self.slow_callback_duration:
627 logger.info(msg)
628 else:
629 logger.debug(msg)
630 return addrinfo
631
Yury Selivanov19a44f62017-12-14 20:53:26 -0500632 async def getaddrinfo(self, host, port, *,
633 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400634 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500635 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200636 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500637 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700638
Yury Selivanov19a44f62017-12-14 20:53:26 -0500639 return await self.run_in_executor(
640 None, getaddr_func, host, port, family, type, proto, flags)
641
642 async def getnameinfo(self, sockaddr, flags=0):
643 return await self.run_in_executor(
644 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700645
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200646 async def sock_sendfile(self, sock, file, offset=0, count=None,
647 *, fallback=True):
648 if self._debug and sock.gettimeout() != 0:
649 raise ValueError("the socket must be non-blocking")
650 self._check_sendfile_params(sock, file, offset, count)
651 try:
652 return await self._sock_sendfile_native(sock, file,
653 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200654 except events.SendfileNotAvailableError as exc:
655 if not fallback:
656 raise
657 return await self._sock_sendfile_fallback(sock, file,
658 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200659
660 async def _sock_sendfile_native(self, sock, file, offset, count):
661 # NB: sendfile syscall is not supported for SSL sockets and
662 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200663 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200664 f"syscall sendfile is not available for socket {sock!r} "
665 "and file {file!r} combination")
666
667 async def _sock_sendfile_fallback(self, sock, file, offset, count):
668 if offset:
669 file.seek(offset)
670 blocksize = min(count, 16384) if count else 16384
671 buf = bytearray(blocksize)
672 total_sent = 0
673 try:
674 while True:
675 if count:
676 blocksize = min(count - total_sent, blocksize)
677 if blocksize <= 0:
678 break
679 view = memoryview(buf)[:blocksize]
680 read = file.readinto(view)
681 if not read:
682 break # EOF
683 await self.sock_sendall(sock, view)
684 total_sent += read
685 return total_sent
686 finally:
687 if total_sent > 0 and hasattr(file, 'seek'):
688 file.seek(offset + total_sent)
689
690 def _check_sendfile_params(self, sock, file, offset, count):
691 if 'b' not in getattr(file, 'mode', 'b'):
692 raise ValueError("file should be opened in binary mode")
693 if not sock.type == socket.SOCK_STREAM:
694 raise ValueError("only SOCK_STREAM type sockets are supported")
695 if count is not None:
696 if not isinstance(count, int):
697 raise TypeError(
698 "count must be a positive integer (got {!r})".format(count))
699 if count <= 0:
700 raise ValueError(
701 "count must be a positive integer (got {!r})".format(count))
702 if not isinstance(offset, int):
703 raise TypeError(
704 "offset must be a non-negative integer (got {!r})".format(
705 offset))
706 if offset < 0:
707 raise ValueError(
708 "offset must be a non-negative integer (got {!r})".format(
709 offset))
710
Neil Aspinallf7686c12017-12-19 19:45:42 +0000711 async def create_connection(
712 self, protocol_factory, host=None, port=None,
713 *, ssl=None, family=0,
714 proto=0, flags=0, sock=None,
715 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200716 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200717 """Connect to a TCP server.
718
719 Create a streaming transport connection to a given Internet host and
720 port: socket family AF_INET or socket.AF_INET6 depending on host (or
721 family if specified), socket type SOCK_STREAM. protocol_factory must be
722 a callable returning a protocol instance.
723
724 This method is a coroutine which will try to establish the connection
725 in the background. When successful, the coroutine returns a
726 (transport, protocol) pair.
727 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700728 if server_hostname is not None and not ssl:
729 raise ValueError('server_hostname is only meaningful with ssl')
730
731 if server_hostname is None and ssl:
732 # Use host as default for server_hostname. It is an error
733 # if host is empty or not set, e.g. when an
734 # already-connected socket was passed or when only a port
735 # is given. To avoid this error, you can pass
736 # server_hostname='' -- this will bypass the hostname
737 # check. (This also means that if host is a numeric
738 # IP/IPv6 address, we will attempt to verify that exact
739 # address; this will probably fail, but it is possible to
740 # create a certificate for a specific IP address, so we
741 # don't judge it here.)
742 if not host:
743 raise ValueError('You must set server_hostname '
744 'when using ssl without a host')
745 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700746
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200747 if ssl_handshake_timeout is not None and not ssl:
748 raise ValueError(
749 'ssl_handshake_timeout is only meaningful with ssl')
750
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700751 if host is not None or port is not None:
752 if sock is not None:
753 raise ValueError(
754 'host/port and sock can not be specified at the same time')
755
Yury Selivanov19a44f62017-12-14 20:53:26 -0500756 infos = await self._ensure_resolved(
757 (host, port), family=family,
758 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700759 if not infos:
760 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500761
762 if local_addr is not None:
763 laddr_infos = await self._ensure_resolved(
764 local_addr, family=family,
765 type=socket.SOCK_STREAM, proto=proto,
766 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700767 if not laddr_infos:
768 raise OSError('getaddrinfo() returned empty list')
769
770 exceptions = []
771 for family, type, proto, cname, address in infos:
772 try:
773 sock = socket.socket(family=family, type=type, proto=proto)
774 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500775 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700776 for _, _, _, _, laddr in laddr_infos:
777 try:
778 sock.bind(laddr)
779 break
780 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500781 msg = (
782 f'error while attempting to bind on '
783 f'address {laddr!r}: '
784 f'{exc.strerror.lower()}'
785 )
786 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700787 exceptions.append(exc)
788 else:
789 sock.close()
790 sock = None
791 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200792 if self._debug:
793 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200794 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700795 except OSError as exc:
796 if sock is not None:
797 sock.close()
798 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200799 except:
800 if sock is not None:
801 sock.close()
802 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700803 else:
804 break
805 else:
806 if len(exceptions) == 1:
807 raise exceptions[0]
808 else:
809 # If they all have the same str(), raise one.
810 model = str(exceptions[0])
811 if all(str(exc) == model for exc in exceptions):
812 raise exceptions[0]
813 # Raise a combined exception so the user can see all
814 # the various error messages.
815 raise OSError('Multiple exceptions: {}'.format(
816 ', '.join(str(exc) for exc in exceptions)))
817
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500818 else:
819 if sock is None:
820 raise ValueError(
821 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500822 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500823 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
824 # are SOCK_STREAM.
825 # We support passing AF_UNIX sockets even though we have
826 # a dedicated API for that: create_unix_connection.
827 # Disallowing AF_UNIX in this method, breaks backwards
828 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500829 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500830 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700831
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200832 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000833 sock, protocol_factory, ssl, server_hostname,
834 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200835 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200836 # Get the socket from the transport because SSL transport closes
837 # the old socket and creates a new SSL socket
838 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200839 logger.debug("%r connected to %s:%r: (%r, %r)",
840 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500841 return transport, protocol
842
Neil Aspinallf7686c12017-12-19 19:45:42 +0000843 async def _create_connection_transport(
844 self, sock, protocol_factory, ssl,
845 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200846 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400847
848 sock.setblocking(False)
849
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700850 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400851 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700852 if ssl:
853 sslcontext = None if isinstance(ssl, bool) else ssl
854 transport = self._make_ssl_transport(
855 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000856 server_side=server_side, server_hostname=server_hostname,
857 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700858 else:
859 transport = self._make_socket_transport(sock, protocol, waiter)
860
Victor Stinner29ad0112015-01-15 00:04:21 +0100861 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200862 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100863 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100864 transport.close()
865 raise
866
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700867 return transport, protocol
868
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500869 async def start_tls(self, transport, protocol, sslcontext, *,
870 server_side=False,
871 server_hostname=None,
872 ssl_handshake_timeout=None):
873 """Upgrade transport to TLS.
874
875 Return a new transport that *protocol* should start using
876 immediately.
877 """
878 if ssl is None:
879 raise RuntimeError('Python ssl module is not available')
880
881 if not isinstance(sslcontext, ssl.SSLContext):
882 raise TypeError(
883 f'sslcontext is expected to be an instance of ssl.SSLContext, '
884 f'got {sslcontext!r}')
885
886 if not getattr(transport, '_start_tls_compatible', False):
887 raise TypeError(
888 f'transport {self!r} is not supported by start_tls()')
889
890 waiter = self.create_future()
891 ssl_protocol = sslproto.SSLProtocol(
892 self, protocol, sslcontext, waiter,
893 server_side, server_hostname,
894 ssl_handshake_timeout=ssl_handshake_timeout,
895 call_connection_made=False)
896
897 transport.set_protocol(ssl_protocol)
898 self.call_soon(ssl_protocol.connection_made, transport)
899 if not transport.is_reading():
900 self.call_soon(transport.resume_reading)
901
902 await waiter
903 return ssl_protocol._app_transport
904
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200905 async def create_datagram_endpoint(self, protocol_factory,
906 local_addr=None, remote_addr=None, *,
907 family=0, proto=0, flags=0,
908 reuse_address=None, reuse_port=None,
909 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700910 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700911 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500912 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500913 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500914 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700915 if (local_addr or remote_addr or
916 family or proto or flags or
917 reuse_address or reuse_port or allow_broadcast):
918 # show the problematic kwargs in exception msg
919 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
920 family=family, proto=proto, flags=flags,
921 reuse_address=reuse_address, reuse_port=reuse_port,
922 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500923 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700924 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500925 f'socket modifier keyword arguments can not be used '
926 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700927 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700928 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700929 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700930 if not (local_addr or remote_addr):
931 if family == 0:
932 raise ValueError('unexpected address family')
933 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100934 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
935 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100936 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100937 raise TypeError('string is expected')
938 addr_pairs_info = (((family, proto),
939 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700940 else:
941 # join address by (family, protocol)
942 addr_infos = collections.OrderedDict()
943 for idx, addr in ((0, local_addr), (1, remote_addr)):
944 if addr is not None:
945 assert isinstance(addr, tuple) and len(addr) == 2, (
946 '2-tuple is expected')
947
Yury Selivanov19a44f62017-12-14 20:53:26 -0500948 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400949 addr, family=family, type=socket.SOCK_DGRAM,
950 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700951 if not infos:
952 raise OSError('getaddrinfo() returned empty list')
953
954 for fam, _, pro, _, address in infos:
955 key = (fam, pro)
956 if key not in addr_infos:
957 addr_infos[key] = [None, None]
958 addr_infos[key][idx] = address
959
960 # each addr has to have info for each (family, proto) pair
961 addr_pairs_info = [
962 (key, addr_pair) for key, addr_pair in addr_infos.items()
963 if not ((local_addr and addr_pair[0] is None) or
964 (remote_addr and addr_pair[1] is None))]
965
966 if not addr_pairs_info:
967 raise ValueError('can not get address information')
968
969 exceptions = []
970
971 if reuse_address is None:
972 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
973
974 for ((family, proto),
975 (local_address, remote_address)) in addr_pairs_info:
976 sock = None
977 r_addr = None
978 try:
979 sock = socket.socket(
980 family=family, type=socket.SOCK_DGRAM, proto=proto)
981 if reuse_address:
982 sock.setsockopt(
983 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
984 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400985 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700986 if allow_broadcast:
987 sock.setsockopt(
988 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
989 sock.setblocking(False)
990
991 if local_addr:
992 sock.bind(local_address)
993 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200994 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700995 r_addr = remote_address
996 except OSError as exc:
997 if sock is not None:
998 sock.close()
999 exceptions.append(exc)
1000 except:
1001 if sock is not None:
1002 sock.close()
1003 raise
1004 else:
1005 break
1006 else:
1007 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001008
1009 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001010 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001011 transport = self._make_datagram_transport(
1012 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001013 if self._debug:
1014 if local_addr:
1015 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1016 "created: (%r, %r)",
1017 local_addr, remote_addr, transport, protocol)
1018 else:
1019 logger.debug("Datagram endpoint remote_addr=%r created: "
1020 "(%r, %r)",
1021 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001022
1023 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001024 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001025 except:
1026 transport.close()
1027 raise
1028
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001029 return transport, protocol
1030
Yury Selivanov19a44f62017-12-14 20:53:26 -05001031 async def _ensure_resolved(self, address, *,
1032 family=0, type=socket.SOCK_STREAM,
1033 proto=0, flags=0, loop):
1034 host, port = address[:2]
1035 info = _ipaddr_info(host, port, family, type, proto)
1036 if info is not None:
1037 # "host" is already a resolved IP.
1038 return [info]
1039 else:
1040 return await loop.getaddrinfo(host, port, family=family, type=type,
1041 proto=proto, flags=flags)
1042
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001043 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001044 infos = await self._ensure_resolved((host, port), family=family,
1045 type=socket.SOCK_STREAM,
1046 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001047 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001048 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001049 return infos
1050
Neil Aspinallf7686c12017-12-19 19:45:42 +00001051 async def create_server(
1052 self, protocol_factory, host=None, port=None,
1053 *,
1054 family=socket.AF_UNSPEC,
1055 flags=socket.AI_PASSIVE,
1056 sock=None,
1057 backlog=100,
1058 ssl=None,
1059 reuse_address=None,
1060 reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001061 ssl_handshake_timeout=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001062 """Create a TCP server.
1063
Yury Selivanov6370f342017-12-10 18:36:12 -05001064 The host parameter can be a string, in that case the TCP server is
1065 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001066
1067 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001068 the TCP server is bound to all hosts of the sequence. If a host
1069 appears multiple times (possibly indirectly e.g. when hostnames
1070 resolve to the same IP address), the server is only bound once to that
1071 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001072
Victor Stinneracdb7822014-07-14 18:33:40 +02001073 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001074
1075 This method is a coroutine.
1076 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001077 if isinstance(ssl, bool):
1078 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001079
1080 if ssl_handshake_timeout is not None and ssl is None:
1081 raise ValueError(
1082 'ssl_handshake_timeout is only meaningful with ssl')
1083
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001084 if host is not None or port is not None:
1085 if sock is not None:
1086 raise ValueError(
1087 'host/port and sock can not be specified at the same time')
1088
1089 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1090 if reuse_address is None:
1091 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1092 sockets = []
1093 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001094 hosts = [None]
1095 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001096 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001097 hosts = [host]
1098 else:
1099 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001100
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001101 fs = [self._create_server_getaddrinfo(host, port, family=family,
1102 flags=flags)
1103 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001104 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001105 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001106
1107 completed = False
1108 try:
1109 for res in infos:
1110 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001111 try:
1112 sock = socket.socket(af, socktype, proto)
1113 except socket.error:
1114 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001115 if self._debug:
1116 logger.warning('create_server() failed to create '
1117 'socket.socket(%r, %r, %r)',
1118 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001119 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001120 sockets.append(sock)
1121 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001122 sock.setsockopt(
1123 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1124 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001125 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001126 # Disable IPv4/IPv6 dual stack support (enabled by
1127 # default on Linux) which makes a single socket
1128 # listen on both address families.
1129 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1130 sock.setsockopt(socket.IPPROTO_IPV6,
1131 socket.IPV6_V6ONLY,
1132 True)
1133 try:
1134 sock.bind(sa)
1135 except OSError as err:
1136 raise OSError(err.errno, 'error while attempting '
1137 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001138 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001139 completed = True
1140 finally:
1141 if not completed:
1142 for sock in sockets:
1143 sock.close()
1144 else:
1145 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001146 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001147 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001148 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001149 sockets = [sock]
1150
1151 server = Server(self, sockets)
1152 for sock in sockets:
1153 sock.listen(backlog)
1154 sock.setblocking(False)
Neil Aspinallf7686c12017-12-19 19:45:42 +00001155 self._start_serving(protocol_factory, sock, ssl, server, backlog,
1156 ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001157 if self._debug:
1158 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001159 return server
1160
Neil Aspinallf7686c12017-12-19 19:45:42 +00001161 async def connect_accepted_socket(
1162 self, protocol_factory, sock,
1163 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001164 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001165 """Handle an accepted connection.
1166
1167 This is used by servers that accept connections outside of
1168 asyncio but that use asyncio to handle connections.
1169
1170 This method is a coroutine. When completed, the coroutine
1171 returns a (transport, protocol) pair.
1172 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001173 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001174 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001175
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001176 if ssl_handshake_timeout is not None and not ssl:
1177 raise ValueError(
1178 'ssl_handshake_timeout is only meaningful with ssl')
1179
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001180 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001181 sock, protocol_factory, ssl, '', server_side=True,
1182 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001183 if self._debug:
1184 # Get the socket from the transport because SSL transport closes
1185 # the old socket and creates a new SSL socket
1186 sock = transport.get_extra_info('socket')
1187 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1188 return transport, protocol
1189
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001190 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001191 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001192 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001193 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001194
1195 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001196 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001197 except:
1198 transport.close()
1199 raise
1200
Victor Stinneracdb7822014-07-14 18:33:40 +02001201 if self._debug:
1202 logger.debug('Read pipe %r connected: (%r, %r)',
1203 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001204 return transport, protocol
1205
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001206 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001207 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001208 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001209 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001210
1211 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001212 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001213 except:
1214 transport.close()
1215 raise
1216
Victor Stinneracdb7822014-07-14 18:33:40 +02001217 if self._debug:
1218 logger.debug('Write pipe %r connected: (%r, %r)',
1219 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001220 return transport, protocol
1221
Victor Stinneracdb7822014-07-14 18:33:40 +02001222 def _log_subprocess(self, msg, stdin, stdout, stderr):
1223 info = [msg]
1224 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001225 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001226 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001227 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001228 else:
1229 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001230 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001231 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001232 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001233 logger.debug(' '.join(info))
1234
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001235 async def subprocess_shell(self, protocol_factory, cmd, *,
1236 stdin=subprocess.PIPE,
1237 stdout=subprocess.PIPE,
1238 stderr=subprocess.PIPE,
1239 universal_newlines=False,
1240 shell=True, bufsize=0,
1241 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001242 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001243 raise ValueError("cmd must be a string")
1244 if universal_newlines:
1245 raise ValueError("universal_newlines must be False")
1246 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001247 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001248 if bufsize != 0:
1249 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001250 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001251 if self._debug:
1252 # don't log parameters: they may contain sensitive information
1253 # (password) and may be too long
1254 debug_log = 'run shell command %r' % cmd
1255 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001256 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001257 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001258 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001259 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001260 return transport, protocol
1261
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001262 async def subprocess_exec(self, protocol_factory, program, *args,
1263 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1264 stderr=subprocess.PIPE, universal_newlines=False,
1265 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001266 if universal_newlines:
1267 raise ValueError("universal_newlines must be False")
1268 if shell:
1269 raise ValueError("shell must be False")
1270 if bufsize != 0:
1271 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001272 popen_args = (program,) + args
1273 for arg in popen_args:
1274 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001275 raise TypeError(
1276 f"program arguments must be a bytes or text string, "
1277 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001278 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001279 if self._debug:
1280 # don't log parameters: they may contain sensitive information
1281 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001282 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001283 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001284 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001285 protocol, popen_args, False, stdin, stdout, stderr,
1286 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001287 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001288 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001289 return transport, protocol
1290
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001291 def get_exception_handler(self):
1292 """Return an exception handler, or None if the default one is in use.
1293 """
1294 return self._exception_handler
1295
Yury Selivanov569efa22014-02-18 18:02:19 -05001296 def set_exception_handler(self, handler):
1297 """Set handler as the new event loop exception handler.
1298
1299 If handler is None, the default exception handler will
1300 be set.
1301
1302 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001303 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001304 will be a reference to the active event loop, 'context'
1305 will be a dict object (see `call_exception_handler()`
1306 documentation for details about context).
1307 """
1308 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001309 raise TypeError(f'A callable object or None is expected, '
1310 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001311 self._exception_handler = handler
1312
1313 def default_exception_handler(self, context):
1314 """Default exception handler.
1315
1316 This is called when an exception occurs and no exception
1317 handler is set, and can be called by a custom exception
1318 handler that wants to defer to the default behavior.
1319
Antoine Pitrou921e9432017-11-07 17:23:29 +01001320 This default handler logs the error message and other
1321 context-dependent information. In debug mode, a truncated
1322 stack trace is also appended showing where the given object
1323 (e.g. a handle or future or task) was created, if any.
1324
Victor Stinneracdb7822014-07-14 18:33:40 +02001325 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001326 `call_exception_handler()`.
1327 """
1328 message = context.get('message')
1329 if not message:
1330 message = 'Unhandled exception in event loop'
1331
1332 exception = context.get('exception')
1333 if exception is not None:
1334 exc_info = (type(exception), exception, exception.__traceback__)
1335 else:
1336 exc_info = False
1337
Yury Selivanov6370f342017-12-10 18:36:12 -05001338 if ('source_traceback' not in context and
1339 self._current_handle is not None and
1340 self._current_handle._source_traceback):
1341 context['handle_traceback'] = \
1342 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001343
Yury Selivanov569efa22014-02-18 18:02:19 -05001344 log_lines = [message]
1345 for key in sorted(context):
1346 if key in {'message', 'exception'}:
1347 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001348 value = context[key]
1349 if key == 'source_traceback':
1350 tb = ''.join(traceback.format_list(value))
1351 value = 'Object created at (most recent call last):\n'
1352 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001353 elif key == 'handle_traceback':
1354 tb = ''.join(traceback.format_list(value))
1355 value = 'Handle created at (most recent call last):\n'
1356 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001357 else:
1358 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001359 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001360
1361 logger.error('\n'.join(log_lines), exc_info=exc_info)
1362
1363 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001364 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001365
Victor Stinneracdb7822014-07-14 18:33:40 +02001366 The context argument is a dict containing the following keys:
1367
Yury Selivanov569efa22014-02-18 18:02:19 -05001368 - 'message': Error message;
1369 - 'exception' (optional): Exception object;
1370 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001371 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001372 - 'handle' (optional): Handle instance;
1373 - 'protocol' (optional): Protocol instance;
1374 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001375 - 'socket' (optional): Socket instance;
1376 - 'asyncgen' (optional): Asynchronous generator that caused
1377 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001378
Victor Stinneracdb7822014-07-14 18:33:40 +02001379 New keys maybe introduced in the future.
1380
1381 Note: do not overload this method in an event loop subclass.
1382 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001383 `set_exception_handler()` method.
1384 """
1385 if self._exception_handler is None:
1386 try:
1387 self.default_exception_handler(context)
1388 except Exception:
1389 # Second protection layer for unexpected errors
1390 # in the default implementation, as well as for subclassed
1391 # event loops with overloaded "default_exception_handler".
1392 logger.error('Exception in default exception handler',
1393 exc_info=True)
1394 else:
1395 try:
1396 self._exception_handler(self, context)
1397 except Exception as exc:
1398 # Exception in the user set custom exception handler.
1399 try:
1400 # Let's try default handler.
1401 self.default_exception_handler({
1402 'message': 'Unhandled error in exception handler',
1403 'exception': exc,
1404 'context': context,
1405 })
1406 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001407 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001408 # overloaded.
1409 logger.error('Exception in default exception handler '
1410 'while handling an unexpected error '
1411 'in custom exception handler',
1412 exc_info=True)
1413
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001414 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001415 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001416 assert isinstance(handle, events.Handle), 'A Handle is required here'
1417 if handle._cancelled:
1418 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001419 assert not isinstance(handle, events.TimerHandle)
1420 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001421
1422 def _add_callback_signalsafe(self, handle):
1423 """Like _add_callback() but called from a signal handler."""
1424 self._add_callback(handle)
1425 self._write_to_self()
1426
Yury Selivanov592ada92014-09-25 12:07:56 -04001427 def _timer_handle_cancelled(self, handle):
1428 """Notification that a TimerHandle has been cancelled."""
1429 if handle._scheduled:
1430 self._timer_cancelled_count += 1
1431
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001432 def _run_once(self):
1433 """Run one full iteration of the event loop.
1434
1435 This calls all currently ready callbacks, polls for I/O,
1436 schedules the resulting callbacks, and finally schedules
1437 'call_later' callbacks.
1438 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001439
Yury Selivanov592ada92014-09-25 12:07:56 -04001440 sched_count = len(self._scheduled)
1441 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1442 self._timer_cancelled_count / sched_count >
1443 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001444 # Remove delayed calls that were cancelled if their number
1445 # is too high
1446 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001447 for handle in self._scheduled:
1448 if handle._cancelled:
1449 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001450 else:
1451 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001452
Victor Stinner68da8fc2014-09-30 18:08:36 +02001453 heapq.heapify(new_scheduled)
1454 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001455 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001456 else:
1457 # Remove delayed calls that were cancelled from head of queue.
1458 while self._scheduled and self._scheduled[0]._cancelled:
1459 self._timer_cancelled_count -= 1
1460 handle = heapq.heappop(self._scheduled)
1461 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001462
1463 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001464 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001465 timeout = 0
1466 elif self._scheduled:
1467 # Compute the desired timeout.
1468 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001469 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001470
Victor Stinner770e48d2014-07-11 11:58:33 +02001471 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001472 t0 = self.time()
1473 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001474 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001475 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001476 level = logging.INFO
1477 else:
1478 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001479 nevent = len(event_list)
1480 if timeout is None:
1481 logger.log(level, 'poll took %.3f ms: %s events',
1482 dt * 1e3, nevent)
1483 elif nevent:
1484 logger.log(level,
1485 'poll %.3f ms took %.3f ms: %s events',
1486 timeout * 1e3, dt * 1e3, nevent)
1487 elif dt >= 1.0:
1488 logger.log(level,
1489 'poll %.3f ms took %.3f ms: timeout',
1490 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001491 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001492 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001493 self._process_events(event_list)
1494
1495 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001496 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001497 while self._scheduled:
1498 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001499 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001500 break
1501 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001502 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001503 self._ready.append(handle)
1504
1505 # This is the only place where callbacks are actually *called*.
1506 # All other places just add them to ready.
1507 # Note: We run all currently scheduled callbacks, but not any
1508 # callbacks scheduled by callbacks run this time around --
1509 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001510 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001511 ntodo = len(self._ready)
1512 for i in range(ntodo):
1513 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001514 if handle._cancelled:
1515 continue
1516 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001517 try:
1518 self._current_handle = handle
1519 t0 = self.time()
1520 handle._run()
1521 dt = self.time() - t0
1522 if dt >= self.slow_callback_duration:
1523 logger.warning('Executing %s took %.3f seconds',
1524 _format_handle(handle), dt)
1525 finally:
1526 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001527 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001528 handle._run()
1529 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001530
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001531 def _set_coroutine_origin_tracking(self, enabled):
1532 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001533 return
1534
Yury Selivanove8944cb2015-05-12 11:43:04 -04001535 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001536 self._coroutine_origin_tracking_saved_depth = (
1537 sys.get_coroutine_origin_tracking_depth())
1538 sys.set_coroutine_origin_tracking_depth(
1539 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001540 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001541 sys.set_coroutine_origin_tracking_depth(
1542 self._coroutine_origin_tracking_saved_depth)
1543
1544 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001545
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001546 def get_debug(self):
1547 return self._debug
1548
1549 def set_debug(self, enabled):
1550 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001551
Yury Selivanove8944cb2015-05-12 11:43:04 -04001552 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001553 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)