blob: b6a9384d95b4d23140f45ddb78e2f3c6aa1bd903 [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
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200157class _SendfileNotAvailable(RuntimeError):
158 pass
159
160
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700161class Server(events.AbstractServer):
162
163 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200164 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700165 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200166 self._active_count = 0
167 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700168
Victor Stinnere912e652014-07-12 03:11:53 +0200169 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500170 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200171
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200172 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700173 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200174 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700175
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200176 def _detach(self):
177 assert self._active_count > 0
178 self._active_count -= 1
179 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700180 self._wakeup()
181
182 def close(self):
183 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200184 if sockets is None:
185 return
186 self.sockets = None
187 for sock in sockets:
188 self._loop._stop_serving(sock)
189 if self._active_count == 0:
190 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530192 def get_loop(self):
193 return self._loop
194
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200196 waiters = self._waiters
197 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198 for waiter in waiters:
199 if not waiter.done():
200 waiter.set_result(waiter)
201
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200202 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200203 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400205 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200207 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208
209
210class BaseEventLoop(events.AbstractEventLoop):
211
212 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400213 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200214 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800215 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700216 self._ready = collections.deque()
217 self._scheduled = []
218 self._default_executor = None
219 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100220 # Identifier of the thread running the event loop, or None if the
221 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100222 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100223 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500224 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800225 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200226 # In debug mode, if the execution of a callback or a step of a task
227 # exceed this duration in seconds, the slow callback/task is logged.
228 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100229 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400230 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400231 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700232
Yury Selivanov0a91d482016-09-15 13:24:03 -0400233 if hasattr(sys, 'get_asyncgen_hooks'):
234 # Python >= 3.6
235 # A weak set of all asynchronous generators that are
236 # being iterated by the loop.
237 self._asyncgens = weakref.WeakSet()
238 else:
239 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700240
241 # Set to True when `loop.shutdown_asyncgens` is called.
242 self._asyncgens_shutdown_called = False
243
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200244 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500245 return (
246 f'<{self.__class__.__name__} running={self.is_running()} '
247 f'closed={self.is_closed()} debug={self.get_debug()}>'
248 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200249
Yury Selivanov7661db62016-05-16 15:38:39 -0400250 def create_future(self):
251 """Create a Future object attached to the loop."""
252 return futures.Future(loop=self)
253
Victor Stinner896a25a2014-07-08 11:29:25 +0200254 def create_task(self, coro):
255 """Schedule a coroutine object.
256
Victor Stinneracdb7822014-07-14 18:33:40 +0200257 Return a task object.
258 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100259 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400260 if self._task_factory is None:
261 task = tasks.Task(coro, loop=self)
262 if task._source_traceback:
263 del task._source_traceback[-1]
264 else:
265 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200266 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200267
Yury Selivanov740169c2015-05-11 14:23:38 -0400268 def set_task_factory(self, factory):
269 """Set a task factory that will be used by loop.create_task().
270
271 If factory is None the default task factory will be set.
272
273 If factory is a callable, it should have a signature matching
274 '(loop, coro)', where 'loop' will be a reference to the active
275 event loop, 'coro' will be a coroutine object. The callable
276 must return a Future.
277 """
278 if factory is not None and not callable(factory):
279 raise TypeError('task factory must be a callable or None')
280 self._task_factory = factory
281
282 def get_task_factory(self):
283 """Return a task factory, or None if the default one is in use."""
284 return self._task_factory
285
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700286 def _make_socket_transport(self, sock, protocol, waiter=None, *,
287 extra=None, server=None):
288 """Create socket transport."""
289 raise NotImplementedError
290
Neil Aspinallf7686c12017-12-19 19:45:42 +0000291 def _make_ssl_transport(
292 self, rawsock, protocol, sslcontext, waiter=None,
293 *, server_side=False, server_hostname=None,
294 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500295 ssl_handshake_timeout=None,
296 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 """Create SSL transport."""
298 raise NotImplementedError
299
300 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200301 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700302 """Create datagram transport."""
303 raise NotImplementedError
304
305 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
306 extra=None):
307 """Create read pipe transport."""
308 raise NotImplementedError
309
310 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
311 extra=None):
312 """Create write pipe transport."""
313 raise NotImplementedError
314
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200315 async def _make_subprocess_transport(self, protocol, args, shell,
316 stdin, stdout, stderr, bufsize,
317 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700318 """Create subprocess transport."""
319 raise NotImplementedError
320
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700321 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200322 """Write a byte to self-pipe, to wake up the event loop.
323
324 This may be called from a different thread.
325
326 The subclass is responsible for implementing the self-pipe.
327 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700328 raise NotImplementedError
329
330 def _process_events(self, event_list):
331 """Process selector events."""
332 raise NotImplementedError
333
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200334 def _check_closed(self):
335 if self._closed:
336 raise RuntimeError('Event loop is closed')
337
Yury Selivanoveb636452016-09-08 22:01:51 -0700338 def _asyncgen_finalizer_hook(self, agen):
339 self._asyncgens.discard(agen)
340 if not self.is_closed():
341 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400342 # Wake up the loop if the finalizer was called from
343 # a different thread.
344 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700345
346 def _asyncgen_firstiter_hook(self, agen):
347 if self._asyncgens_shutdown_called:
348 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500349 f"asynchronous generator {agen!r} was scheduled after "
350 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700351 ResourceWarning, source=self)
352
353 self._asyncgens.add(agen)
354
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200355 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700356 """Shutdown all active asynchronous generators."""
357 self._asyncgens_shutdown_called = True
358
Yury Selivanov0a91d482016-09-15 13:24:03 -0400359 if self._asyncgens is None or not len(self._asyncgens):
360 # If Python version is <3.6 or we don't have any asynchronous
361 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700362 return
363
364 closing_agens = list(self._asyncgens)
365 self._asyncgens.clear()
366
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200367 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700368 *[ag.aclose() for ag in closing_agens],
369 return_exceptions=True,
370 loop=self)
371
Yury Selivanoveb636452016-09-08 22:01:51 -0700372 for result, agen in zip(results, closing_agens):
373 if isinstance(result, Exception):
374 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500375 'message': f'an error occurred during closing of '
376 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700377 'exception': result,
378 'asyncgen': agen
379 })
380
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700381 def run_forever(self):
382 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200383 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100384 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400385 raise RuntimeError('This event loop is already running')
386 if events._get_running_loop() is not None:
387 raise RuntimeError(
388 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400389 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100390 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400391 if self._asyncgens is not None:
392 old_agen_hooks = sys.get_asyncgen_hooks()
393 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
394 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700395 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400396 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700397 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800398 self._run_once()
399 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700400 break
401 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800402 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100403 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400404 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400405 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400406 if self._asyncgens is not None:
407 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408
409 def run_until_complete(self, future):
410 """Run until the Future is done.
411
412 If the argument is a coroutine, it is wrapped in a Task.
413
Victor Stinneracdb7822014-07-14 18:33:40 +0200414 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700415 with the same coroutine twice -- it would wrap it in two
416 different Tasks and that can't be good.
417
418 Return the Future's result, or raise its exception.
419 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200420 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200421
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700422 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400423 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200424 if new_task:
425 # An exception is raised if the future didn't complete, so there
426 # is no need to log the "destroy pending task" message
427 future._log_destroy_pending = False
428
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100429 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200430 try:
431 self.run_forever()
432 except:
433 if new_task and future.done() and not future.cancelled():
434 # The coroutine raised a BaseException. Consume the exception
435 # to not log a warning, the caller doesn't have access to the
436 # local task.
437 future.exception()
438 raise
jimmylai21b3e042017-05-22 22:32:46 -0700439 finally:
440 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700441 if not future.done():
442 raise RuntimeError('Event loop stopped before Future completed.')
443
444 return future.result()
445
446 def stop(self):
447 """Stop running the event loop.
448
Guido van Rossum41f69f42015-11-19 13:28:47 -0800449 Every callback already scheduled will still run. This simply informs
450 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700451 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800452 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700453
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200454 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700455 """Close the event loop.
456
457 This clears the queues and shuts down the executor,
458 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200459
460 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700461 """
Victor Stinner956de692014-12-26 21:07:52 +0100462 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200463 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200464 if self._closed:
465 return
Victor Stinnere912e652014-07-12 03:11:53 +0200466 if self._debug:
467 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400468 self._closed = True
469 self._ready.clear()
470 self._scheduled.clear()
471 executor = self._default_executor
472 if executor is not None:
473 self._default_executor = None
474 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200475
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200476 def is_closed(self):
477 """Returns True if the event loop was closed."""
478 return self._closed
479
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900480 def __del__(self):
481 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500482 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900483 source=self)
484 if not self.is_running():
485 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100486
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700487 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200488 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100489 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490
491 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200492 """Return the time according to the event loop's clock.
493
494 This is a float expressed in seconds since an epoch, but the
495 epoch, precision, accuracy and drift are unspecified and may
496 differ per event loop.
497 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700498 return time.monotonic()
499
500 def call_later(self, delay, callback, *args):
501 """Arrange for a callback to be called at a given time.
502
503 Return a Handle: an opaque object with a cancel() method that
504 can be used to cancel the call.
505
506 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200507 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700508
509 Each callback will be called exactly once. If two callbacks
510 are scheduled for exactly the same time, it undefined which
511 will be called first.
512
513 Any positional arguments after the callback will be passed to
514 the callback when it is called.
515 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200516 timer = self.call_at(self.time() + delay, callback, *args)
517 if timer._source_traceback:
518 del timer._source_traceback[-1]
519 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700520
521 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200522 """Like call_later(), but uses an absolute time.
523
524 Absolute time corresponds to the event loop's time() method.
525 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100526 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100527 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100528 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700529 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500530 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200531 if timer._source_traceback:
532 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400534 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535 return timer
536
537 def call_soon(self, callback, *args):
538 """Arrange for a callback to be called as soon as possible.
539
Victor Stinneracdb7822014-07-14 18:33:40 +0200540 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700541 order in which they are registered. Each callback will be
542 called exactly once.
543
544 Any positional arguments after the callback will be passed to
545 the callback when it is called.
546 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700547 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100548 if self._debug:
549 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700550 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100551 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200552 if handle._source_traceback:
553 del handle._source_traceback[-1]
554 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100555
Yury Selivanov491a9122016-11-03 15:09:24 -0700556 def _check_callback(self, callback, method):
557 if (coroutines.iscoroutine(callback) or
558 coroutines.iscoroutinefunction(callback)):
559 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500560 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700561 if not callable(callback):
562 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500563 f'a callable object was expected by {method}(), '
564 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700565
Victor Stinner956de692014-12-26 21:07:52 +0100566 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500567 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200568 if handle._source_traceback:
569 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700570 self._ready.append(handle)
571 return handle
572
Victor Stinner956de692014-12-26 21:07:52 +0100573 def _check_thread(self):
574 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100575
Victor Stinneracdb7822014-07-14 18:33:40 +0200576 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100577 likely behave incorrectly when the assumption is violated.
578
Victor Stinneracdb7822014-07-14 18:33:40 +0200579 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100580 responsible for checking this condition for performance reasons.
581 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100582 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200583 return
Victor Stinner956de692014-12-26 21:07:52 +0100584 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100585 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100586 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200587 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100588 "than the current one")
589
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700590 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200591 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700592 self._check_closed()
593 if self._debug:
594 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100595 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200596 if handle._source_traceback:
597 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 self._write_to_self()
599 return handle
600
Yury Selivanov19a44f62017-12-14 20:53:26 -0500601 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100602 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700603 if self._debug:
604 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605 if executor is None:
606 executor = self._default_executor
607 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400608 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700609 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500610 return await futures.wrap_future(
611 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700612
613 def set_default_executor(self, executor):
614 self._default_executor = executor
615
Victor Stinnere912e652014-07-12 03:11:53 +0200616 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500617 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200618 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500619 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200620 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500621 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200622 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500623 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200624 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500625 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200626 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200627 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200628
629 t0 = self.time()
630 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
631 dt = self.time() - t0
632
Yury Selivanov6370f342017-12-10 18:36:12 -0500633 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200634 if dt >= self.slow_callback_duration:
635 logger.info(msg)
636 else:
637 logger.debug(msg)
638 return addrinfo
639
Yury Selivanov19a44f62017-12-14 20:53:26 -0500640 async def getaddrinfo(self, host, port, *,
641 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400642 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500643 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200644 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500645 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646
Yury Selivanov19a44f62017-12-14 20:53:26 -0500647 return await self.run_in_executor(
648 None, getaddr_func, host, port, family, type, proto, flags)
649
650 async def getnameinfo(self, sockaddr, flags=0):
651 return await self.run_in_executor(
652 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700653
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200654 async def sock_sendfile(self, sock, file, offset=0, count=None,
655 *, fallback=True):
656 if self._debug and sock.gettimeout() != 0:
657 raise ValueError("the socket must be non-blocking")
658 self._check_sendfile_params(sock, file, offset, count)
659 try:
660 return await self._sock_sendfile_native(sock, file,
661 offset, count)
662 except _SendfileNotAvailable as exc:
663 if fallback:
664 return await self._sock_sendfile_fallback(sock, file,
665 offset, count)
666 else:
667 raise RuntimeError(exc.args[0]) from None
668
669 async def _sock_sendfile_native(self, sock, file, offset, count):
670 # NB: sendfile syscall is not supported for SSL sockets and
671 # non-mmap files even if sendfile is supported by OS
672 raise _SendfileNotAvailable(
673 f"syscall sendfile is not available for socket {sock!r} "
674 "and file {file!r} combination")
675
676 async def _sock_sendfile_fallback(self, sock, file, offset, count):
677 if offset:
678 file.seek(offset)
679 blocksize = min(count, 16384) if count else 16384
680 buf = bytearray(blocksize)
681 total_sent = 0
682 try:
683 while True:
684 if count:
685 blocksize = min(count - total_sent, blocksize)
686 if blocksize <= 0:
687 break
688 view = memoryview(buf)[:blocksize]
689 read = file.readinto(view)
690 if not read:
691 break # EOF
692 await self.sock_sendall(sock, view)
693 total_sent += read
694 return total_sent
695 finally:
696 if total_sent > 0 and hasattr(file, 'seek'):
697 file.seek(offset + total_sent)
698
699 def _check_sendfile_params(self, sock, file, offset, count):
700 if 'b' not in getattr(file, 'mode', 'b'):
701 raise ValueError("file should be opened in binary mode")
702 if not sock.type == socket.SOCK_STREAM:
703 raise ValueError("only SOCK_STREAM type sockets are supported")
704 if count is not None:
705 if not isinstance(count, int):
706 raise TypeError(
707 "count must be a positive integer (got {!r})".format(count))
708 if count <= 0:
709 raise ValueError(
710 "count must be a positive integer (got {!r})".format(count))
711 if not isinstance(offset, int):
712 raise TypeError(
713 "offset must be a non-negative integer (got {!r})".format(
714 offset))
715 if offset < 0:
716 raise ValueError(
717 "offset must be a non-negative integer (got {!r})".format(
718 offset))
719
Neil Aspinallf7686c12017-12-19 19:45:42 +0000720 async def create_connection(
721 self, protocol_factory, host=None, port=None,
722 *, ssl=None, family=0,
723 proto=0, flags=0, sock=None,
724 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200725 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200726 """Connect to a TCP server.
727
728 Create a streaming transport connection to a given Internet host and
729 port: socket family AF_INET or socket.AF_INET6 depending on host (or
730 family if specified), socket type SOCK_STREAM. protocol_factory must be
731 a callable returning a protocol instance.
732
733 This method is a coroutine which will try to establish the connection
734 in the background. When successful, the coroutine returns a
735 (transport, protocol) pair.
736 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700737 if server_hostname is not None and not ssl:
738 raise ValueError('server_hostname is only meaningful with ssl')
739
740 if server_hostname is None and ssl:
741 # Use host as default for server_hostname. It is an error
742 # if host is empty or not set, e.g. when an
743 # already-connected socket was passed or when only a port
744 # is given. To avoid this error, you can pass
745 # server_hostname='' -- this will bypass the hostname
746 # check. (This also means that if host is a numeric
747 # IP/IPv6 address, we will attempt to verify that exact
748 # address; this will probably fail, but it is possible to
749 # create a certificate for a specific IP address, so we
750 # don't judge it here.)
751 if not host:
752 raise ValueError('You must set server_hostname '
753 'when using ssl without a host')
754 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700755
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200756 if ssl_handshake_timeout is not None and not ssl:
757 raise ValueError(
758 'ssl_handshake_timeout is only meaningful with ssl')
759
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700760 if host is not None or port is not None:
761 if sock is not None:
762 raise ValueError(
763 'host/port and sock can not be specified at the same time')
764
Yury Selivanov19a44f62017-12-14 20:53:26 -0500765 infos = await self._ensure_resolved(
766 (host, port), family=family,
767 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700768 if not infos:
769 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500770
771 if local_addr is not None:
772 laddr_infos = await self._ensure_resolved(
773 local_addr, family=family,
774 type=socket.SOCK_STREAM, proto=proto,
775 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700776 if not laddr_infos:
777 raise OSError('getaddrinfo() returned empty list')
778
779 exceptions = []
780 for family, type, proto, cname, address in infos:
781 try:
782 sock = socket.socket(family=family, type=type, proto=proto)
783 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500784 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700785 for _, _, _, _, laddr in laddr_infos:
786 try:
787 sock.bind(laddr)
788 break
789 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500790 msg = (
791 f'error while attempting to bind on '
792 f'address {laddr!r}: '
793 f'{exc.strerror.lower()}'
794 )
795 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700796 exceptions.append(exc)
797 else:
798 sock.close()
799 sock = None
800 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200801 if self._debug:
802 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200803 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700804 except OSError as exc:
805 if sock is not None:
806 sock.close()
807 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200808 except:
809 if sock is not None:
810 sock.close()
811 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700812 else:
813 break
814 else:
815 if len(exceptions) == 1:
816 raise exceptions[0]
817 else:
818 # If they all have the same str(), raise one.
819 model = str(exceptions[0])
820 if all(str(exc) == model for exc in exceptions):
821 raise exceptions[0]
822 # Raise a combined exception so the user can see all
823 # the various error messages.
824 raise OSError('Multiple exceptions: {}'.format(
825 ', '.join(str(exc) for exc in exceptions)))
826
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500827 else:
828 if sock is None:
829 raise ValueError(
830 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500831 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500832 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
833 # are SOCK_STREAM.
834 # We support passing AF_UNIX sockets even though we have
835 # a dedicated API for that: create_unix_connection.
836 # Disallowing AF_UNIX in this method, breaks backwards
837 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500838 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500839 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700840
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200841 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000842 sock, protocol_factory, ssl, server_hostname,
843 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200844 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200845 # Get the socket from the transport because SSL transport closes
846 # the old socket and creates a new SSL socket
847 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200848 logger.debug("%r connected to %s:%r: (%r, %r)",
849 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500850 return transport, protocol
851
Neil Aspinallf7686c12017-12-19 19:45:42 +0000852 async def _create_connection_transport(
853 self, sock, protocol_factory, ssl,
854 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200855 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400856
857 sock.setblocking(False)
858
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700859 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400860 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700861 if ssl:
862 sslcontext = None if isinstance(ssl, bool) else ssl
863 transport = self._make_ssl_transport(
864 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000865 server_side=server_side, server_hostname=server_hostname,
866 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700867 else:
868 transport = self._make_socket_transport(sock, protocol, waiter)
869
Victor Stinner29ad0112015-01-15 00:04:21 +0100870 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200871 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100872 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100873 transport.close()
874 raise
875
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700876 return transport, protocol
877
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500878 async def start_tls(self, transport, protocol, sslcontext, *,
879 server_side=False,
880 server_hostname=None,
881 ssl_handshake_timeout=None):
882 """Upgrade transport to TLS.
883
884 Return a new transport that *protocol* should start using
885 immediately.
886 """
887 if ssl is None:
888 raise RuntimeError('Python ssl module is not available')
889
890 if not isinstance(sslcontext, ssl.SSLContext):
891 raise TypeError(
892 f'sslcontext is expected to be an instance of ssl.SSLContext, '
893 f'got {sslcontext!r}')
894
895 if not getattr(transport, '_start_tls_compatible', False):
896 raise TypeError(
897 f'transport {self!r} is not supported by start_tls()')
898
899 waiter = self.create_future()
900 ssl_protocol = sslproto.SSLProtocol(
901 self, protocol, sslcontext, waiter,
902 server_side, server_hostname,
903 ssl_handshake_timeout=ssl_handshake_timeout,
904 call_connection_made=False)
905
906 transport.set_protocol(ssl_protocol)
907 self.call_soon(ssl_protocol.connection_made, transport)
908 if not transport.is_reading():
909 self.call_soon(transport.resume_reading)
910
911 await waiter
912 return ssl_protocol._app_transport
913
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200914 async def create_datagram_endpoint(self, protocol_factory,
915 local_addr=None, remote_addr=None, *,
916 family=0, proto=0, flags=0,
917 reuse_address=None, reuse_port=None,
918 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700919 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700920 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500921 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500922 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500923 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700924 if (local_addr or remote_addr or
925 family or proto or flags or
926 reuse_address or reuse_port or allow_broadcast):
927 # show the problematic kwargs in exception msg
928 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
929 family=family, proto=proto, flags=flags,
930 reuse_address=reuse_address, reuse_port=reuse_port,
931 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500932 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700933 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500934 f'socket modifier keyword arguments can not be used '
935 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700936 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700937 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700938 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700939 if not (local_addr or remote_addr):
940 if family == 0:
941 raise ValueError('unexpected address family')
942 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100943 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
944 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100945 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100946 raise TypeError('string is expected')
947 addr_pairs_info = (((family, proto),
948 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700949 else:
950 # join address by (family, protocol)
951 addr_infos = collections.OrderedDict()
952 for idx, addr in ((0, local_addr), (1, remote_addr)):
953 if addr is not None:
954 assert isinstance(addr, tuple) and len(addr) == 2, (
955 '2-tuple is expected')
956
Yury Selivanov19a44f62017-12-14 20:53:26 -0500957 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400958 addr, family=family, type=socket.SOCK_DGRAM,
959 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700960 if not infos:
961 raise OSError('getaddrinfo() returned empty list')
962
963 for fam, _, pro, _, address in infos:
964 key = (fam, pro)
965 if key not in addr_infos:
966 addr_infos[key] = [None, None]
967 addr_infos[key][idx] = address
968
969 # each addr has to have info for each (family, proto) pair
970 addr_pairs_info = [
971 (key, addr_pair) for key, addr_pair in addr_infos.items()
972 if not ((local_addr and addr_pair[0] is None) or
973 (remote_addr and addr_pair[1] is None))]
974
975 if not addr_pairs_info:
976 raise ValueError('can not get address information')
977
978 exceptions = []
979
980 if reuse_address is None:
981 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
982
983 for ((family, proto),
984 (local_address, remote_address)) in addr_pairs_info:
985 sock = None
986 r_addr = None
987 try:
988 sock = socket.socket(
989 family=family, type=socket.SOCK_DGRAM, proto=proto)
990 if reuse_address:
991 sock.setsockopt(
992 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
993 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400994 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700995 if allow_broadcast:
996 sock.setsockopt(
997 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
998 sock.setblocking(False)
999
1000 if local_addr:
1001 sock.bind(local_address)
1002 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001003 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001004 r_addr = remote_address
1005 except OSError as exc:
1006 if sock is not None:
1007 sock.close()
1008 exceptions.append(exc)
1009 except:
1010 if sock is not None:
1011 sock.close()
1012 raise
1013 else:
1014 break
1015 else:
1016 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001017
1018 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001019 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001020 transport = self._make_datagram_transport(
1021 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001022 if self._debug:
1023 if local_addr:
1024 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1025 "created: (%r, %r)",
1026 local_addr, remote_addr, transport, protocol)
1027 else:
1028 logger.debug("Datagram endpoint remote_addr=%r created: "
1029 "(%r, %r)",
1030 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001031
1032 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001033 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001034 except:
1035 transport.close()
1036 raise
1037
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001038 return transport, protocol
1039
Yury Selivanov19a44f62017-12-14 20:53:26 -05001040 async def _ensure_resolved(self, address, *,
1041 family=0, type=socket.SOCK_STREAM,
1042 proto=0, flags=0, loop):
1043 host, port = address[:2]
1044 info = _ipaddr_info(host, port, family, type, proto)
1045 if info is not None:
1046 # "host" is already a resolved IP.
1047 return [info]
1048 else:
1049 return await loop.getaddrinfo(host, port, family=family, type=type,
1050 proto=proto, flags=flags)
1051
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001052 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001053 infos = await self._ensure_resolved((host, port), family=family,
1054 type=socket.SOCK_STREAM,
1055 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001056 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001057 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001058 return infos
1059
Neil Aspinallf7686c12017-12-19 19:45:42 +00001060 async def create_server(
1061 self, protocol_factory, host=None, port=None,
1062 *,
1063 family=socket.AF_UNSPEC,
1064 flags=socket.AI_PASSIVE,
1065 sock=None,
1066 backlog=100,
1067 ssl=None,
1068 reuse_address=None,
1069 reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001070 ssl_handshake_timeout=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001071 """Create a TCP server.
1072
Yury Selivanov6370f342017-12-10 18:36:12 -05001073 The host parameter can be a string, in that case the TCP server is
1074 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001075
1076 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001077 the TCP server is bound to all hosts of the sequence. If a host
1078 appears multiple times (possibly indirectly e.g. when hostnames
1079 resolve to the same IP address), the server is only bound once to that
1080 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001081
Victor Stinneracdb7822014-07-14 18:33:40 +02001082 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001083
1084 This method is a coroutine.
1085 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001086 if isinstance(ssl, bool):
1087 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001088
1089 if ssl_handshake_timeout is not None and ssl is None:
1090 raise ValueError(
1091 'ssl_handshake_timeout is only meaningful with ssl')
1092
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001093 if host is not None or port is not None:
1094 if sock is not None:
1095 raise ValueError(
1096 'host/port and sock can not be specified at the same time')
1097
1098 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1099 if reuse_address is None:
1100 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1101 sockets = []
1102 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001103 hosts = [None]
1104 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001105 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001106 hosts = [host]
1107 else:
1108 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001109
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001110 fs = [self._create_server_getaddrinfo(host, port, family=family,
1111 flags=flags)
1112 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001113 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001114 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001115
1116 completed = False
1117 try:
1118 for res in infos:
1119 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001120 try:
1121 sock = socket.socket(af, socktype, proto)
1122 except socket.error:
1123 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001124 if self._debug:
1125 logger.warning('create_server() failed to create '
1126 'socket.socket(%r, %r, %r)',
1127 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001128 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001129 sockets.append(sock)
1130 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001131 sock.setsockopt(
1132 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1133 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001134 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001135 # Disable IPv4/IPv6 dual stack support (enabled by
1136 # default on Linux) which makes a single socket
1137 # listen on both address families.
1138 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1139 sock.setsockopt(socket.IPPROTO_IPV6,
1140 socket.IPV6_V6ONLY,
1141 True)
1142 try:
1143 sock.bind(sa)
1144 except OSError as err:
1145 raise OSError(err.errno, 'error while attempting '
1146 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001147 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001148 completed = True
1149 finally:
1150 if not completed:
1151 for sock in sockets:
1152 sock.close()
1153 else:
1154 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001155 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001156 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001157 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001158 sockets = [sock]
1159
1160 server = Server(self, sockets)
1161 for sock in sockets:
1162 sock.listen(backlog)
1163 sock.setblocking(False)
Neil Aspinallf7686c12017-12-19 19:45:42 +00001164 self._start_serving(protocol_factory, sock, ssl, server, backlog,
1165 ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001166 if self._debug:
1167 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001168 return server
1169
Neil Aspinallf7686c12017-12-19 19:45:42 +00001170 async def connect_accepted_socket(
1171 self, protocol_factory, sock,
1172 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001173 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001174 """Handle an accepted connection.
1175
1176 This is used by servers that accept connections outside of
1177 asyncio but that use asyncio to handle connections.
1178
1179 This method is a coroutine. When completed, the coroutine
1180 returns a (transport, protocol) pair.
1181 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001182 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001183 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001184
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001185 if ssl_handshake_timeout is not None and not ssl:
1186 raise ValueError(
1187 'ssl_handshake_timeout is only meaningful with ssl')
1188
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001189 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001190 sock, protocol_factory, ssl, '', server_side=True,
1191 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001192 if self._debug:
1193 # Get the socket from the transport because SSL transport closes
1194 # the old socket and creates a new SSL socket
1195 sock = transport.get_extra_info('socket')
1196 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1197 return transport, protocol
1198
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001199 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001200 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001201 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001202 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001203
1204 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001205 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001206 except:
1207 transport.close()
1208 raise
1209
Victor Stinneracdb7822014-07-14 18:33:40 +02001210 if self._debug:
1211 logger.debug('Read pipe %r connected: (%r, %r)',
1212 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001213 return transport, protocol
1214
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001215 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001216 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001217 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001218 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001219
1220 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001221 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001222 except:
1223 transport.close()
1224 raise
1225
Victor Stinneracdb7822014-07-14 18:33:40 +02001226 if self._debug:
1227 logger.debug('Write pipe %r connected: (%r, %r)',
1228 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001229 return transport, protocol
1230
Victor Stinneracdb7822014-07-14 18:33:40 +02001231 def _log_subprocess(self, msg, stdin, stdout, stderr):
1232 info = [msg]
1233 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001234 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001235 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001236 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001237 else:
1238 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001239 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001240 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001241 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001242 logger.debug(' '.join(info))
1243
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001244 async def subprocess_shell(self, protocol_factory, cmd, *,
1245 stdin=subprocess.PIPE,
1246 stdout=subprocess.PIPE,
1247 stderr=subprocess.PIPE,
1248 universal_newlines=False,
1249 shell=True, bufsize=0,
1250 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001251 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001252 raise ValueError("cmd must be a string")
1253 if universal_newlines:
1254 raise ValueError("universal_newlines must be False")
1255 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001256 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001257 if bufsize != 0:
1258 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001259 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001260 if self._debug:
1261 # don't log parameters: they may contain sensitive information
1262 # (password) and may be too long
1263 debug_log = 'run shell command %r' % cmd
1264 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001265 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001266 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001267 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001268 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001269 return transport, protocol
1270
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001271 async def subprocess_exec(self, protocol_factory, program, *args,
1272 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1273 stderr=subprocess.PIPE, universal_newlines=False,
1274 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001275 if universal_newlines:
1276 raise ValueError("universal_newlines must be False")
1277 if shell:
1278 raise ValueError("shell must be False")
1279 if bufsize != 0:
1280 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001281 popen_args = (program,) + args
1282 for arg in popen_args:
1283 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001284 raise TypeError(
1285 f"program arguments must be a bytes or text string, "
1286 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001287 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001288 if self._debug:
1289 # don't log parameters: they may contain sensitive information
1290 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001291 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001292 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001293 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001294 protocol, popen_args, False, stdin, stdout, stderr,
1295 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001296 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001297 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001298 return transport, protocol
1299
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001300 def get_exception_handler(self):
1301 """Return an exception handler, or None if the default one is in use.
1302 """
1303 return self._exception_handler
1304
Yury Selivanov569efa22014-02-18 18:02:19 -05001305 def set_exception_handler(self, handler):
1306 """Set handler as the new event loop exception handler.
1307
1308 If handler is None, the default exception handler will
1309 be set.
1310
1311 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001312 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001313 will be a reference to the active event loop, 'context'
1314 will be a dict object (see `call_exception_handler()`
1315 documentation for details about context).
1316 """
1317 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001318 raise TypeError(f'A callable object or None is expected, '
1319 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001320 self._exception_handler = handler
1321
1322 def default_exception_handler(self, context):
1323 """Default exception handler.
1324
1325 This is called when an exception occurs and no exception
1326 handler is set, and can be called by a custom exception
1327 handler that wants to defer to the default behavior.
1328
Antoine Pitrou921e9432017-11-07 17:23:29 +01001329 This default handler logs the error message and other
1330 context-dependent information. In debug mode, a truncated
1331 stack trace is also appended showing where the given object
1332 (e.g. a handle or future or task) was created, if any.
1333
Victor Stinneracdb7822014-07-14 18:33:40 +02001334 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001335 `call_exception_handler()`.
1336 """
1337 message = context.get('message')
1338 if not message:
1339 message = 'Unhandled exception in event loop'
1340
1341 exception = context.get('exception')
1342 if exception is not None:
1343 exc_info = (type(exception), exception, exception.__traceback__)
1344 else:
1345 exc_info = False
1346
Yury Selivanov6370f342017-12-10 18:36:12 -05001347 if ('source_traceback' not in context and
1348 self._current_handle is not None and
1349 self._current_handle._source_traceback):
1350 context['handle_traceback'] = \
1351 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001352
Yury Selivanov569efa22014-02-18 18:02:19 -05001353 log_lines = [message]
1354 for key in sorted(context):
1355 if key in {'message', 'exception'}:
1356 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001357 value = context[key]
1358 if key == 'source_traceback':
1359 tb = ''.join(traceback.format_list(value))
1360 value = 'Object created at (most recent call last):\n'
1361 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001362 elif key == 'handle_traceback':
1363 tb = ''.join(traceback.format_list(value))
1364 value = 'Handle created at (most recent call last):\n'
1365 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001366 else:
1367 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001368 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001369
1370 logger.error('\n'.join(log_lines), exc_info=exc_info)
1371
1372 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001373 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001374
Victor Stinneracdb7822014-07-14 18:33:40 +02001375 The context argument is a dict containing the following keys:
1376
Yury Selivanov569efa22014-02-18 18:02:19 -05001377 - 'message': Error message;
1378 - 'exception' (optional): Exception object;
1379 - 'future' (optional): Future instance;
1380 - 'handle' (optional): Handle instance;
1381 - 'protocol' (optional): Protocol instance;
1382 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001383 - 'socket' (optional): Socket instance;
1384 - 'asyncgen' (optional): Asynchronous generator that caused
1385 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001386
Victor Stinneracdb7822014-07-14 18:33:40 +02001387 New keys maybe introduced in the future.
1388
1389 Note: do not overload this method in an event loop subclass.
1390 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001391 `set_exception_handler()` method.
1392 """
1393 if self._exception_handler is None:
1394 try:
1395 self.default_exception_handler(context)
1396 except Exception:
1397 # Second protection layer for unexpected errors
1398 # in the default implementation, as well as for subclassed
1399 # event loops with overloaded "default_exception_handler".
1400 logger.error('Exception in default exception handler',
1401 exc_info=True)
1402 else:
1403 try:
1404 self._exception_handler(self, context)
1405 except Exception as exc:
1406 # Exception in the user set custom exception handler.
1407 try:
1408 # Let's try default handler.
1409 self.default_exception_handler({
1410 'message': 'Unhandled error in exception handler',
1411 'exception': exc,
1412 'context': context,
1413 })
1414 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001415 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001416 # overloaded.
1417 logger.error('Exception in default exception handler '
1418 'while handling an unexpected error '
1419 'in custom exception handler',
1420 exc_info=True)
1421
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001422 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001423 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001424 assert isinstance(handle, events.Handle), 'A Handle is required here'
1425 if handle._cancelled:
1426 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001427 assert not isinstance(handle, events.TimerHandle)
1428 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001429
1430 def _add_callback_signalsafe(self, handle):
1431 """Like _add_callback() but called from a signal handler."""
1432 self._add_callback(handle)
1433 self._write_to_self()
1434
Yury Selivanov592ada92014-09-25 12:07:56 -04001435 def _timer_handle_cancelled(self, handle):
1436 """Notification that a TimerHandle has been cancelled."""
1437 if handle._scheduled:
1438 self._timer_cancelled_count += 1
1439
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001440 def _run_once(self):
1441 """Run one full iteration of the event loop.
1442
1443 This calls all currently ready callbacks, polls for I/O,
1444 schedules the resulting callbacks, and finally schedules
1445 'call_later' callbacks.
1446 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001447
Yury Selivanov592ada92014-09-25 12:07:56 -04001448 sched_count = len(self._scheduled)
1449 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1450 self._timer_cancelled_count / sched_count >
1451 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001452 # Remove delayed calls that were cancelled if their number
1453 # is too high
1454 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001455 for handle in self._scheduled:
1456 if handle._cancelled:
1457 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001458 else:
1459 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001460
Victor Stinner68da8fc2014-09-30 18:08:36 +02001461 heapq.heapify(new_scheduled)
1462 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001463 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001464 else:
1465 # Remove delayed calls that were cancelled from head of queue.
1466 while self._scheduled and self._scheduled[0]._cancelled:
1467 self._timer_cancelled_count -= 1
1468 handle = heapq.heappop(self._scheduled)
1469 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001470
1471 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001472 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001473 timeout = 0
1474 elif self._scheduled:
1475 # Compute the desired timeout.
1476 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001477 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001478
Victor Stinner770e48d2014-07-11 11:58:33 +02001479 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001480 t0 = self.time()
1481 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001482 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001483 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001484 level = logging.INFO
1485 else:
1486 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001487 nevent = len(event_list)
1488 if timeout is None:
1489 logger.log(level, 'poll took %.3f ms: %s events',
1490 dt * 1e3, nevent)
1491 elif nevent:
1492 logger.log(level,
1493 'poll %.3f ms took %.3f ms: %s events',
1494 timeout * 1e3, dt * 1e3, nevent)
1495 elif dt >= 1.0:
1496 logger.log(level,
1497 'poll %.3f ms took %.3f ms: timeout',
1498 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001499 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001500 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001501 self._process_events(event_list)
1502
1503 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001504 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001505 while self._scheduled:
1506 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001507 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001508 break
1509 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001510 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001511 self._ready.append(handle)
1512
1513 # This is the only place where callbacks are actually *called*.
1514 # All other places just add them to ready.
1515 # Note: We run all currently scheduled callbacks, but not any
1516 # callbacks scheduled by callbacks run this time around --
1517 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001518 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001519 ntodo = len(self._ready)
1520 for i in range(ntodo):
1521 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001522 if handle._cancelled:
1523 continue
1524 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001525 try:
1526 self._current_handle = handle
1527 t0 = self.time()
1528 handle._run()
1529 dt = self.time() - t0
1530 if dt >= self.slow_callback_duration:
1531 logger.warning('Executing %s took %.3f seconds',
1532 _format_handle(handle), dt)
1533 finally:
1534 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001535 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001536 handle._run()
1537 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001538
Yury Selivanove8944cb2015-05-12 11:43:04 -04001539 def _set_coroutine_wrapper(self, enabled):
1540 try:
1541 set_wrapper = sys.set_coroutine_wrapper
1542 get_wrapper = sys.get_coroutine_wrapper
1543 except AttributeError:
1544 return
1545
1546 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001547 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001548 return
1549
1550 wrapper = coroutines.debug_wrapper
1551 current_wrapper = get_wrapper()
1552
1553 if enabled:
1554 if current_wrapper not in (None, wrapper):
1555 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001556 f"loop.set_debug(True): cannot set debug coroutine "
1557 f"wrapper; another wrapper is already set "
1558 f"{current_wrapper!r}",
1559 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001560 else:
1561 set_wrapper(wrapper)
1562 self._coroutine_wrapper_set = True
1563 else:
1564 if current_wrapper not in (None, wrapper):
1565 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -05001566 f"loop.set_debug(False): cannot unset debug coroutine "
1567 f"wrapper; another wrapper was set {current_wrapper!r}",
1568 RuntimeWarning)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001569 else:
1570 set_wrapper(None)
1571 self._coroutine_wrapper_set = False
1572
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001573 def get_debug(self):
1574 return self._debug
1575
1576 def set_debug(self, enabled):
1577 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001578
Yury Selivanove8944cb2015-05-12 11:43:04 -04001579 if self.is_running():
1580 self._set_coroutine_wrapper(enabled)