blob: ab002319c18edc0db3ee1bb34ace6391fe317ed0 [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
Victor Stinnerf951d282014-06-29 00:46:45 +020037from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070038from . import events
39from . import futures
Yury Selivanovf111b3d2017-12-30 00:35:36 -050040from . import sslproto
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070041from . import tasks
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070042from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070043
44
Yury Selivanov6370f342017-12-10 18:36:12 -050045__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046
47
Yury Selivanov592ada92014-09-25 12:07:56 -040048# Minimum number of _scheduled timer handles before cleanup of
49# cancelled handles is performed.
50_MIN_SCHEDULED_TIMER_HANDLES = 100
51
52# Minimum fraction of _scheduled timer handles that are cancelled
53# before cleanup of cancelled handles is performed.
54_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070055
Victor Stinnerc94a93a2016-04-01 21:43:39 +020056# Exceptions which must not call the exception handler in fatal error
57# methods (_fatal_error())
58_FATAL_ERROR_IGNORE = (BrokenPipeError,
59 ConnectionResetError, ConnectionAbortedError)
60
61
Victor Stinner0e6f52a2014-06-20 17:34:15 +020062def _format_handle(handle):
63 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040064 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020065 # format the task
66 return repr(cb.__self__)
67 else:
68 return str(handle)
69
70
Victor Stinneracdb7822014-07-14 18:33:40 +020071def _format_pipe(fd):
72 if fd == subprocess.PIPE:
73 return '<pipe>'
74 elif fd == subprocess.STDOUT:
75 return '<stdout>'
76 else:
77 return repr(fd)
78
79
Yury Selivanov5587d7c2016-09-15 15:45:07 -040080def _set_reuseport(sock):
81 if not hasattr(socket, 'SO_REUSEPORT'):
82 raise ValueError('reuse_port not supported by socket module')
83 else:
84 try:
85 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
86 except OSError:
87 raise ValueError('reuse_port not supported by socket module, '
88 'SO_REUSEPORT defined but not implemented.')
89
90
Yury Selivanovd5c2a622015-12-16 19:31:17 -050091def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040092 # Try to skip getaddrinfo if "host" is already an IP. Users might have
93 # handled name resolution in their own code and pass in resolved IPs.
94 if not hasattr(socket, 'inet_pton'):
95 return
96
97 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
98 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -050099 return None
100
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500101 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500102 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500103 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500104 proto = socket.IPPROTO_UDP
105 else:
106 return None
107
Yury Selivanova7146162016-06-02 16:51:07 -0400108 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400109 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700110 elif isinstance(port, bytes) and port == b'':
111 port = 0
112 elif isinstance(port, str) and port == '':
113 port = 0
114 else:
115 # If port's a service name like "http", don't skip getaddrinfo.
116 try:
117 port = int(port)
118 except (TypeError, ValueError):
119 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400120
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400121 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500122 afs = [socket.AF_INET]
123 if hasattr(socket, 'AF_INET6'):
124 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400125 else:
126 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500127
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400128 if isinstance(host, bytes):
129 host = host.decode('idna')
130 if '%' in host:
131 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
132 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500133 return None
134
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400135 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500136 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400137 socket.inet_pton(af, host)
138 # The host has already been resolved.
139 return af, type, proto, '', (host, port)
140 except OSError:
141 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500142
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400143 # "host" is not an IP address.
144 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145
146
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100147def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500148 if not fut.cancelled():
149 exc = fut.exception()
150 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
151 # Issue #22429: run_forever() already finished, no need to
152 # stop it.
153 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500154 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100155
156
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700157class Server(events.AbstractServer):
158
159 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200160 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700161 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200162 self._active_count = 0
163 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700164
Victor Stinnere912e652014-07-12 03:11:53 +0200165 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500166 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200167
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200168 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700169 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200170 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700171
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200172 def _detach(self):
173 assert self._active_count > 0
174 self._active_count -= 1
175 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700176 self._wakeup()
177
178 def close(self):
179 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200180 if sockets is None:
181 return
182 self.sockets = None
183 for sock in sockets:
184 self._loop._stop_serving(sock)
185 if self._active_count == 0:
186 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700187
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530188 def get_loop(self):
189 return self._loop
190
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200192 waiters = self._waiters
193 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194 for waiter in waiters:
195 if not waiter.done():
196 waiter.set_result(waiter)
197
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200198 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200199 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700200 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400201 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200202 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200203 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204
205
206class BaseEventLoop(events.AbstractEventLoop):
207
208 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400209 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200210 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800211 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700212 self._ready = collections.deque()
213 self._scheduled = []
214 self._default_executor = None
215 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100216 # Identifier of the thread running the event loop, or None if the
217 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100218 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100219 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500220 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800221 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200222 # In debug mode, if the execution of a callback or a step of a task
223 # exceed this duration in seconds, the slow callback/task is logged.
224 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100225 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400226 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400227 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700228
Yury Selivanov0a91d482016-09-15 13:24:03 -0400229 if hasattr(sys, 'get_asyncgen_hooks'):
230 # Python >= 3.6
231 # A weak set of all asynchronous generators that are
232 # being iterated by the loop.
233 self._asyncgens = weakref.WeakSet()
234 else:
235 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700236
237 # Set to True when `loop.shutdown_asyncgens` is called.
238 self._asyncgens_shutdown_called = False
239
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200240 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500241 return (
242 f'<{self.__class__.__name__} running={self.is_running()} '
243 f'closed={self.is_closed()} debug={self.get_debug()}>'
244 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200245
Yury Selivanov7661db62016-05-16 15:38:39 -0400246 def create_future(self):
247 """Create a Future object attached to the loop."""
248 return futures.Future(loop=self)
249
Victor Stinner896a25a2014-07-08 11:29:25 +0200250 def create_task(self, coro):
251 """Schedule a coroutine object.
252
Victor Stinneracdb7822014-07-14 18:33:40 +0200253 Return a task object.
254 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100255 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400256 if self._task_factory is None:
257 task = tasks.Task(coro, loop=self)
258 if task._source_traceback:
259 del task._source_traceback[-1]
260 else:
261 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200262 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200263
Yury Selivanov740169c2015-05-11 14:23:38 -0400264 def set_task_factory(self, factory):
265 """Set a task factory that will be used by loop.create_task().
266
267 If factory is None the default task factory will be set.
268
269 If factory is a callable, it should have a signature matching
270 '(loop, coro)', where 'loop' will be a reference to the active
271 event loop, 'coro' will be a coroutine object. The callable
272 must return a Future.
273 """
274 if factory is not None and not callable(factory):
275 raise TypeError('task factory must be a callable or None')
276 self._task_factory = factory
277
278 def get_task_factory(self):
279 """Return a task factory, or None if the default one is in use."""
280 return self._task_factory
281
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700282 def _make_socket_transport(self, sock, protocol, waiter=None, *,
283 extra=None, server=None):
284 """Create socket transport."""
285 raise NotImplementedError
286
Neil Aspinallf7686c12017-12-19 19:45:42 +0000287 def _make_ssl_transport(
288 self, rawsock, protocol, sslcontext, waiter=None,
289 *, server_side=False, server_hostname=None,
290 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500291 ssl_handshake_timeout=None,
292 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700293 """Create SSL transport."""
294 raise NotImplementedError
295
296 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200297 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700298 """Create datagram transport."""
299 raise NotImplementedError
300
301 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
302 extra=None):
303 """Create read pipe transport."""
304 raise NotImplementedError
305
306 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
307 extra=None):
308 """Create write pipe transport."""
309 raise NotImplementedError
310
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200311 async def _make_subprocess_transport(self, protocol, args, shell,
312 stdin, stdout, stderr, bufsize,
313 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700314 """Create subprocess transport."""
315 raise NotImplementedError
316
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700317 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200318 """Write a byte to self-pipe, to wake up the event loop.
319
320 This may be called from a different thread.
321
322 The subclass is responsible for implementing the self-pipe.
323 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700324 raise NotImplementedError
325
326 def _process_events(self, event_list):
327 """Process selector events."""
328 raise NotImplementedError
329
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200330 def _check_closed(self):
331 if self._closed:
332 raise RuntimeError('Event loop is closed')
333
Yury Selivanoveb636452016-09-08 22:01:51 -0700334 def _asyncgen_finalizer_hook(self, agen):
335 self._asyncgens.discard(agen)
336 if not self.is_closed():
337 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400338 # Wake up the loop if the finalizer was called from
339 # a different thread.
340 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700341
342 def _asyncgen_firstiter_hook(self, agen):
343 if self._asyncgens_shutdown_called:
344 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500345 f"asynchronous generator {agen!r} was scheduled after "
346 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700347 ResourceWarning, source=self)
348
349 self._asyncgens.add(agen)
350
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200351 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700352 """Shutdown all active asynchronous generators."""
353 self._asyncgens_shutdown_called = True
354
Yury Selivanov0a91d482016-09-15 13:24:03 -0400355 if self._asyncgens is None or not len(self._asyncgens):
356 # If Python version is <3.6 or we don't have any asynchronous
357 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700358 return
359
360 closing_agens = list(self._asyncgens)
361 self._asyncgens.clear()
362
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200363 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700364 *[ag.aclose() for ag in closing_agens],
365 return_exceptions=True,
366 loop=self)
367
Yury Selivanoveb636452016-09-08 22:01:51 -0700368 for result, agen in zip(results, closing_agens):
369 if isinstance(result, Exception):
370 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500371 'message': f'an error occurred during closing of '
372 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700373 'exception': result,
374 'asyncgen': agen
375 })
376
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700377 def run_forever(self):
378 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200379 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100380 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400381 raise RuntimeError('This event loop is already running')
382 if events._get_running_loop() is not None:
383 raise RuntimeError(
384 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400385 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100386 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400387 if self._asyncgens is not None:
388 old_agen_hooks = sys.get_asyncgen_hooks()
389 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
390 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700391 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400392 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700393 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800394 self._run_once()
395 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700396 break
397 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800398 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100399 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400400 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400401 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400402 if self._asyncgens is not None:
403 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700404
405 def run_until_complete(self, future):
406 """Run until the Future is done.
407
408 If the argument is a coroutine, it is wrapped in a Task.
409
Victor Stinneracdb7822014-07-14 18:33:40 +0200410 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 with the same coroutine twice -- it would wrap it in two
412 different Tasks and that can't be good.
413
414 Return the Future's result, or raise its exception.
415 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200416 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200417
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700418 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400419 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200420 if new_task:
421 # An exception is raised if the future didn't complete, so there
422 # is no need to log the "destroy pending task" message
423 future._log_destroy_pending = False
424
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100425 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200426 try:
427 self.run_forever()
428 except:
429 if new_task and future.done() and not future.cancelled():
430 # The coroutine raised a BaseException. Consume the exception
431 # to not log a warning, the caller doesn't have access to the
432 # local task.
433 future.exception()
434 raise
jimmylai21b3e042017-05-22 22:32:46 -0700435 finally:
436 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700437 if not future.done():
438 raise RuntimeError('Event loop stopped before Future completed.')
439
440 return future.result()
441
442 def stop(self):
443 """Stop running the event loop.
444
Guido van Rossum41f69f42015-11-19 13:28:47 -0800445 Every callback already scheduled will still run. This simply informs
446 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800448 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700449
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200450 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700451 """Close the event loop.
452
453 This clears the queues and shuts down the executor,
454 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200455
456 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700457 """
Victor Stinner956de692014-12-26 21:07:52 +0100458 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200459 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200460 if self._closed:
461 return
Victor Stinnere912e652014-07-12 03:11:53 +0200462 if self._debug:
463 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400464 self._closed = True
465 self._ready.clear()
466 self._scheduled.clear()
467 executor = self._default_executor
468 if executor is not None:
469 self._default_executor = None
470 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200471
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200472 def is_closed(self):
473 """Returns True if the event loop was closed."""
474 return self._closed
475
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900476 def __del__(self):
477 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500478 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900479 source=self)
480 if not self.is_running():
481 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100482
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700483 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200484 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100485 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700486
487 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200488 """Return the time according to the event loop's clock.
489
490 This is a float expressed in seconds since an epoch, but the
491 epoch, precision, accuracy and drift are unspecified and may
492 differ per event loop.
493 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700494 return time.monotonic()
495
496 def call_later(self, delay, callback, *args):
497 """Arrange for a callback to be called at a given time.
498
499 Return a Handle: an opaque object with a cancel() method that
500 can be used to cancel the call.
501
502 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200503 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504
505 Each callback will be called exactly once. If two callbacks
506 are scheduled for exactly the same time, it undefined which
507 will be called first.
508
509 Any positional arguments after the callback will be passed to
510 the callback when it is called.
511 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200512 timer = self.call_at(self.time() + delay, callback, *args)
513 if timer._source_traceback:
514 del timer._source_traceback[-1]
515 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516
517 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200518 """Like call_later(), but uses an absolute time.
519
520 Absolute time corresponds to the event loop's time() method.
521 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100522 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100523 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100524 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700525 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500526 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200527 if timer._source_traceback:
528 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700529 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400530 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 return timer
532
533 def call_soon(self, callback, *args):
534 """Arrange for a callback to be called as soon as possible.
535
Victor Stinneracdb7822014-07-14 18:33:40 +0200536 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 order in which they are registered. Each callback will be
538 called exactly once.
539
540 Any positional arguments after the callback will be passed to
541 the callback when it is called.
542 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700543 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100544 if self._debug:
545 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700546 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100547 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200548 if handle._source_traceback:
549 del handle._source_traceback[-1]
550 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100551
Yury Selivanov491a9122016-11-03 15:09:24 -0700552 def _check_callback(self, callback, method):
553 if (coroutines.iscoroutine(callback) or
554 coroutines.iscoroutinefunction(callback)):
555 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500556 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700557 if not callable(callback):
558 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500559 f'a callable object was expected by {method}(), '
560 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700561
Victor Stinner956de692014-12-26 21:07:52 +0100562 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500563 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200564 if handle._source_traceback:
565 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566 self._ready.append(handle)
567 return handle
568
Victor Stinner956de692014-12-26 21:07:52 +0100569 def _check_thread(self):
570 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100571
Victor Stinneracdb7822014-07-14 18:33:40 +0200572 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100573 likely behave incorrectly when the assumption is violated.
574
Victor Stinneracdb7822014-07-14 18:33:40 +0200575 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100576 responsible for checking this condition for performance reasons.
577 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100578 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200579 return
Victor Stinner956de692014-12-26 21:07:52 +0100580 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100581 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100582 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200583 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100584 "than the current one")
585
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700586 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200587 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700588 self._check_closed()
589 if self._debug:
590 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100591 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200592 if handle._source_traceback:
593 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700594 self._write_to_self()
595 return handle
596
Yury Selivanov19a44f62017-12-14 20:53:26 -0500597 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100598 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700599 if self._debug:
600 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601 if executor is None:
602 executor = self._default_executor
603 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400604 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500606 return await futures.wrap_future(
607 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700608
609 def set_default_executor(self, executor):
610 self._default_executor = executor
611
Victor Stinnere912e652014-07-12 03:11:53 +0200612 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500613 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200614 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500615 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200616 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500617 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200618 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500619 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200620 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500621 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200622 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200623 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200624
625 t0 = self.time()
626 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
627 dt = self.time() - t0
628
Yury Selivanov6370f342017-12-10 18:36:12 -0500629 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200630 if dt >= self.slow_callback_duration:
631 logger.info(msg)
632 else:
633 logger.debug(msg)
634 return addrinfo
635
Yury Selivanov19a44f62017-12-14 20:53:26 -0500636 async def getaddrinfo(self, host, port, *,
637 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400638 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500639 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200640 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500641 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700642
Yury Selivanov19a44f62017-12-14 20:53:26 -0500643 return await self.run_in_executor(
644 None, getaddr_func, host, port, family, type, proto, flags)
645
646 async def getnameinfo(self, sockaddr, flags=0):
647 return await self.run_in_executor(
648 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700649
Neil Aspinallf7686c12017-12-19 19:45:42 +0000650 async def create_connection(
651 self, protocol_factory, host=None, port=None,
652 *, ssl=None, family=0,
653 proto=0, flags=0, sock=None,
654 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200655 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200656 """Connect to a TCP server.
657
658 Create a streaming transport connection to a given Internet host and
659 port: socket family AF_INET or socket.AF_INET6 depending on host (or
660 family if specified), socket type SOCK_STREAM. protocol_factory must be
661 a callable returning a protocol instance.
662
663 This method is a coroutine which will try to establish the connection
664 in the background. When successful, the coroutine returns a
665 (transport, protocol) pair.
666 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700667 if server_hostname is not None and not ssl:
668 raise ValueError('server_hostname is only meaningful with ssl')
669
670 if server_hostname is None and ssl:
671 # Use host as default for server_hostname. It is an error
672 # if host is empty or not set, e.g. when an
673 # already-connected socket was passed or when only a port
674 # is given. To avoid this error, you can pass
675 # server_hostname='' -- this will bypass the hostname
676 # check. (This also means that if host is a numeric
677 # IP/IPv6 address, we will attempt to verify that exact
678 # address; this will probably fail, but it is possible to
679 # create a certificate for a specific IP address, so we
680 # don't judge it here.)
681 if not host:
682 raise ValueError('You must set server_hostname '
683 'when using ssl without a host')
684 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700685
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200686 if ssl_handshake_timeout is not None and not ssl:
687 raise ValueError(
688 'ssl_handshake_timeout is only meaningful with ssl')
689
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700690 if host is not None or port is not None:
691 if sock is not None:
692 raise ValueError(
693 'host/port and sock can not be specified at the same time')
694
Yury Selivanov19a44f62017-12-14 20:53:26 -0500695 infos = await self._ensure_resolved(
696 (host, port), family=family,
697 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700698 if not infos:
699 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500700
701 if local_addr is not None:
702 laddr_infos = await self._ensure_resolved(
703 local_addr, family=family,
704 type=socket.SOCK_STREAM, proto=proto,
705 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700706 if not laddr_infos:
707 raise OSError('getaddrinfo() returned empty list')
708
709 exceptions = []
710 for family, type, proto, cname, address in infos:
711 try:
712 sock = socket.socket(family=family, type=type, proto=proto)
713 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500714 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700715 for _, _, _, _, laddr in laddr_infos:
716 try:
717 sock.bind(laddr)
718 break
719 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500720 msg = (
721 f'error while attempting to bind on '
722 f'address {laddr!r}: '
723 f'{exc.strerror.lower()}'
724 )
725 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700726 exceptions.append(exc)
727 else:
728 sock.close()
729 sock = None
730 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200731 if self._debug:
732 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200733 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 except OSError as exc:
735 if sock is not None:
736 sock.close()
737 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200738 except:
739 if sock is not None:
740 sock.close()
741 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700742 else:
743 break
744 else:
745 if len(exceptions) == 1:
746 raise exceptions[0]
747 else:
748 # If they all have the same str(), raise one.
749 model = str(exceptions[0])
750 if all(str(exc) == model for exc in exceptions):
751 raise exceptions[0]
752 # Raise a combined exception so the user can see all
753 # the various error messages.
754 raise OSError('Multiple exceptions: {}'.format(
755 ', '.join(str(exc) for exc in exceptions)))
756
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500757 else:
758 if sock is None:
759 raise ValueError(
760 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500761 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500762 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
763 # are SOCK_STREAM.
764 # We support passing AF_UNIX sockets even though we have
765 # a dedicated API for that: create_unix_connection.
766 # Disallowing AF_UNIX in this method, breaks backwards
767 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500768 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500769 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700770
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200771 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000772 sock, protocol_factory, ssl, server_hostname,
773 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200774 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200775 # Get the socket from the transport because SSL transport closes
776 # the old socket and creates a new SSL socket
777 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200778 logger.debug("%r connected to %s:%r: (%r, %r)",
779 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500780 return transport, protocol
781
Neil Aspinallf7686c12017-12-19 19:45:42 +0000782 async def _create_connection_transport(
783 self, sock, protocol_factory, ssl,
784 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200785 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400786
787 sock.setblocking(False)
788
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700789 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400790 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700791 if ssl:
792 sslcontext = None if isinstance(ssl, bool) else ssl
793 transport = self._make_ssl_transport(
794 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000795 server_side=server_side, server_hostname=server_hostname,
796 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700797 else:
798 transport = self._make_socket_transport(sock, protocol, waiter)
799
Victor Stinner29ad0112015-01-15 00:04:21 +0100800 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200801 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100802 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100803 transport.close()
804 raise
805
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700806 return transport, protocol
807
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500808 async def start_tls(self, transport, protocol, sslcontext, *,
809 server_side=False,
810 server_hostname=None,
811 ssl_handshake_timeout=None):
812 """Upgrade transport to TLS.
813
814 Return a new transport that *protocol* should start using
815 immediately.
816 """
817 if ssl is None:
818 raise RuntimeError('Python ssl module is not available')
819
820 if not isinstance(sslcontext, ssl.SSLContext):
821 raise TypeError(
822 f'sslcontext is expected to be an instance of ssl.SSLContext, '
823 f'got {sslcontext!r}')
824
825 if not getattr(transport, '_start_tls_compatible', False):
826 raise TypeError(
827 f'transport {self!r} is not supported by start_tls()')
828
829 waiter = self.create_future()
830 ssl_protocol = sslproto.SSLProtocol(
831 self, protocol, sslcontext, waiter,
832 server_side, server_hostname,
833 ssl_handshake_timeout=ssl_handshake_timeout,
834 call_connection_made=False)
835
836 transport.set_protocol(ssl_protocol)
837 self.call_soon(ssl_protocol.connection_made, transport)
838 if not transport.is_reading():
839 self.call_soon(transport.resume_reading)
840
841 await waiter
842 return ssl_protocol._app_transport
843
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200844 async def create_datagram_endpoint(self, protocol_factory,
845 local_addr=None, remote_addr=None, *,
846 family=0, proto=0, flags=0,
847 reuse_address=None, reuse_port=None,
848 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700849 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700850 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500851 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500852 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500853 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700854 if (local_addr or remote_addr or
855 family or proto or flags or
856 reuse_address or reuse_port or allow_broadcast):
857 # show the problematic kwargs in exception msg
858 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
859 family=family, proto=proto, flags=flags,
860 reuse_address=reuse_address, reuse_port=reuse_port,
861 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500862 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700863 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500864 f'socket modifier keyword arguments can not be used '
865 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700866 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700867 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700868 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700869 if not (local_addr or remote_addr):
870 if family == 0:
871 raise ValueError('unexpected address family')
872 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100873 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
874 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100875 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100876 raise TypeError('string is expected')
877 addr_pairs_info = (((family, proto),
878 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700879 else:
880 # join address by (family, protocol)
881 addr_infos = collections.OrderedDict()
882 for idx, addr in ((0, local_addr), (1, remote_addr)):
883 if addr is not None:
884 assert isinstance(addr, tuple) and len(addr) == 2, (
885 '2-tuple is expected')
886
Yury Selivanov19a44f62017-12-14 20:53:26 -0500887 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400888 addr, family=family, type=socket.SOCK_DGRAM,
889 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700890 if not infos:
891 raise OSError('getaddrinfo() returned empty list')
892
893 for fam, _, pro, _, address in infos:
894 key = (fam, pro)
895 if key not in addr_infos:
896 addr_infos[key] = [None, None]
897 addr_infos[key][idx] = address
898
899 # each addr has to have info for each (family, proto) pair
900 addr_pairs_info = [
901 (key, addr_pair) for key, addr_pair in addr_infos.items()
902 if not ((local_addr and addr_pair[0] is None) or
903 (remote_addr and addr_pair[1] is None))]
904
905 if not addr_pairs_info:
906 raise ValueError('can not get address information')
907
908 exceptions = []
909
910 if reuse_address is None:
911 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
912
913 for ((family, proto),
914 (local_address, remote_address)) in addr_pairs_info:
915 sock = None
916 r_addr = None
917 try:
918 sock = socket.socket(
919 family=family, type=socket.SOCK_DGRAM, proto=proto)
920 if reuse_address:
921 sock.setsockopt(
922 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
923 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400924 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700925 if allow_broadcast:
926 sock.setsockopt(
927 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
928 sock.setblocking(False)
929
930 if local_addr:
931 sock.bind(local_address)
932 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200933 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700934 r_addr = remote_address
935 except OSError as exc:
936 if sock is not None:
937 sock.close()
938 exceptions.append(exc)
939 except:
940 if sock is not None:
941 sock.close()
942 raise
943 else:
944 break
945 else:
946 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700947
948 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400949 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700950 transport = self._make_datagram_transport(
951 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200952 if self._debug:
953 if local_addr:
954 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
955 "created: (%r, %r)",
956 local_addr, remote_addr, transport, protocol)
957 else:
958 logger.debug("Datagram endpoint remote_addr=%r created: "
959 "(%r, %r)",
960 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100961
962 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200963 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +0100964 except:
965 transport.close()
966 raise
967
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700968 return transport, protocol
969
Yury Selivanov19a44f62017-12-14 20:53:26 -0500970 async def _ensure_resolved(self, address, *,
971 family=0, type=socket.SOCK_STREAM,
972 proto=0, flags=0, loop):
973 host, port = address[:2]
974 info = _ipaddr_info(host, port, family, type, proto)
975 if info is not None:
976 # "host" is already a resolved IP.
977 return [info]
978 else:
979 return await loop.getaddrinfo(host, port, family=family, type=type,
980 proto=proto, flags=flags)
981
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200982 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -0500983 infos = await self._ensure_resolved((host, port), family=family,
984 type=socket.SOCK_STREAM,
985 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200986 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -0500987 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200988 return infos
989
Neil Aspinallf7686c12017-12-19 19:45:42 +0000990 async def create_server(
991 self, protocol_factory, host=None, port=None,
992 *,
993 family=socket.AF_UNSPEC,
994 flags=socket.AI_PASSIVE,
995 sock=None,
996 backlog=100,
997 ssl=None,
998 reuse_address=None,
999 reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001000 ssl_handshake_timeout=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001001 """Create a TCP server.
1002
Yury Selivanov6370f342017-12-10 18:36:12 -05001003 The host parameter can be a string, in that case the TCP server is
1004 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001005
1006 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001007 the TCP server is bound to all hosts of the sequence. If a host
1008 appears multiple times (possibly indirectly e.g. when hostnames
1009 resolve to the same IP address), the server is only bound once to that
1010 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001011
Victor Stinneracdb7822014-07-14 18:33:40 +02001012 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001013
1014 This method is a coroutine.
1015 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001016 if isinstance(ssl, bool):
1017 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001018
1019 if ssl_handshake_timeout is not None and ssl is None:
1020 raise ValueError(
1021 'ssl_handshake_timeout is only meaningful with ssl')
1022
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001023 if host is not None or port is not None:
1024 if sock is not None:
1025 raise ValueError(
1026 'host/port and sock can not be specified at the same time')
1027
1028 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1029 if reuse_address is None:
1030 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1031 sockets = []
1032 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001033 hosts = [None]
1034 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001035 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001036 hosts = [host]
1037 else:
1038 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001039
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001040 fs = [self._create_server_getaddrinfo(host, port, family=family,
1041 flags=flags)
1042 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001043 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001044 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001045
1046 completed = False
1047 try:
1048 for res in infos:
1049 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001050 try:
1051 sock = socket.socket(af, socktype, proto)
1052 except socket.error:
1053 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001054 if self._debug:
1055 logger.warning('create_server() failed to create '
1056 'socket.socket(%r, %r, %r)',
1057 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001058 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001059 sockets.append(sock)
1060 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001061 sock.setsockopt(
1062 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1063 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001064 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001065 # Disable IPv4/IPv6 dual stack support (enabled by
1066 # default on Linux) which makes a single socket
1067 # listen on both address families.
1068 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1069 sock.setsockopt(socket.IPPROTO_IPV6,
1070 socket.IPV6_V6ONLY,
1071 True)
1072 try:
1073 sock.bind(sa)
1074 except OSError as err:
1075 raise OSError(err.errno, 'error while attempting '
1076 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001077 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078 completed = True
1079 finally:
1080 if not completed:
1081 for sock in sockets:
1082 sock.close()
1083 else:
1084 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001085 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001086 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001087 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001088 sockets = [sock]
1089
1090 server = Server(self, sockets)
1091 for sock in sockets:
1092 sock.listen(backlog)
1093 sock.setblocking(False)
Neil Aspinallf7686c12017-12-19 19:45:42 +00001094 self._start_serving(protocol_factory, sock, ssl, server, backlog,
1095 ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001096 if self._debug:
1097 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001098 return server
1099
Neil Aspinallf7686c12017-12-19 19:45:42 +00001100 async def connect_accepted_socket(
1101 self, protocol_factory, sock,
1102 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001103 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001104 """Handle an accepted connection.
1105
1106 This is used by servers that accept connections outside of
1107 asyncio but that use asyncio to handle connections.
1108
1109 This method is a coroutine. When completed, the coroutine
1110 returns a (transport, protocol) pair.
1111 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001112 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001113 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001114
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001115 if ssl_handshake_timeout is not None and not ssl:
1116 raise ValueError(
1117 'ssl_handshake_timeout is only meaningful with ssl')
1118
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001119 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001120 sock, protocol_factory, ssl, '', server_side=True,
1121 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001122 if self._debug:
1123 # Get the socket from the transport because SSL transport closes
1124 # the old socket and creates a new SSL socket
1125 sock = transport.get_extra_info('socket')
1126 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1127 return transport, protocol
1128
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001129 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001130 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001131 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001132 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001133
1134 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001135 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001136 except:
1137 transport.close()
1138 raise
1139
Victor Stinneracdb7822014-07-14 18:33:40 +02001140 if self._debug:
1141 logger.debug('Read pipe %r connected: (%r, %r)',
1142 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001143 return transport, protocol
1144
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001145 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001146 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001147 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001148 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001149
1150 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001151 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001152 except:
1153 transport.close()
1154 raise
1155
Victor Stinneracdb7822014-07-14 18:33:40 +02001156 if self._debug:
1157 logger.debug('Write pipe %r connected: (%r, %r)',
1158 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001159 return transport, protocol
1160
Victor Stinneracdb7822014-07-14 18:33:40 +02001161 def _log_subprocess(self, msg, stdin, stdout, stderr):
1162 info = [msg]
1163 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001164 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001165 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001166 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001167 else:
1168 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001169 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001170 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001171 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001172 logger.debug(' '.join(info))
1173
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001174 async def subprocess_shell(self, protocol_factory, cmd, *,
1175 stdin=subprocess.PIPE,
1176 stdout=subprocess.PIPE,
1177 stderr=subprocess.PIPE,
1178 universal_newlines=False,
1179 shell=True, bufsize=0,
1180 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001181 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001182 raise ValueError("cmd must be a string")
1183 if universal_newlines:
1184 raise ValueError("universal_newlines must be False")
1185 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001186 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001187 if bufsize != 0:
1188 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001189 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001190 if self._debug:
1191 # don't log parameters: they may contain sensitive information
1192 # (password) and may be too long
1193 debug_log = 'run shell command %r' % cmd
1194 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001195 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001196 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001197 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001198 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001199 return transport, protocol
1200
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001201 async def subprocess_exec(self, protocol_factory, program, *args,
1202 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1203 stderr=subprocess.PIPE, universal_newlines=False,
1204 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001205 if universal_newlines:
1206 raise ValueError("universal_newlines must be False")
1207 if shell:
1208 raise ValueError("shell must be False")
1209 if bufsize != 0:
1210 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001211 popen_args = (program,) + args
1212 for arg in popen_args:
1213 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001214 raise TypeError(
1215 f"program arguments must be a bytes or text string, "
1216 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001217 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001218 if self._debug:
1219 # don't log parameters: they may contain sensitive information
1220 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001221 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001222 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001223 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001224 protocol, popen_args, False, stdin, stdout, stderr,
1225 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001226 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001227 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001228 return transport, protocol
1229
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001230 def get_exception_handler(self):
1231 """Return an exception handler, or None if the default one is in use.
1232 """
1233 return self._exception_handler
1234
Yury Selivanov569efa22014-02-18 18:02:19 -05001235 def set_exception_handler(self, handler):
1236 """Set handler as the new event loop exception handler.
1237
1238 If handler is None, the default exception handler will
1239 be set.
1240
1241 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001242 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001243 will be a reference to the active event loop, 'context'
1244 will be a dict object (see `call_exception_handler()`
1245 documentation for details about context).
1246 """
1247 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001248 raise TypeError(f'A callable object or None is expected, '
1249 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001250 self._exception_handler = handler
1251
1252 def default_exception_handler(self, context):
1253 """Default exception handler.
1254
1255 This is called when an exception occurs and no exception
1256 handler is set, and can be called by a custom exception
1257 handler that wants to defer to the default behavior.
1258
Antoine Pitrou921e9432017-11-07 17:23:29 +01001259 This default handler logs the error message and other
1260 context-dependent information. In debug mode, a truncated
1261 stack trace is also appended showing where the given object
1262 (e.g. a handle or future or task) was created, if any.
1263
Victor Stinneracdb7822014-07-14 18:33:40 +02001264 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001265 `call_exception_handler()`.
1266 """
1267 message = context.get('message')
1268 if not message:
1269 message = 'Unhandled exception in event loop'
1270
1271 exception = context.get('exception')
1272 if exception is not None:
1273 exc_info = (type(exception), exception, exception.__traceback__)
1274 else:
1275 exc_info = False
1276
Yury Selivanov6370f342017-12-10 18:36:12 -05001277 if ('source_traceback' not in context and
1278 self._current_handle is not None and
1279 self._current_handle._source_traceback):
1280 context['handle_traceback'] = \
1281 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001282
Yury Selivanov569efa22014-02-18 18:02:19 -05001283 log_lines = [message]
1284 for key in sorted(context):
1285 if key in {'message', 'exception'}:
1286 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001287 value = context[key]
1288 if key == 'source_traceback':
1289 tb = ''.join(traceback.format_list(value))
1290 value = 'Object created at (most recent call last):\n'
1291 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001292 elif key == 'handle_traceback':
1293 tb = ''.join(traceback.format_list(value))
1294 value = 'Handle created at (most recent call last):\n'
1295 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001296 else:
1297 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001298 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001299
1300 logger.error('\n'.join(log_lines), exc_info=exc_info)
1301
1302 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001303 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001304
Victor Stinneracdb7822014-07-14 18:33:40 +02001305 The context argument is a dict containing the following keys:
1306
Yury Selivanov569efa22014-02-18 18:02:19 -05001307 - 'message': Error message;
1308 - 'exception' (optional): Exception object;
1309 - 'future' (optional): Future instance;
1310 - 'handle' (optional): Handle instance;
1311 - 'protocol' (optional): Protocol instance;
1312 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001313 - 'socket' (optional): Socket instance;
1314 - 'asyncgen' (optional): Asynchronous generator that caused
1315 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001316
Victor Stinneracdb7822014-07-14 18:33:40 +02001317 New keys maybe introduced in the future.
1318
1319 Note: do not overload this method in an event loop subclass.
1320 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001321 `set_exception_handler()` method.
1322 """
1323 if self._exception_handler is None:
1324 try:
1325 self.default_exception_handler(context)
1326 except Exception:
1327 # Second protection layer for unexpected errors
1328 # in the default implementation, as well as for subclassed
1329 # event loops with overloaded "default_exception_handler".
1330 logger.error('Exception in default exception handler',
1331 exc_info=True)
1332 else:
1333 try:
1334 self._exception_handler(self, context)
1335 except Exception as exc:
1336 # Exception in the user set custom exception handler.
1337 try:
1338 # Let's try default handler.
1339 self.default_exception_handler({
1340 'message': 'Unhandled error in exception handler',
1341 'exception': exc,
1342 'context': context,
1343 })
1344 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001345 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001346 # overloaded.
1347 logger.error('Exception in default exception handler '
1348 'while handling an unexpected error '
1349 'in custom exception handler',
1350 exc_info=True)
1351
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001352 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001353 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001354 assert isinstance(handle, events.Handle), 'A Handle is required here'
1355 if handle._cancelled:
1356 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001357 assert not isinstance(handle, events.TimerHandle)
1358 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001359
1360 def _add_callback_signalsafe(self, handle):
1361 """Like _add_callback() but called from a signal handler."""
1362 self._add_callback(handle)
1363 self._write_to_self()
1364
Yury Selivanov592ada92014-09-25 12:07:56 -04001365 def _timer_handle_cancelled(self, handle):
1366 """Notification that a TimerHandle has been cancelled."""
1367 if handle._scheduled:
1368 self._timer_cancelled_count += 1
1369
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001370 def _run_once(self):
1371 """Run one full iteration of the event loop.
1372
1373 This calls all currently ready callbacks, polls for I/O,
1374 schedules the resulting callbacks, and finally schedules
1375 'call_later' callbacks.
1376 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001377
Yury Selivanov592ada92014-09-25 12:07:56 -04001378 sched_count = len(self._scheduled)
1379 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1380 self._timer_cancelled_count / sched_count >
1381 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001382 # Remove delayed calls that were cancelled if their number
1383 # is too high
1384 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001385 for handle in self._scheduled:
1386 if handle._cancelled:
1387 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001388 else:
1389 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001390
Victor Stinner68da8fc2014-09-30 18:08:36 +02001391 heapq.heapify(new_scheduled)
1392 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001393 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001394 else:
1395 # Remove delayed calls that were cancelled from head of queue.
1396 while self._scheduled and self._scheduled[0]._cancelled:
1397 self._timer_cancelled_count -= 1
1398 handle = heapq.heappop(self._scheduled)
1399 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001400
1401 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001402 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001403 timeout = 0
1404 elif self._scheduled:
1405 # Compute the desired timeout.
1406 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001407 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001408
Victor Stinner770e48d2014-07-11 11:58:33 +02001409 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001410 t0 = self.time()
1411 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001412 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001413 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001414 level = logging.INFO
1415 else:
1416 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001417 nevent = len(event_list)
1418 if timeout is None:
1419 logger.log(level, 'poll took %.3f ms: %s events',
1420 dt * 1e3, nevent)
1421 elif nevent:
1422 logger.log(level,
1423 'poll %.3f ms took %.3f ms: %s events',
1424 timeout * 1e3, dt * 1e3, nevent)
1425 elif dt >= 1.0:
1426 logger.log(level,
1427 'poll %.3f ms took %.3f ms: timeout',
1428 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001429 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001430 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001431 self._process_events(event_list)
1432
1433 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001434 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001435 while self._scheduled:
1436 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001437 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001438 break
1439 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001440 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001441 self._ready.append(handle)
1442
1443 # This is the only place where callbacks are actually *called*.
1444 # All other places just add them to ready.
1445 # Note: We run all currently scheduled callbacks, but not any
1446 # callbacks scheduled by callbacks run this time around --
1447 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001448 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001449 ntodo = len(self._ready)
1450 for i in range(ntodo):
1451 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001452 if handle._cancelled:
1453 continue
1454 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001455 try:
1456 self._current_handle = handle
1457 t0 = self.time()
1458 handle._run()
1459 dt = self.time() - t0
1460 if dt >= self.slow_callback_duration:
1461 logger.warning('Executing %s took %.3f seconds',
1462 _format_handle(handle), dt)
1463 finally:
1464 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001465 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001466 handle._run()
1467 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001468
Yury Selivanove8944cb2015-05-12 11:43:04 -04001469 def _set_coroutine_wrapper(self, enabled):
1470 try:
1471 set_wrapper = sys.set_coroutine_wrapper
1472 get_wrapper = sys.get_coroutine_wrapper
1473 except AttributeError:
1474 return
1475
1476 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001477 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001478 return
1479
1480 wrapper = coroutines.debug_wrapper
1481 current_wrapper = get_wrapper()
1482
1483 if enabled:
1484 if current_wrapper not in (None, wrapper):
1485 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001486 f"loop.set_debug(True): cannot set debug coroutine "
1487 f"wrapper; another wrapper is already set "
1488 f"{current_wrapper!r}",
1489 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001490 else:
1491 set_wrapper(wrapper)
1492 self._coroutine_wrapper_set = True
1493 else:
1494 if current_wrapper not in (None, wrapper):
1495 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001496 f"loop.set_debug(False): cannot unset debug coroutine "
1497 f"wrapper; another wrapper was set {current_wrapper!r}",
1498 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001499 else:
1500 set_wrapper(None)
1501 self._coroutine_wrapper_set = False
1502
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001503 def get_debug(self):
1504 return self._debug
1505
1506 def set_debug(self, enabled):
1507 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001508
Yury Selivanove8944cb2015-05-12 11:43:04 -04001509 if self.is_running():
1510 self._set_coroutine_wrapper(enabled)