blob: 9584d6355f89b280c3f8ef2350de3fc28a8c6a7b [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
Victor Stinnerf951d282014-06-29 00:46:45 +020032from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070033from . import events
34from . import futures
35from . import tasks
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070036from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037
38
Yury Selivanov6370f342017-12-10 18:36:12 -050039__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040
41
Yury Selivanov592ada92014-09-25 12:07:56 -040042# Minimum number of _scheduled timer handles before cleanup of
43# cancelled handles is performed.
44_MIN_SCHEDULED_TIMER_HANDLES = 100
45
46# Minimum fraction of _scheduled timer handles that are cancelled
47# before cleanup of cancelled handles is performed.
48_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049
Victor Stinnerc94a93a2016-04-01 21:43:39 +020050# Exceptions which must not call the exception handler in fatal error
51# methods (_fatal_error())
52_FATAL_ERROR_IGNORE = (BrokenPipeError,
53 ConnectionResetError, ConnectionAbortedError)
54
55
Victor Stinner0e6f52a2014-06-20 17:34:15 +020056def _format_handle(handle):
57 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040058 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020059 # format the task
60 return repr(cb.__self__)
61 else:
62 return str(handle)
63
64
Victor Stinneracdb7822014-07-14 18:33:40 +020065def _format_pipe(fd):
66 if fd == subprocess.PIPE:
67 return '<pipe>'
68 elif fd == subprocess.STDOUT:
69 return '<stdout>'
70 else:
71 return repr(fd)
72
73
Yury Selivanov5587d7c2016-09-15 15:45:07 -040074def _set_reuseport(sock):
75 if not hasattr(socket, 'SO_REUSEPORT'):
76 raise ValueError('reuse_port not supported by socket module')
77 else:
78 try:
79 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
80 except OSError:
81 raise ValueError('reuse_port not supported by socket module, '
82 'SO_REUSEPORT defined but not implemented.')
83
84
Yury Selivanova1a8b7d2016-11-09 15:47:00 -050085def _is_stream_socket(sock):
86 # Linux's socket.type is a bitmask that can include extra info
87 # about socket, therefore we can't do simple
88 # `sock_type == socket.SOCK_STREAM`.
89 return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM
90
91
92def _is_dgram_socket(sock):
93 # Linux's socket.type is a bitmask that can include extra info
94 # about socket, therefore we can't do simple
95 # `sock_type == socket.SOCK_DGRAM`.
96 return (sock.type & socket.SOCK_DGRAM) == socket.SOCK_DGRAM
97
98
Yury Selivanovd5c2a622015-12-16 19:31:17 -050099def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400100 # Try to skip getaddrinfo if "host" is already an IP. Users might have
101 # handled name resolution in their own code and pass in resolved IPs.
102 if not hasattr(socket, 'inet_pton'):
103 return
104
105 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
106 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 return None
108
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500109 if type == socket.SOCK_STREAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500110 # Linux only:
111 # getaddrinfo() can raise when socket.type is a bit mask.
112 # So if socket.type is a bit mask of SOCK_STREAM, and say
113 # SOCK_NONBLOCK, we simply return None, which will trigger
114 # a call to getaddrinfo() letting it process this request.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500115 proto = socket.IPPROTO_TCP
116 elif type == socket.SOCK_DGRAM:
117 proto = socket.IPPROTO_UDP
118 else:
119 return None
120
Yury Selivanova7146162016-06-02 16:51:07 -0400121 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400122 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700123 elif isinstance(port, bytes) and port == b'':
124 port = 0
125 elif isinstance(port, str) and port == '':
126 port = 0
127 else:
128 # If port's a service name like "http", don't skip getaddrinfo.
129 try:
130 port = int(port)
131 except (TypeError, ValueError):
132 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400133
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400134 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500135 afs = [socket.AF_INET]
136 if hasattr(socket, 'AF_INET6'):
137 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 else:
139 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500140
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400141 if isinstance(host, bytes):
142 host = host.decode('idna')
143 if '%' in host:
144 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
145 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500146 return None
147
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400148 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500149 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150 socket.inet_pton(af, host)
151 # The host has already been resolved.
152 return af, type, proto, '', (host, port)
153 except OSError:
154 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500155
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400156 # "host" is not an IP address.
157 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500158
159
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400160def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
161 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500162 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400163 info = _ipaddr_info(host, port, family, type, proto)
164 if info is not None:
165 # "host" is already a resolved IP.
166 fut = loop.create_future()
167 fut.set_result([info])
168 return fut
169 else:
170 return loop.getaddrinfo(host, port, family=family, type=type,
171 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100172
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700173
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100174def _run_until_complete_cb(fut):
175 exc = fut._exception
Yury Selivanov6370f342017-12-10 18:36:12 -0500176 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100177 # Issue #22429: run_forever() already finished, no need to
178 # stop it.
179 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800180 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100181
182
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700183class Server(events.AbstractServer):
184
185 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200186 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700187 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200188 self._active_count = 0
189 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700190
Victor Stinnere912e652014-07-12 03:11:53 +0200191 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500192 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200193
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200194 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200196 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700197
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200198 def _detach(self):
199 assert self._active_count > 0
200 self._active_count -= 1
201 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700202 self._wakeup()
203
204 def close(self):
205 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 if sockets is None:
207 return
208 self.sockets = None
209 for sock in sockets:
210 self._loop._stop_serving(sock)
211 if self._active_count == 0:
212 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213
214 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200215 waiters = self._waiters
216 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700217 for waiter in waiters:
218 if not waiter.done():
219 waiter.set_result(waiter)
220
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200221 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200222 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700223 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400224 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200225 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200226 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227
228
229class BaseEventLoop(events.AbstractEventLoop):
230
231 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400232 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200233 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800234 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700235 self._ready = collections.deque()
236 self._scheduled = []
237 self._default_executor = None
238 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100239 # Identifier of the thread running the event loop, or None if the
240 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100241 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100242 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500243 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800244 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200245 # In debug mode, if the execution of a callback or a step of a task
246 # exceed this duration in seconds, the slow callback/task is logged.
247 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100248 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400249 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400250 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700251
Yury Selivanov0a91d482016-09-15 13:24:03 -0400252 if hasattr(sys, 'get_asyncgen_hooks'):
253 # Python >= 3.6
254 # A weak set of all asynchronous generators that are
255 # being iterated by the loop.
256 self._asyncgens = weakref.WeakSet()
257 else:
258 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700259
260 # Set to True when `loop.shutdown_asyncgens` is called.
261 self._asyncgens_shutdown_called = False
262
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200263 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500264 return (
265 f'<{self.__class__.__name__} running={self.is_running()} '
266 f'closed={self.is_closed()} debug={self.get_debug()}>'
267 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200268
Yury Selivanov7661db62016-05-16 15:38:39 -0400269 def create_future(self):
270 """Create a Future object attached to the loop."""
271 return futures.Future(loop=self)
272
Victor Stinner896a25a2014-07-08 11:29:25 +0200273 def create_task(self, coro):
274 """Schedule a coroutine object.
275
Victor Stinneracdb7822014-07-14 18:33:40 +0200276 Return a task object.
277 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100278 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400279 if self._task_factory is None:
280 task = tasks.Task(coro, loop=self)
281 if task._source_traceback:
282 del task._source_traceback[-1]
283 else:
284 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200285 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200286
Yury Selivanov740169c2015-05-11 14:23:38 -0400287 def set_task_factory(self, factory):
288 """Set a task factory that will be used by loop.create_task().
289
290 If factory is None the default task factory will be set.
291
292 If factory is a callable, it should have a signature matching
293 '(loop, coro)', where 'loop' will be a reference to the active
294 event loop, 'coro' will be a coroutine object. The callable
295 must return a Future.
296 """
297 if factory is not None and not callable(factory):
298 raise TypeError('task factory must be a callable or None')
299 self._task_factory = factory
300
301 def get_task_factory(self):
302 """Return a task factory, or None if the default one is in use."""
303 return self._task_factory
304
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 def _make_socket_transport(self, sock, protocol, waiter=None, *,
306 extra=None, server=None):
307 """Create socket transport."""
308 raise NotImplementedError
309
Victor Stinner15cc6782015-01-09 00:09:10 +0100310 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
311 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700312 extra=None, server=None):
313 """Create SSL transport."""
314 raise NotImplementedError
315
316 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200317 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700318 """Create datagram transport."""
319 raise NotImplementedError
320
321 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
322 extra=None):
323 """Create read pipe transport."""
324 raise NotImplementedError
325
326 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
327 extra=None):
328 """Create write pipe transport."""
329 raise NotImplementedError
330
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200331 async def _make_subprocess_transport(self, protocol, args, shell,
332 stdin, stdout, stderr, bufsize,
333 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700334 """Create subprocess transport."""
335 raise NotImplementedError
336
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700337 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200338 """Write a byte to self-pipe, to wake up the event loop.
339
340 This may be called from a different thread.
341
342 The subclass is responsible for implementing the self-pipe.
343 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344 raise NotImplementedError
345
346 def _process_events(self, event_list):
347 """Process selector events."""
348 raise NotImplementedError
349
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200350 def _check_closed(self):
351 if self._closed:
352 raise RuntimeError('Event loop is closed')
353
Yury Selivanoveb636452016-09-08 22:01:51 -0700354 def _asyncgen_finalizer_hook(self, agen):
355 self._asyncgens.discard(agen)
356 if not self.is_closed():
357 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400358 # Wake up the loop if the finalizer was called from
359 # a different thread.
360 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700361
362 def _asyncgen_firstiter_hook(self, agen):
363 if self._asyncgens_shutdown_called:
364 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500365 f"asynchronous generator {agen!r} was scheduled after "
366 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700367 ResourceWarning, source=self)
368
369 self._asyncgens.add(agen)
370
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200371 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700372 """Shutdown all active asynchronous generators."""
373 self._asyncgens_shutdown_called = True
374
Yury Selivanov0a91d482016-09-15 13:24:03 -0400375 if self._asyncgens is None or not len(self._asyncgens):
376 # If Python version is <3.6 or we don't have any asynchronous
377 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700378 return
379
380 closing_agens = list(self._asyncgens)
381 self._asyncgens.clear()
382
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200383 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700384 *[ag.aclose() for ag in closing_agens],
385 return_exceptions=True,
386 loop=self)
387
Yury Selivanoveb636452016-09-08 22:01:51 -0700388 for result, agen in zip(results, closing_agens):
389 if isinstance(result, Exception):
390 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500391 'message': f'an error occurred during closing of '
392 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700393 'exception': result,
394 'asyncgen': agen
395 })
396
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700397 def run_forever(self):
398 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200399 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100400 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400401 raise RuntimeError('This event loop is already running')
402 if events._get_running_loop() is not None:
403 raise RuntimeError(
404 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400405 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100406 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400407 if self._asyncgens is not None:
408 old_agen_hooks = sys.get_asyncgen_hooks()
409 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
410 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400412 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700413 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800414 self._run_once()
415 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700416 break
417 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800418 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100419 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400420 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400421 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400422 if self._asyncgens is not None:
423 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700424
425 def run_until_complete(self, future):
426 """Run until the Future is done.
427
428 If the argument is a coroutine, it is wrapped in a Task.
429
Victor Stinneracdb7822014-07-14 18:33:40 +0200430 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 with the same coroutine twice -- it would wrap it in two
432 different Tasks and that can't be good.
433
434 Return the Future's result, or raise its exception.
435 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200436 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200437
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700438 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400439 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200440 if new_task:
441 # An exception is raised if the future didn't complete, so there
442 # is no need to log the "destroy pending task" message
443 future._log_destroy_pending = False
444
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100445 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200446 try:
447 self.run_forever()
448 except:
449 if new_task and future.done() and not future.cancelled():
450 # The coroutine raised a BaseException. Consume the exception
451 # to not log a warning, the caller doesn't have access to the
452 # local task.
453 future.exception()
454 raise
jimmylai21b3e042017-05-22 22:32:46 -0700455 finally:
456 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700457 if not future.done():
458 raise RuntimeError('Event loop stopped before Future completed.')
459
460 return future.result()
461
462 def stop(self):
463 """Stop running the event loop.
464
Guido van Rossum41f69f42015-11-19 13:28:47 -0800465 Every callback already scheduled will still run. This simply informs
466 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800468 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700469
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200470 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700471 """Close the event loop.
472
473 This clears the queues and shuts down the executor,
474 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200475
476 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700477 """
Victor Stinner956de692014-12-26 21:07:52 +0100478 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200479 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200480 if self._closed:
481 return
Victor Stinnere912e652014-07-12 03:11:53 +0200482 if self._debug:
483 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400484 self._closed = True
485 self._ready.clear()
486 self._scheduled.clear()
487 executor = self._default_executor
488 if executor is not None:
489 self._default_executor = None
490 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200491
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200492 def is_closed(self):
493 """Returns True if the event loop was closed."""
494 return self._closed
495
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900496 def __del__(self):
497 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500498 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900499 source=self)
500 if not self.is_running():
501 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100502
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700503 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200504 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100505 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506
507 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200508 """Return the time according to the event loop's clock.
509
510 This is a float expressed in seconds since an epoch, but the
511 epoch, precision, accuracy and drift are unspecified and may
512 differ per event loop.
513 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 return time.monotonic()
515
516 def call_later(self, delay, callback, *args):
517 """Arrange for a callback to be called at a given time.
518
519 Return a Handle: an opaque object with a cancel() method that
520 can be used to cancel the call.
521
522 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200523 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 Each callback will be called exactly once. If two callbacks
526 are scheduled for exactly the same time, it undefined which
527 will be called first.
528
529 Any positional arguments after the callback will be passed to
530 the callback when it is called.
531 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200532 timer = self.call_at(self.time() + delay, callback, *args)
533 if timer._source_traceback:
534 del timer._source_traceback[-1]
535 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700536
537 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200538 """Like call_later(), but uses an absolute time.
539
540 Absolute time corresponds to the event loop's time() method.
541 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100542 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100543 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100544 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700545 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500546 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200547 if timer._source_traceback:
548 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400550 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 return timer
552
553 def call_soon(self, callback, *args):
554 """Arrange for a callback to be called as soon as possible.
555
Victor Stinneracdb7822014-07-14 18:33:40 +0200556 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557 order in which they are registered. Each callback will be
558 called exactly once.
559
560 Any positional arguments after the callback will be passed to
561 the callback when it is called.
562 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700563 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100564 if self._debug:
565 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700566 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100567 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200568 if handle._source_traceback:
569 del handle._source_traceback[-1]
570 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100571
Yury Selivanov491a9122016-11-03 15:09:24 -0700572 def _check_callback(self, callback, method):
573 if (coroutines.iscoroutine(callback) or
574 coroutines.iscoroutinefunction(callback)):
575 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500576 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700577 if not callable(callback):
578 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500579 f'a callable object was expected by {method}(), '
580 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700581
Victor Stinner956de692014-12-26 21:07:52 +0100582 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500583 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200584 if handle._source_traceback:
585 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700586 self._ready.append(handle)
587 return handle
588
Victor Stinner956de692014-12-26 21:07:52 +0100589 def _check_thread(self):
590 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100591
Victor Stinneracdb7822014-07-14 18:33:40 +0200592 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100593 likely behave incorrectly when the assumption is violated.
594
Victor Stinneracdb7822014-07-14 18:33:40 +0200595 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100596 responsible for checking this condition for performance reasons.
597 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100598 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200599 return
Victor Stinner956de692014-12-26 21:07:52 +0100600 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100601 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100602 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200603 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100604 "than the current one")
605
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700606 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200607 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700608 self._check_closed()
609 if self._debug:
610 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100611 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200612 if handle._source_traceback:
613 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700614 self._write_to_self()
615 return handle
616
Yury Selivanov740169c2015-05-11 14:23:38 -0400617 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100618 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700619 if self._debug:
620 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 if executor is None:
622 executor = self._default_executor
623 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400624 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400626 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700627
628 def set_default_executor(self, executor):
629 self._default_executor = executor
630
Victor Stinnere912e652014-07-12 03:11:53 +0200631 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500632 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200633 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500634 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200635 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500636 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200637 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500638 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200639 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500640 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200641 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200642 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200643
644 t0 = self.time()
645 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
646 dt = self.time() - t0
647
Yury Selivanov6370f342017-12-10 18:36:12 -0500648 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200649 if dt >= self.slow_callback_duration:
650 logger.info(msg)
651 else:
652 logger.debug(msg)
653 return addrinfo
654
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700655 def getaddrinfo(self, host, port, *,
656 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400657 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200658 return self.run_in_executor(None, self._getaddrinfo_debug,
659 host, port, family, type, proto, flags)
660 else:
661 return self.run_in_executor(None, socket.getaddrinfo,
662 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700663
664 def getnameinfo(self, sockaddr, flags=0):
665 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
666
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200667 async def create_connection(self, protocol_factory, host=None, port=None,
668 *, ssl=None, family=0,
669 proto=0, flags=0, sock=None,
670 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200671 """Connect to a TCP server.
672
673 Create a streaming transport connection to a given Internet host and
674 port: socket family AF_INET or socket.AF_INET6 depending on host (or
675 family if specified), socket type SOCK_STREAM. protocol_factory must be
676 a callable returning a protocol instance.
677
678 This method is a coroutine which will try to establish the connection
679 in the background. When successful, the coroutine returns a
680 (transport, protocol) pair.
681 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700682 if server_hostname is not None and not ssl:
683 raise ValueError('server_hostname is only meaningful with ssl')
684
685 if server_hostname is None and ssl:
686 # Use host as default for server_hostname. It is an error
687 # if host is empty or not set, e.g. when an
688 # already-connected socket was passed or when only a port
689 # is given. To avoid this error, you can pass
690 # server_hostname='' -- this will bypass the hostname
691 # check. (This also means that if host is a numeric
692 # IP/IPv6 address, we will attempt to verify that exact
693 # address; this will probably fail, but it is possible to
694 # create a certificate for a specific IP address, so we
695 # don't judge it here.)
696 if not host:
697 raise ValueError('You must set server_hostname '
698 'when using ssl without a host')
699 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700700
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700701 if host is not None or port is not None:
702 if sock is not None:
703 raise ValueError(
704 'host/port and sock can not be specified at the same time')
705
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400706 f1 = _ensure_resolved((host, port), family=family,
707 type=socket.SOCK_STREAM, proto=proto,
708 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700709 fs = [f1]
710 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400711 f2 = _ensure_resolved(local_addr, family=family,
712 type=socket.SOCK_STREAM, proto=proto,
713 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700714 fs.append(f2)
715 else:
716 f2 = None
717
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200718 await tasks.wait(fs, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700719
720 infos = f1.result()
721 if not infos:
722 raise OSError('getaddrinfo() returned empty list')
723 if f2 is not None:
724 laddr_infos = f2.result()
725 if not laddr_infos:
726 raise OSError('getaddrinfo() returned empty list')
727
728 exceptions = []
729 for family, type, proto, cname, address in infos:
730 try:
731 sock = socket.socket(family=family, type=type, proto=proto)
732 sock.setblocking(False)
733 if f2 is not None:
734 for _, _, _, _, laddr in laddr_infos:
735 try:
736 sock.bind(laddr)
737 break
738 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500739 msg = (
740 f'error while attempting to bind on '
741 f'address {laddr!r}: '
742 f'{exc.strerror.lower()}'
743 )
744 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700745 exceptions.append(exc)
746 else:
747 sock.close()
748 sock = None
749 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200750 if self._debug:
751 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200752 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700753 except OSError as exc:
754 if sock is not None:
755 sock.close()
756 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200757 except:
758 if sock is not None:
759 sock.close()
760 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700761 else:
762 break
763 else:
764 if len(exceptions) == 1:
765 raise exceptions[0]
766 else:
767 # If they all have the same str(), raise one.
768 model = str(exceptions[0])
769 if all(str(exc) == model for exc in exceptions):
770 raise exceptions[0]
771 # Raise a combined exception so the user can see all
772 # the various error messages.
773 raise OSError('Multiple exceptions: {}'.format(
774 ', '.join(str(exc) for exc in exceptions)))
775
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500776 else:
777 if sock is None:
778 raise ValueError(
779 'host and port was not specified and no sock specified')
Yury Selivanovdab05842016-11-21 17:47:27 -0500780 if not _is_stream_socket(sock):
781 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
782 # are SOCK_STREAM.
783 # We support passing AF_UNIX sockets even though we have
784 # a dedicated API for that: create_unix_connection.
785 # Disallowing AF_UNIX in this method, breaks backwards
786 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500787 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500788 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700789
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200790 transport, protocol = await self._create_connection_transport(
Yury Selivanovb057c522014-02-18 12:15:06 -0500791 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200792 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200793 # Get the socket from the transport because SSL transport closes
794 # the old socket and creates a new SSL socket
795 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200796 logger.debug("%r connected to %s:%r: (%r, %r)",
797 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500798 return transport, protocol
799
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200800 async def _create_connection_transport(self, sock, protocol_factory, ssl,
801 server_hostname, server_side=False):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400802
803 sock.setblocking(False)
804
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700805 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400806 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700807 if ssl:
808 sslcontext = None if isinstance(ssl, bool) else ssl
809 transport = self._make_ssl_transport(
810 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400811 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700812 else:
813 transport = self._make_socket_transport(sock, protocol, waiter)
814
Victor Stinner29ad0112015-01-15 00:04:21 +0100815 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200816 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100817 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100818 transport.close()
819 raise
820
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700821 return transport, protocol
822
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200823 async def create_datagram_endpoint(self, protocol_factory,
824 local_addr=None, remote_addr=None, *,
825 family=0, proto=0, flags=0,
826 reuse_address=None, reuse_port=None,
827 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700828 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700829 if sock is not None:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500830 if not _is_dgram_socket(sock):
831 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500832 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700833 if (local_addr or remote_addr or
834 family or proto or flags or
835 reuse_address or reuse_port or allow_broadcast):
836 # show the problematic kwargs in exception msg
837 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
838 family=family, proto=proto, flags=flags,
839 reuse_address=reuse_address, reuse_port=reuse_port,
840 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500841 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700842 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500843 f'socket modifier keyword arguments can not be used '
844 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700845 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700846 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700847 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700848 if not (local_addr or remote_addr):
849 if family == 0:
850 raise ValueError('unexpected address family')
851 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100852 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
853 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100854 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100855 raise TypeError('string is expected')
856 addr_pairs_info = (((family, proto),
857 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700858 else:
859 # join address by (family, protocol)
860 addr_infos = collections.OrderedDict()
861 for idx, addr in ((0, local_addr), (1, remote_addr)):
862 if addr is not None:
863 assert isinstance(addr, tuple) and len(addr) == 2, (
864 '2-tuple is expected')
865
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200866 infos = await _ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400867 addr, family=family, type=socket.SOCK_DGRAM,
868 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700869 if not infos:
870 raise OSError('getaddrinfo() returned empty list')
871
872 for fam, _, pro, _, address in infos:
873 key = (fam, pro)
874 if key not in addr_infos:
875 addr_infos[key] = [None, None]
876 addr_infos[key][idx] = address
877
878 # each addr has to have info for each (family, proto) pair
879 addr_pairs_info = [
880 (key, addr_pair) for key, addr_pair in addr_infos.items()
881 if not ((local_addr and addr_pair[0] is None) or
882 (remote_addr and addr_pair[1] is None))]
883
884 if not addr_pairs_info:
885 raise ValueError('can not get address information')
886
887 exceptions = []
888
889 if reuse_address is None:
890 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
891
892 for ((family, proto),
893 (local_address, remote_address)) in addr_pairs_info:
894 sock = None
895 r_addr = None
896 try:
897 sock = socket.socket(
898 family=family, type=socket.SOCK_DGRAM, proto=proto)
899 if reuse_address:
900 sock.setsockopt(
901 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
902 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400903 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700904 if allow_broadcast:
905 sock.setsockopt(
906 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
907 sock.setblocking(False)
908
909 if local_addr:
910 sock.bind(local_address)
911 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200912 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700913 r_addr = remote_address
914 except OSError as exc:
915 if sock is not None:
916 sock.close()
917 exceptions.append(exc)
918 except:
919 if sock is not None:
920 sock.close()
921 raise
922 else:
923 break
924 else:
925 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700926
927 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400928 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700929 transport = self._make_datagram_transport(
930 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200931 if self._debug:
932 if local_addr:
933 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
934 "created: (%r, %r)",
935 local_addr, remote_addr, transport, protocol)
936 else:
937 logger.debug("Datagram endpoint remote_addr=%r created: "
938 "(%r, %r)",
939 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100940
941 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200942 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +0100943 except:
944 transport.close()
945 raise
946
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700947 return transport, protocol
948
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200949 async def _create_server_getaddrinfo(self, host, port, family, flags):
950 infos = await _ensure_resolved((host, port), family=family,
951 type=socket.SOCK_STREAM,
952 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200953 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -0500954 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200955 return infos
956
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200957 async def create_server(self, protocol_factory, host=None, port=None,
958 *,
959 family=socket.AF_UNSPEC,
960 flags=socket.AI_PASSIVE,
961 sock=None,
962 backlog=100,
963 ssl=None,
964 reuse_address=None,
965 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200966 """Create a TCP server.
967
Yury Selivanov6370f342017-12-10 18:36:12 -0500968 The host parameter can be a string, in that case the TCP server is
969 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200970
971 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500972 the TCP server is bound to all hosts of the sequence. If a host
973 appears multiple times (possibly indirectly e.g. when hostnames
974 resolve to the same IP address), the server is only bound once to that
975 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200976
Victor Stinneracdb7822014-07-14 18:33:40 +0200977 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200978
979 This method is a coroutine.
980 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700981 if isinstance(ssl, bool):
982 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700983 if host is not None or port is not None:
984 if sock is not None:
985 raise ValueError(
986 'host/port and sock can not be specified at the same time')
987
988 AF_INET6 = getattr(socket, 'AF_INET6', 0)
989 if reuse_address is None:
990 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
991 sockets = []
992 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200993 hosts = [None]
994 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +0300995 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200996 hosts = [host]
997 else:
998 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700999
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001000 fs = [self._create_server_getaddrinfo(host, port, family=family,
1001 flags=flags)
1002 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001003 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001004 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001005
1006 completed = False
1007 try:
1008 for res in infos:
1009 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001010 try:
1011 sock = socket.socket(af, socktype, proto)
1012 except socket.error:
1013 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001014 if self._debug:
1015 logger.warning('create_server() failed to create '
1016 'socket.socket(%r, %r, %r)',
1017 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001018 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001019 sockets.append(sock)
1020 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001021 sock.setsockopt(
1022 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1023 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001024 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001025 # Disable IPv4/IPv6 dual stack support (enabled by
1026 # default on Linux) which makes a single socket
1027 # listen on both address families.
1028 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1029 sock.setsockopt(socket.IPPROTO_IPV6,
1030 socket.IPV6_V6ONLY,
1031 True)
1032 try:
1033 sock.bind(sa)
1034 except OSError as err:
1035 raise OSError(err.errno, 'error while attempting '
1036 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001037 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001038 completed = True
1039 finally:
1040 if not completed:
1041 for sock in sockets:
1042 sock.close()
1043 else:
1044 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001045 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanovdab05842016-11-21 17:47:27 -05001046 if not _is_stream_socket(sock):
Yury Selivanov6370f342017-12-10 18:36:12 -05001047 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001048 sockets = [sock]
1049
1050 server = Server(self, sockets)
1051 for sock in sockets:
1052 sock.listen(backlog)
1053 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001054 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001055 if self._debug:
1056 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001057 return server
1058
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001059 async def connect_accepted_socket(self, protocol_factory, sock,
1060 *, ssl=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001061 """Handle an accepted connection.
1062
1063 This is used by servers that accept connections outside of
1064 asyncio but that use asyncio to handle connections.
1065
1066 This method is a coroutine. When completed, the coroutine
1067 returns a (transport, protocol) pair.
1068 """
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001069 if not _is_stream_socket(sock):
Yury Selivanov6370f342017-12-10 18:36:12 -05001070 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001071
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001072 transport, protocol = await self._create_connection_transport(
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001073 sock, protocol_factory, ssl, '', server_side=True)
1074 if self._debug:
1075 # Get the socket from the transport because SSL transport closes
1076 # the old socket and creates a new SSL socket
1077 sock = transport.get_extra_info('socket')
1078 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1079 return transport, protocol
1080
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001081 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001082 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001083 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001084 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001085
1086 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001087 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001088 except:
1089 transport.close()
1090 raise
1091
Victor Stinneracdb7822014-07-14 18:33:40 +02001092 if self._debug:
1093 logger.debug('Read pipe %r connected: (%r, %r)',
1094 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001095 return transport, protocol
1096
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001097 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001098 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001099 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001100 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001101
1102 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001103 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001104 except:
1105 transport.close()
1106 raise
1107
Victor Stinneracdb7822014-07-14 18:33:40 +02001108 if self._debug:
1109 logger.debug('Write pipe %r connected: (%r, %r)',
1110 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001111 return transport, protocol
1112
Victor Stinneracdb7822014-07-14 18:33:40 +02001113 def _log_subprocess(self, msg, stdin, stdout, stderr):
1114 info = [msg]
1115 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001116 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001117 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001118 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001119 else:
1120 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001121 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001122 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001123 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001124 logger.debug(' '.join(info))
1125
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001126 async def subprocess_shell(self, protocol_factory, cmd, *,
1127 stdin=subprocess.PIPE,
1128 stdout=subprocess.PIPE,
1129 stderr=subprocess.PIPE,
1130 universal_newlines=False,
1131 shell=True, bufsize=0,
1132 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001133 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001134 raise ValueError("cmd must be a string")
1135 if universal_newlines:
1136 raise ValueError("universal_newlines must be False")
1137 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001138 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001139 if bufsize != 0:
1140 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001141 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001142 if self._debug:
1143 # don't log parameters: they may contain sensitive information
1144 # (password) and may be too long
1145 debug_log = 'run shell command %r' % cmd
1146 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001147 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001148 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001149 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001150 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001151 return transport, protocol
1152
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001153 async def subprocess_exec(self, protocol_factory, program, *args,
1154 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1155 stderr=subprocess.PIPE, universal_newlines=False,
1156 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001157 if universal_newlines:
1158 raise ValueError("universal_newlines must be False")
1159 if shell:
1160 raise ValueError("shell must be False")
1161 if bufsize != 0:
1162 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001163 popen_args = (program,) + args
1164 for arg in popen_args:
1165 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001166 raise TypeError(
1167 f"program arguments must be a bytes or text string, "
1168 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001169 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001170 if self._debug:
1171 # don't log parameters: they may contain sensitive information
1172 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001173 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001174 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001175 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001176 protocol, popen_args, False, stdin, stdout, stderr,
1177 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001178 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001179 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001180 return transport, protocol
1181
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001182 def get_exception_handler(self):
1183 """Return an exception handler, or None if the default one is in use.
1184 """
1185 return self._exception_handler
1186
Yury Selivanov569efa22014-02-18 18:02:19 -05001187 def set_exception_handler(self, handler):
1188 """Set handler as the new event loop exception handler.
1189
1190 If handler is None, the default exception handler will
1191 be set.
1192
1193 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001194 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001195 will be a reference to the active event loop, 'context'
1196 will be a dict object (see `call_exception_handler()`
1197 documentation for details about context).
1198 """
1199 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001200 raise TypeError(f'A callable object or None is expected, '
1201 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001202 self._exception_handler = handler
1203
1204 def default_exception_handler(self, context):
1205 """Default exception handler.
1206
1207 This is called when an exception occurs and no exception
1208 handler is set, and can be called by a custom exception
1209 handler that wants to defer to the default behavior.
1210
Antoine Pitrou921e9432017-11-07 17:23:29 +01001211 This default handler logs the error message and other
1212 context-dependent information. In debug mode, a truncated
1213 stack trace is also appended showing where the given object
1214 (e.g. a handle or future or task) was created, if any.
1215
Victor Stinneracdb7822014-07-14 18:33:40 +02001216 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001217 `call_exception_handler()`.
1218 """
1219 message = context.get('message')
1220 if not message:
1221 message = 'Unhandled exception in event loop'
1222
1223 exception = context.get('exception')
1224 if exception is not None:
1225 exc_info = (type(exception), exception, exception.__traceback__)
1226 else:
1227 exc_info = False
1228
Yury Selivanov6370f342017-12-10 18:36:12 -05001229 if ('source_traceback' not in context and
1230 self._current_handle is not None and
1231 self._current_handle._source_traceback):
1232 context['handle_traceback'] = \
1233 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001234
Yury Selivanov569efa22014-02-18 18:02:19 -05001235 log_lines = [message]
1236 for key in sorted(context):
1237 if key in {'message', 'exception'}:
1238 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001239 value = context[key]
1240 if key == 'source_traceback':
1241 tb = ''.join(traceback.format_list(value))
1242 value = 'Object created at (most recent call last):\n'
1243 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001244 elif key == 'handle_traceback':
1245 tb = ''.join(traceback.format_list(value))
1246 value = 'Handle created at (most recent call last):\n'
1247 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001248 else:
1249 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001250 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001251
1252 logger.error('\n'.join(log_lines), exc_info=exc_info)
1253
1254 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001255 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001256
Victor Stinneracdb7822014-07-14 18:33:40 +02001257 The context argument is a dict containing the following keys:
1258
Yury Selivanov569efa22014-02-18 18:02:19 -05001259 - 'message': Error message;
1260 - 'exception' (optional): Exception object;
1261 - 'future' (optional): Future instance;
1262 - 'handle' (optional): Handle instance;
1263 - 'protocol' (optional): Protocol instance;
1264 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001265 - 'socket' (optional): Socket instance;
1266 - 'asyncgen' (optional): Asynchronous generator that caused
1267 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001268
Victor Stinneracdb7822014-07-14 18:33:40 +02001269 New keys maybe introduced in the future.
1270
1271 Note: do not overload this method in an event loop subclass.
1272 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001273 `set_exception_handler()` method.
1274 """
1275 if self._exception_handler is None:
1276 try:
1277 self.default_exception_handler(context)
1278 except Exception:
1279 # Second protection layer for unexpected errors
1280 # in the default implementation, as well as for subclassed
1281 # event loops with overloaded "default_exception_handler".
1282 logger.error('Exception in default exception handler',
1283 exc_info=True)
1284 else:
1285 try:
1286 self._exception_handler(self, context)
1287 except Exception as exc:
1288 # Exception in the user set custom exception handler.
1289 try:
1290 # Let's try default handler.
1291 self.default_exception_handler({
1292 'message': 'Unhandled error in exception handler',
1293 'exception': exc,
1294 'context': context,
1295 })
1296 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001297 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001298 # overloaded.
1299 logger.error('Exception in default exception handler '
1300 'while handling an unexpected error '
1301 'in custom exception handler',
1302 exc_info=True)
1303
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001304 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001305 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001306 assert isinstance(handle, events.Handle), 'A Handle is required here'
1307 if handle._cancelled:
1308 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001309 assert not isinstance(handle, events.TimerHandle)
1310 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001311
1312 def _add_callback_signalsafe(self, handle):
1313 """Like _add_callback() but called from a signal handler."""
1314 self._add_callback(handle)
1315 self._write_to_self()
1316
Yury Selivanov592ada92014-09-25 12:07:56 -04001317 def _timer_handle_cancelled(self, handle):
1318 """Notification that a TimerHandle has been cancelled."""
1319 if handle._scheduled:
1320 self._timer_cancelled_count += 1
1321
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001322 def _run_once(self):
1323 """Run one full iteration of the event loop.
1324
1325 This calls all currently ready callbacks, polls for I/O,
1326 schedules the resulting callbacks, and finally schedules
1327 'call_later' callbacks.
1328 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001329
Yury Selivanov592ada92014-09-25 12:07:56 -04001330 sched_count = len(self._scheduled)
1331 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1332 self._timer_cancelled_count / sched_count >
1333 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001334 # Remove delayed calls that were cancelled if their number
1335 # is too high
1336 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001337 for handle in self._scheduled:
1338 if handle._cancelled:
1339 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001340 else:
1341 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001342
Victor Stinner68da8fc2014-09-30 18:08:36 +02001343 heapq.heapify(new_scheduled)
1344 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001345 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001346 else:
1347 # Remove delayed calls that were cancelled from head of queue.
1348 while self._scheduled and self._scheduled[0]._cancelled:
1349 self._timer_cancelled_count -= 1
1350 handle = heapq.heappop(self._scheduled)
1351 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001352
1353 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001354 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001355 timeout = 0
1356 elif self._scheduled:
1357 # Compute the desired timeout.
1358 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001359 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001360
Victor Stinner770e48d2014-07-11 11:58:33 +02001361 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001362 t0 = self.time()
1363 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001364 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001365 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001366 level = logging.INFO
1367 else:
1368 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001369 nevent = len(event_list)
1370 if timeout is None:
1371 logger.log(level, 'poll took %.3f ms: %s events',
1372 dt * 1e3, nevent)
1373 elif nevent:
1374 logger.log(level,
1375 'poll %.3f ms took %.3f ms: %s events',
1376 timeout * 1e3, dt * 1e3, nevent)
1377 elif dt >= 1.0:
1378 logger.log(level,
1379 'poll %.3f ms took %.3f ms: timeout',
1380 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001381 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001382 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001383 self._process_events(event_list)
1384
1385 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001386 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001387 while self._scheduled:
1388 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001389 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001390 break
1391 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001392 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001393 self._ready.append(handle)
1394
1395 # This is the only place where callbacks are actually *called*.
1396 # All other places just add them to ready.
1397 # Note: We run all currently scheduled callbacks, but not any
1398 # callbacks scheduled by callbacks run this time around --
1399 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001400 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001401 ntodo = len(self._ready)
1402 for i in range(ntodo):
1403 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001404 if handle._cancelled:
1405 continue
1406 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001407 try:
1408 self._current_handle = handle
1409 t0 = self.time()
1410 handle._run()
1411 dt = self.time() - t0
1412 if dt >= self.slow_callback_duration:
1413 logger.warning('Executing %s took %.3f seconds',
1414 _format_handle(handle), dt)
1415 finally:
1416 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001417 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001418 handle._run()
1419 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001420
Yury Selivanove8944cb2015-05-12 11:43:04 -04001421 def _set_coroutine_wrapper(self, enabled):
1422 try:
1423 set_wrapper = sys.set_coroutine_wrapper
1424 get_wrapper = sys.get_coroutine_wrapper
1425 except AttributeError:
1426 return
1427
1428 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001429 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001430 return
1431
1432 wrapper = coroutines.debug_wrapper
1433 current_wrapper = get_wrapper()
1434
1435 if enabled:
1436 if current_wrapper not in (None, wrapper):
1437 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001438 f"loop.set_debug(True): cannot set debug coroutine "
1439 f"wrapper; another wrapper is already set "
1440 f"{current_wrapper!r}",
1441 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001442 else:
1443 set_wrapper(wrapper)
1444 self._coroutine_wrapper_set = True
1445 else:
1446 if current_wrapper not in (None, wrapper):
1447 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001448 f"loop.set_debug(False): cannot unset debug coroutine "
1449 f"wrapper; another wrapper was set {current_wrapper!r}",
1450 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001451 else:
1452 set_wrapper(None)
1453 self._coroutine_wrapper_set = False
1454
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001455 def get_debug(self):
1456 return self._debug
1457
1458 def set_debug(self, enabled):
1459 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001460
Yury Selivanove8944cb2015-05-12 11:43:04 -04001461 if self.is_running():
1462 self._set_coroutine_wrapper(enabled)