blob: 00831b398532140c17feb3e01f82fcfe2beb3d06 [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
188 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 waiters = self._waiters
190 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191 for waiter in waiters:
192 if not waiter.done():
193 waiter.set_result(waiter)
194
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200195 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200196 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700197 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400198 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200199 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200200 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700201
202
203class BaseEventLoop(events.AbstractEventLoop):
204
205 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400206 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200207 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800208 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700209 self._ready = collections.deque()
210 self._scheduled = []
211 self._default_executor = None
212 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100213 # Identifier of the thread running the event loop, or None if the
214 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100215 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100216 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500217 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800218 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200219 # In debug mode, if the execution of a callback or a step of a task
220 # exceed this duration in seconds, the slow callback/task is logged.
221 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100222 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400223 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400224 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700225
Yury Selivanov0a91d482016-09-15 13:24:03 -0400226 if hasattr(sys, 'get_asyncgen_hooks'):
227 # Python >= 3.6
228 # A weak set of all asynchronous generators that are
229 # being iterated by the loop.
230 self._asyncgens = weakref.WeakSet()
231 else:
232 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700233
234 # 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 Selivanov0a91d482016-09-15 13:24:03 -0400352 if self._asyncgens is None or not len(self._asyncgens):
353 # 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')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400382 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100383 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400384 if self._asyncgens is not None:
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)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400398 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400399 if self._asyncgens is not None:
400 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700401
402 def run_until_complete(self, future):
403 """Run until the Future is done.
404
405 If the argument is a coroutine, it is wrapped in a Task.
406
Victor Stinneracdb7822014-07-14 18:33:40 +0200407 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408 with the same coroutine twice -- it would wrap it in two
409 different Tasks and that can't be good.
410
411 Return the Future's result, or raise its exception.
412 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200413 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200414
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700415 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400416 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200417 if new_task:
418 # An exception is raised if the future didn't complete, so there
419 # is no need to log the "destroy pending task" message
420 future._log_destroy_pending = False
421
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100422 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200423 try:
424 self.run_forever()
425 except:
426 if new_task and future.done() and not future.cancelled():
427 # The coroutine raised a BaseException. Consume the exception
428 # to not log a warning, the caller doesn't have access to the
429 # local task.
430 future.exception()
431 raise
jimmylai21b3e042017-05-22 22:32:46 -0700432 finally:
433 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700434 if not future.done():
435 raise RuntimeError('Event loop stopped before Future completed.')
436
437 return future.result()
438
439 def stop(self):
440 """Stop running the event loop.
441
Guido van Rossum41f69f42015-11-19 13:28:47 -0800442 Every callback already scheduled will still run. This simply informs
443 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700444 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800445 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200447 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700448 """Close the event loop.
449
450 This clears the queues and shuts down the executor,
451 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200452
453 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700454 """
Victor Stinner956de692014-12-26 21:07:52 +0100455 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200456 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200457 if self._closed:
458 return
Victor Stinnere912e652014-07-12 03:11:53 +0200459 if self._debug:
460 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400461 self._closed = True
462 self._ready.clear()
463 self._scheduled.clear()
464 executor = self._default_executor
465 if executor is not None:
466 self._default_executor = None
467 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200468
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200469 def is_closed(self):
470 """Returns True if the event loop was closed."""
471 return self._closed
472
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900473 def __del__(self):
474 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500475 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900476 source=self)
477 if not self.is_running():
478 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100479
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700480 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200481 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100482 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700483
484 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200485 """Return the time according to the event loop's clock.
486
487 This is a float expressed in seconds since an epoch, but the
488 epoch, precision, accuracy and drift are unspecified and may
489 differ per event loop.
490 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700491 return time.monotonic()
492
493 def call_later(self, delay, callback, *args):
494 """Arrange for a callback to be called at a given time.
495
496 Return a Handle: an opaque object with a cancel() method that
497 can be used to cancel the call.
498
499 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200500 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700501
502 Each callback will be called exactly once. If two callbacks
503 are scheduled for exactly the same time, it undefined which
504 will be called first.
505
506 Any positional arguments after the callback will be passed to
507 the callback when it is called.
508 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200509 timer = self.call_at(self.time() + delay, callback, *args)
510 if timer._source_traceback:
511 del timer._source_traceback[-1]
512 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700513
514 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200515 """Like call_later(), but uses an absolute time.
516
517 Absolute time corresponds to the event loop's time() method.
518 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100519 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100520 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100521 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700522 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500523 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200524 if timer._source_traceback:
525 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400527 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 return timer
529
530 def call_soon(self, callback, *args):
531 """Arrange for a callback to be called as soon as possible.
532
Victor Stinneracdb7822014-07-14 18:33:40 +0200533 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700534 order in which they are registered. Each callback will be
535 called exactly once.
536
537 Any positional arguments after the callback will be passed to
538 the callback when it is called.
539 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700540 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100541 if self._debug:
542 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700543 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100544 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200545 if handle._source_traceback:
546 del handle._source_traceback[-1]
547 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100548
Yury Selivanov491a9122016-11-03 15:09:24 -0700549 def _check_callback(self, callback, method):
550 if (coroutines.iscoroutine(callback) or
551 coroutines.iscoroutinefunction(callback)):
552 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500553 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700554 if not callable(callback):
555 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500556 f'a callable object was expected by {method}(), '
557 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700558
Victor Stinner956de692014-12-26 21:07:52 +0100559 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500560 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200561 if handle._source_traceback:
562 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700563 self._ready.append(handle)
564 return handle
565
Victor Stinner956de692014-12-26 21:07:52 +0100566 def _check_thread(self):
567 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100568
Victor Stinneracdb7822014-07-14 18:33:40 +0200569 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100570 likely behave incorrectly when the assumption is violated.
571
Victor Stinneracdb7822014-07-14 18:33:40 +0200572 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100573 responsible for checking this condition for performance reasons.
574 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100575 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200576 return
Victor Stinner956de692014-12-26 21:07:52 +0100577 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100578 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100579 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200580 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100581 "than the current one")
582
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700583 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200584 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700585 self._check_closed()
586 if self._debug:
587 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100588 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200589 if handle._source_traceback:
590 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591 self._write_to_self()
592 return handle
593
Yury Selivanov19a44f62017-12-14 20:53:26 -0500594 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100595 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700596 if self._debug:
597 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 if executor is None:
599 executor = self._default_executor
600 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400601 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700602 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500603 return await futures.wrap_future(
604 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605
606 def set_default_executor(self, executor):
607 self._default_executor = executor
608
Victor Stinnere912e652014-07-12 03:11:53 +0200609 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500610 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200611 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500612 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200613 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500614 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200615 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500616 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200617 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500618 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200619 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200620 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200621
622 t0 = self.time()
623 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
624 dt = self.time() - t0
625
Yury Selivanov6370f342017-12-10 18:36:12 -0500626 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200627 if dt >= self.slow_callback_duration:
628 logger.info(msg)
629 else:
630 logger.debug(msg)
631 return addrinfo
632
Yury Selivanov19a44f62017-12-14 20:53:26 -0500633 async def getaddrinfo(self, host, port, *,
634 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400635 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500636 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200637 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500638 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700639
Yury Selivanov19a44f62017-12-14 20:53:26 -0500640 return await self.run_in_executor(
641 None, getaddr_func, host, port, family, type, proto, flags)
642
643 async def getnameinfo(self, sockaddr, flags=0):
644 return await self.run_in_executor(
645 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646
Neil Aspinallf7686c12017-12-19 19:45:42 +0000647 async def create_connection(
648 self, protocol_factory, host=None, port=None,
649 *, ssl=None, family=0,
650 proto=0, flags=0, sock=None,
651 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200652 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200653 """Connect to a TCP server.
654
655 Create a streaming transport connection to a given Internet host and
656 port: socket family AF_INET or socket.AF_INET6 depending on host (or
657 family if specified), socket type SOCK_STREAM. protocol_factory must be
658 a callable returning a protocol instance.
659
660 This method is a coroutine which will try to establish the connection
661 in the background. When successful, the coroutine returns a
662 (transport, protocol) pair.
663 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700664 if server_hostname is not None and not ssl:
665 raise ValueError('server_hostname is only meaningful with ssl')
666
667 if server_hostname is None and ssl:
668 # Use host as default for server_hostname. It is an error
669 # if host is empty or not set, e.g. when an
670 # already-connected socket was passed or when only a port
671 # is given. To avoid this error, you can pass
672 # server_hostname='' -- this will bypass the hostname
673 # check. (This also means that if host is a numeric
674 # IP/IPv6 address, we will attempt to verify that exact
675 # address; this will probably fail, but it is possible to
676 # create a certificate for a specific IP address, so we
677 # don't judge it here.)
678 if not host:
679 raise ValueError('You must set server_hostname '
680 'when using ssl without a host')
681 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700682
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200683 if ssl_handshake_timeout is not None and not ssl:
684 raise ValueError(
685 'ssl_handshake_timeout is only meaningful with ssl')
686
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700687 if host is not None or port is not None:
688 if sock is not None:
689 raise ValueError(
690 'host/port and sock can not be specified at the same time')
691
Yury Selivanov19a44f62017-12-14 20:53:26 -0500692 infos = await self._ensure_resolved(
693 (host, port), family=family,
694 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700695 if not infos:
696 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500697
698 if local_addr is not None:
699 laddr_infos = await self._ensure_resolved(
700 local_addr, family=family,
701 type=socket.SOCK_STREAM, proto=proto,
702 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700703 if not laddr_infos:
704 raise OSError('getaddrinfo() returned empty list')
705
706 exceptions = []
707 for family, type, proto, cname, address in infos:
708 try:
709 sock = socket.socket(family=family, type=type, proto=proto)
710 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500711 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700712 for _, _, _, _, laddr in laddr_infos:
713 try:
714 sock.bind(laddr)
715 break
716 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500717 msg = (
718 f'error while attempting to bind on '
719 f'address {laddr!r}: '
720 f'{exc.strerror.lower()}'
721 )
722 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700723 exceptions.append(exc)
724 else:
725 sock.close()
726 sock = None
727 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200728 if self._debug:
729 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200730 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700731 except OSError as exc:
732 if sock is not None:
733 sock.close()
734 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200735 except:
736 if sock is not None:
737 sock.close()
738 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700739 else:
740 break
741 else:
742 if len(exceptions) == 1:
743 raise exceptions[0]
744 else:
745 # If they all have the same str(), raise one.
746 model = str(exceptions[0])
747 if all(str(exc) == model for exc in exceptions):
748 raise exceptions[0]
749 # Raise a combined exception so the user can see all
750 # the various error messages.
751 raise OSError('Multiple exceptions: {}'.format(
752 ', '.join(str(exc) for exc in exceptions)))
753
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500754 else:
755 if sock is None:
756 raise ValueError(
757 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500758 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500759 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
760 # are SOCK_STREAM.
761 # We support passing AF_UNIX sockets even though we have
762 # a dedicated API for that: create_unix_connection.
763 # Disallowing AF_UNIX in this method, breaks backwards
764 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500765 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500766 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700767
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200768 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000769 sock, protocol_factory, ssl, server_hostname,
770 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200771 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200772 # Get the socket from the transport because SSL transport closes
773 # the old socket and creates a new SSL socket
774 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200775 logger.debug("%r connected to %s:%r: (%r, %r)",
776 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500777 return transport, protocol
778
Neil Aspinallf7686c12017-12-19 19:45:42 +0000779 async def _create_connection_transport(
780 self, sock, protocol_factory, ssl,
781 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200782 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400783
784 sock.setblocking(False)
785
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700786 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400787 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700788 if ssl:
789 sslcontext = None if isinstance(ssl, bool) else ssl
790 transport = self._make_ssl_transport(
791 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000792 server_side=server_side, server_hostname=server_hostname,
793 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700794 else:
795 transport = self._make_socket_transport(sock, protocol, waiter)
796
Victor Stinner29ad0112015-01-15 00:04:21 +0100797 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200798 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100799 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100800 transport.close()
801 raise
802
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700803 return transport, protocol
804
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500805 async def start_tls(self, transport, protocol, sslcontext, *,
806 server_side=False,
807 server_hostname=None,
808 ssl_handshake_timeout=None):
809 """Upgrade transport to TLS.
810
811 Return a new transport that *protocol* should start using
812 immediately.
813 """
814 if ssl is None:
815 raise RuntimeError('Python ssl module is not available')
816
817 if not isinstance(sslcontext, ssl.SSLContext):
818 raise TypeError(
819 f'sslcontext is expected to be an instance of ssl.SSLContext, '
820 f'got {sslcontext!r}')
821
822 if not getattr(transport, '_start_tls_compatible', False):
823 raise TypeError(
824 f'transport {self!r} is not supported by start_tls()')
825
826 waiter = self.create_future()
827 ssl_protocol = sslproto.SSLProtocol(
828 self, protocol, sslcontext, waiter,
829 server_side, server_hostname,
830 ssl_handshake_timeout=ssl_handshake_timeout,
831 call_connection_made=False)
832
833 transport.set_protocol(ssl_protocol)
834 self.call_soon(ssl_protocol.connection_made, transport)
835 if not transport.is_reading():
836 self.call_soon(transport.resume_reading)
837
838 await waiter
839 return ssl_protocol._app_transport
840
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200841 async def create_datagram_endpoint(self, protocol_factory,
842 local_addr=None, remote_addr=None, *,
843 family=0, proto=0, flags=0,
844 reuse_address=None, reuse_port=None,
845 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700846 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700847 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500848 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500849 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500850 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700851 if (local_addr or remote_addr or
852 family or proto or flags or
853 reuse_address or reuse_port or allow_broadcast):
854 # show the problematic kwargs in exception msg
855 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
856 family=family, proto=proto, flags=flags,
857 reuse_address=reuse_address, reuse_port=reuse_port,
858 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500859 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700860 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500861 f'socket modifier keyword arguments can not be used '
862 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700863 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700864 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700865 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700866 if not (local_addr or remote_addr):
867 if family == 0:
868 raise ValueError('unexpected address family')
869 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100870 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
871 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100872 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100873 raise TypeError('string is expected')
874 addr_pairs_info = (((family, proto),
875 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700876 else:
877 # join address by (family, protocol)
878 addr_infos = collections.OrderedDict()
879 for idx, addr in ((0, local_addr), (1, remote_addr)):
880 if addr is not None:
881 assert isinstance(addr, tuple) and len(addr) == 2, (
882 '2-tuple is expected')
883
Yury Selivanov19a44f62017-12-14 20:53:26 -0500884 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400885 addr, family=family, type=socket.SOCK_DGRAM,
886 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700887 if not infos:
888 raise OSError('getaddrinfo() returned empty list')
889
890 for fam, _, pro, _, address in infos:
891 key = (fam, pro)
892 if key not in addr_infos:
893 addr_infos[key] = [None, None]
894 addr_infos[key][idx] = address
895
896 # each addr has to have info for each (family, proto) pair
897 addr_pairs_info = [
898 (key, addr_pair) for key, addr_pair in addr_infos.items()
899 if not ((local_addr and addr_pair[0] is None) or
900 (remote_addr and addr_pair[1] is None))]
901
902 if not addr_pairs_info:
903 raise ValueError('can not get address information')
904
905 exceptions = []
906
907 if reuse_address is None:
908 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
909
910 for ((family, proto),
911 (local_address, remote_address)) in addr_pairs_info:
912 sock = None
913 r_addr = None
914 try:
915 sock = socket.socket(
916 family=family, type=socket.SOCK_DGRAM, proto=proto)
917 if reuse_address:
918 sock.setsockopt(
919 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
920 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400921 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700922 if allow_broadcast:
923 sock.setsockopt(
924 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
925 sock.setblocking(False)
926
927 if local_addr:
928 sock.bind(local_address)
929 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200930 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700931 r_addr = remote_address
932 except OSError as exc:
933 if sock is not None:
934 sock.close()
935 exceptions.append(exc)
936 except:
937 if sock is not None:
938 sock.close()
939 raise
940 else:
941 break
942 else:
943 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700944
945 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400946 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700947 transport = self._make_datagram_transport(
948 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200949 if self._debug:
950 if local_addr:
951 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
952 "created: (%r, %r)",
953 local_addr, remote_addr, transport, protocol)
954 else:
955 logger.debug("Datagram endpoint remote_addr=%r created: "
956 "(%r, %r)",
957 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100958
959 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200960 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +0100961 except:
962 transport.close()
963 raise
964
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700965 return transport, protocol
966
Yury Selivanov19a44f62017-12-14 20:53:26 -0500967 async def _ensure_resolved(self, address, *,
968 family=0, type=socket.SOCK_STREAM,
969 proto=0, flags=0, loop):
970 host, port = address[:2]
971 info = _ipaddr_info(host, port, family, type, proto)
972 if info is not None:
973 # "host" is already a resolved IP.
974 return [info]
975 else:
976 return await loop.getaddrinfo(host, port, family=family, type=type,
977 proto=proto, flags=flags)
978
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200979 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -0500980 infos = await self._ensure_resolved((host, port), family=family,
981 type=socket.SOCK_STREAM,
982 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200983 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -0500984 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200985 return infos
986
Neil Aspinallf7686c12017-12-19 19:45:42 +0000987 async def create_server(
988 self, protocol_factory, host=None, port=None,
989 *,
990 family=socket.AF_UNSPEC,
991 flags=socket.AI_PASSIVE,
992 sock=None,
993 backlog=100,
994 ssl=None,
995 reuse_address=None,
996 reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200997 ssl_handshake_timeout=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200998 """Create a TCP server.
999
Yury Selivanov6370f342017-12-10 18:36:12 -05001000 The host parameter can be a string, in that case the TCP server is
1001 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001002
1003 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001004 the TCP server is bound to all hosts of the sequence. If a host
1005 appears multiple times (possibly indirectly e.g. when hostnames
1006 resolve to the same IP address), the server is only bound once to that
1007 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001008
Victor Stinneracdb7822014-07-14 18:33:40 +02001009 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001010
1011 This method is a coroutine.
1012 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001013 if isinstance(ssl, bool):
1014 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001015
1016 if ssl_handshake_timeout is not None and ssl is None:
1017 raise ValueError(
1018 'ssl_handshake_timeout is only meaningful with ssl')
1019
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001020 if host is not None or port is not None:
1021 if sock is not None:
1022 raise ValueError(
1023 'host/port and sock can not be specified at the same time')
1024
1025 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1026 if reuse_address is None:
1027 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1028 sockets = []
1029 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001030 hosts = [None]
1031 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001032 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001033 hosts = [host]
1034 else:
1035 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001036
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001037 fs = [self._create_server_getaddrinfo(host, port, family=family,
1038 flags=flags)
1039 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001040 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001041 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001042
1043 completed = False
1044 try:
1045 for res in infos:
1046 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001047 try:
1048 sock = socket.socket(af, socktype, proto)
1049 except socket.error:
1050 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001051 if self._debug:
1052 logger.warning('create_server() failed to create '
1053 'socket.socket(%r, %r, %r)',
1054 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001055 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001056 sockets.append(sock)
1057 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001058 sock.setsockopt(
1059 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1060 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001061 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001062 # Disable IPv4/IPv6 dual stack support (enabled by
1063 # default on Linux) which makes a single socket
1064 # listen on both address families.
1065 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1066 sock.setsockopt(socket.IPPROTO_IPV6,
1067 socket.IPV6_V6ONLY,
1068 True)
1069 try:
1070 sock.bind(sa)
1071 except OSError as err:
1072 raise OSError(err.errno, 'error while attempting '
1073 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001074 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001075 completed = True
1076 finally:
1077 if not completed:
1078 for sock in sockets:
1079 sock.close()
1080 else:
1081 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001082 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001083 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001084 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001085 sockets = [sock]
1086
1087 server = Server(self, sockets)
1088 for sock in sockets:
1089 sock.listen(backlog)
1090 sock.setblocking(False)
Neil Aspinallf7686c12017-12-19 19:45:42 +00001091 self._start_serving(protocol_factory, sock, ssl, server, backlog,
1092 ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001093 if self._debug:
1094 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001095 return server
1096
Neil Aspinallf7686c12017-12-19 19:45:42 +00001097 async def connect_accepted_socket(
1098 self, protocol_factory, sock,
1099 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001100 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001101 """Handle an accepted connection.
1102
1103 This is used by servers that accept connections outside of
1104 asyncio but that use asyncio to handle connections.
1105
1106 This method is a coroutine. When completed, the coroutine
1107 returns a (transport, protocol) pair.
1108 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001109 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001110 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001111
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001112 if ssl_handshake_timeout is not None and not ssl:
1113 raise ValueError(
1114 'ssl_handshake_timeout is only meaningful with ssl')
1115
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001116 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001117 sock, protocol_factory, ssl, '', server_side=True,
1118 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001119 if self._debug:
1120 # Get the socket from the transport because SSL transport closes
1121 # the old socket and creates a new SSL socket
1122 sock = transport.get_extra_info('socket')
1123 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1124 return transport, protocol
1125
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001126 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001127 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001128 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001129 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001130
1131 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001132 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001133 except:
1134 transport.close()
1135 raise
1136
Victor Stinneracdb7822014-07-14 18:33:40 +02001137 if self._debug:
1138 logger.debug('Read pipe %r connected: (%r, %r)',
1139 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001140 return transport, protocol
1141
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001142 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001143 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001144 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001145 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001146
1147 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001148 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001149 except:
1150 transport.close()
1151 raise
1152
Victor Stinneracdb7822014-07-14 18:33:40 +02001153 if self._debug:
1154 logger.debug('Write pipe %r connected: (%r, %r)',
1155 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001156 return transport, protocol
1157
Victor Stinneracdb7822014-07-14 18:33:40 +02001158 def _log_subprocess(self, msg, stdin, stdout, stderr):
1159 info = [msg]
1160 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001161 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001162 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001163 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001164 else:
1165 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001166 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001167 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001168 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001169 logger.debug(' '.join(info))
1170
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001171 async def subprocess_shell(self, protocol_factory, cmd, *,
1172 stdin=subprocess.PIPE,
1173 stdout=subprocess.PIPE,
1174 stderr=subprocess.PIPE,
1175 universal_newlines=False,
1176 shell=True, bufsize=0,
1177 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001178 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001179 raise ValueError("cmd must be a string")
1180 if universal_newlines:
1181 raise ValueError("universal_newlines must be False")
1182 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001183 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001184 if bufsize != 0:
1185 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001186 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001187 if self._debug:
1188 # don't log parameters: they may contain sensitive information
1189 # (password) and may be too long
1190 debug_log = 'run shell command %r' % cmd
1191 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001192 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001193 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001194 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001195 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001196 return transport, protocol
1197
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001198 async def subprocess_exec(self, protocol_factory, program, *args,
1199 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1200 stderr=subprocess.PIPE, universal_newlines=False,
1201 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001202 if universal_newlines:
1203 raise ValueError("universal_newlines must be False")
1204 if shell:
1205 raise ValueError("shell must be False")
1206 if bufsize != 0:
1207 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001208 popen_args = (program,) + args
1209 for arg in popen_args:
1210 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001211 raise TypeError(
1212 f"program arguments must be a bytes or text string, "
1213 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001214 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001215 if self._debug:
1216 # don't log parameters: they may contain sensitive information
1217 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001218 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001219 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001220 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001221 protocol, popen_args, False, stdin, stdout, stderr,
1222 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001223 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001224 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001225 return transport, protocol
1226
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001227 def get_exception_handler(self):
1228 """Return an exception handler, or None if the default one is in use.
1229 """
1230 return self._exception_handler
1231
Yury Selivanov569efa22014-02-18 18:02:19 -05001232 def set_exception_handler(self, handler):
1233 """Set handler as the new event loop exception handler.
1234
1235 If handler is None, the default exception handler will
1236 be set.
1237
1238 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001239 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001240 will be a reference to the active event loop, 'context'
1241 will be a dict object (see `call_exception_handler()`
1242 documentation for details about context).
1243 """
1244 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001245 raise TypeError(f'A callable object or None is expected, '
1246 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001247 self._exception_handler = handler
1248
1249 def default_exception_handler(self, context):
1250 """Default exception handler.
1251
1252 This is called when an exception occurs and no exception
1253 handler is set, and can be called by a custom exception
1254 handler that wants to defer to the default behavior.
1255
Antoine Pitrou921e9432017-11-07 17:23:29 +01001256 This default handler logs the error message and other
1257 context-dependent information. In debug mode, a truncated
1258 stack trace is also appended showing where the given object
1259 (e.g. a handle or future or task) was created, if any.
1260
Victor Stinneracdb7822014-07-14 18:33:40 +02001261 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001262 `call_exception_handler()`.
1263 """
1264 message = context.get('message')
1265 if not message:
1266 message = 'Unhandled exception in event loop'
1267
1268 exception = context.get('exception')
1269 if exception is not None:
1270 exc_info = (type(exception), exception, exception.__traceback__)
1271 else:
1272 exc_info = False
1273
Yury Selivanov6370f342017-12-10 18:36:12 -05001274 if ('source_traceback' not in context and
1275 self._current_handle is not None and
1276 self._current_handle._source_traceback):
1277 context['handle_traceback'] = \
1278 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001279
Yury Selivanov569efa22014-02-18 18:02:19 -05001280 log_lines = [message]
1281 for key in sorted(context):
1282 if key in {'message', 'exception'}:
1283 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001284 value = context[key]
1285 if key == 'source_traceback':
1286 tb = ''.join(traceback.format_list(value))
1287 value = 'Object created at (most recent call last):\n'
1288 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001289 elif key == 'handle_traceback':
1290 tb = ''.join(traceback.format_list(value))
1291 value = 'Handle created at (most recent call last):\n'
1292 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001293 else:
1294 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001295 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001296
1297 logger.error('\n'.join(log_lines), exc_info=exc_info)
1298
1299 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001300 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001301
Victor Stinneracdb7822014-07-14 18:33:40 +02001302 The context argument is a dict containing the following keys:
1303
Yury Selivanov569efa22014-02-18 18:02:19 -05001304 - 'message': Error message;
1305 - 'exception' (optional): Exception object;
1306 - 'future' (optional): Future instance;
1307 - 'handle' (optional): Handle instance;
1308 - 'protocol' (optional): Protocol instance;
1309 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001310 - 'socket' (optional): Socket instance;
1311 - 'asyncgen' (optional): Asynchronous generator that caused
1312 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001313
Victor Stinneracdb7822014-07-14 18:33:40 +02001314 New keys maybe introduced in the future.
1315
1316 Note: do not overload this method in an event loop subclass.
1317 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001318 `set_exception_handler()` method.
1319 """
1320 if self._exception_handler is None:
1321 try:
1322 self.default_exception_handler(context)
1323 except Exception:
1324 # Second protection layer for unexpected errors
1325 # in the default implementation, as well as for subclassed
1326 # event loops with overloaded "default_exception_handler".
1327 logger.error('Exception in default exception handler',
1328 exc_info=True)
1329 else:
1330 try:
1331 self._exception_handler(self, context)
1332 except Exception as exc:
1333 # Exception in the user set custom exception handler.
1334 try:
1335 # Let's try default handler.
1336 self.default_exception_handler({
1337 'message': 'Unhandled error in exception handler',
1338 'exception': exc,
1339 'context': context,
1340 })
1341 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001342 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001343 # overloaded.
1344 logger.error('Exception in default exception handler '
1345 'while handling an unexpected error '
1346 'in custom exception handler',
1347 exc_info=True)
1348
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001349 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001350 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001351 assert isinstance(handle, events.Handle), 'A Handle is required here'
1352 if handle._cancelled:
1353 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001354 assert not isinstance(handle, events.TimerHandle)
1355 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001356
1357 def _add_callback_signalsafe(self, handle):
1358 """Like _add_callback() but called from a signal handler."""
1359 self._add_callback(handle)
1360 self._write_to_self()
1361
Yury Selivanov592ada92014-09-25 12:07:56 -04001362 def _timer_handle_cancelled(self, handle):
1363 """Notification that a TimerHandle has been cancelled."""
1364 if handle._scheduled:
1365 self._timer_cancelled_count += 1
1366
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001367 def _run_once(self):
1368 """Run one full iteration of the event loop.
1369
1370 This calls all currently ready callbacks, polls for I/O,
1371 schedules the resulting callbacks, and finally schedules
1372 'call_later' callbacks.
1373 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001374
Yury Selivanov592ada92014-09-25 12:07:56 -04001375 sched_count = len(self._scheduled)
1376 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1377 self._timer_cancelled_count / sched_count >
1378 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001379 # Remove delayed calls that were cancelled if their number
1380 # is too high
1381 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001382 for handle in self._scheduled:
1383 if handle._cancelled:
1384 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001385 else:
1386 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001387
Victor Stinner68da8fc2014-09-30 18:08:36 +02001388 heapq.heapify(new_scheduled)
1389 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001390 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001391 else:
1392 # Remove delayed calls that were cancelled from head of queue.
1393 while self._scheduled and self._scheduled[0]._cancelled:
1394 self._timer_cancelled_count -= 1
1395 handle = heapq.heappop(self._scheduled)
1396 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001397
1398 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001399 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001400 timeout = 0
1401 elif self._scheduled:
1402 # Compute the desired timeout.
1403 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001404 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001405
Victor Stinner770e48d2014-07-11 11:58:33 +02001406 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001407 t0 = self.time()
1408 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001409 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001410 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001411 level = logging.INFO
1412 else:
1413 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001414 nevent = len(event_list)
1415 if timeout is None:
1416 logger.log(level, 'poll took %.3f ms: %s events',
1417 dt * 1e3, nevent)
1418 elif nevent:
1419 logger.log(level,
1420 'poll %.3f ms took %.3f ms: %s events',
1421 timeout * 1e3, dt * 1e3, nevent)
1422 elif dt >= 1.0:
1423 logger.log(level,
1424 'poll %.3f ms took %.3f ms: timeout',
1425 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001426 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001427 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001428 self._process_events(event_list)
1429
1430 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001431 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001432 while self._scheduled:
1433 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001434 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001435 break
1436 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001437 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001438 self._ready.append(handle)
1439
1440 # This is the only place where callbacks are actually *called*.
1441 # All other places just add them to ready.
1442 # Note: We run all currently scheduled callbacks, but not any
1443 # callbacks scheduled by callbacks run this time around --
1444 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001445 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001446 ntodo = len(self._ready)
1447 for i in range(ntodo):
1448 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001449 if handle._cancelled:
1450 continue
1451 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001452 try:
1453 self._current_handle = handle
1454 t0 = self.time()
1455 handle._run()
1456 dt = self.time() - t0
1457 if dt >= self.slow_callback_duration:
1458 logger.warning('Executing %s took %.3f seconds',
1459 _format_handle(handle), dt)
1460 finally:
1461 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001462 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001463 handle._run()
1464 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001465
Yury Selivanove8944cb2015-05-12 11:43:04 -04001466 def _set_coroutine_wrapper(self, enabled):
1467 try:
1468 set_wrapper = sys.set_coroutine_wrapper
1469 get_wrapper = sys.get_coroutine_wrapper
1470 except AttributeError:
1471 return
1472
1473 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001474 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001475 return
1476
1477 wrapper = coroutines.debug_wrapper
1478 current_wrapper = get_wrapper()
1479
1480 if enabled:
1481 if current_wrapper not in (None, wrapper):
1482 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001483 f"loop.set_debug(True): cannot set debug coroutine "
1484 f"wrapper; another wrapper is already set "
1485 f"{current_wrapper!r}",
1486 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001487 else:
1488 set_wrapper(wrapper)
1489 self._coroutine_wrapper_set = True
1490 else:
1491 if current_wrapper not in (None, wrapper):
1492 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001493 f"loop.set_debug(False): cannot unset debug coroutine "
1494 f"wrapper; another wrapper was set {current_wrapper!r}",
1495 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001496 else:
1497 set_wrapper(None)
1498 self._coroutine_wrapper_set = False
1499
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001500 def get_debug(self):
1501 return self._debug
1502
1503 def set_debug(self, enabled):
1504 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001505
Yury Selivanove8944cb2015-05-12 11:43:04 -04001506 if self.is_running():
1507 self._set_coroutine_wrapper(enabled)