blob: e722cf26b514aa036142d10258c21d17ecb2f576 [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Base implementation of event loop.
2
3The event loop can be broken up into a multiplexer (the part
Victor Stinneracdb7822014-07-14 18:33:40 +02004responsible for notifying us of I/O events) and the event loop proper,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07005which wraps a multiplexer with functionality for scheduling callbacks,
6immediately or at a given time in the future.
7
8Whenever a public API takes a callback, subsequent positional
9arguments will be passed to the callback if/when it is called. This
10avoids the proliferation of trivial lambdas implementing closures.
11Keyword arguments for the callback are not supported; this is a
12conscious design decision, leaving the door open for keyword arguments
13to modify the meaning of the API call itself.
14"""
15
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import collections
Serhiy Storchaka2e576f52017-04-24 09:05:00 +030017import collections.abc
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import concurrent.futures
19import heapq
Victor Stinner5e4a7d82015-09-21 18:33:43 +020020import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
24import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010025import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020027import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070028import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010029import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070030import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanovf111b3d2017-12-30 00:35:36 -050032try:
33 import ssl
34except ImportError: # pragma: no cover
35 ssl = None
36
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020038from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039from . import events
40from . import futures
Yury Selivanovf111b3d2017-12-30 00:35:36 -050041from . import sslproto
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042from . import tasks
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070043from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044
45
Yury Selivanov6370f342017-12-10 18:36:12 -050046__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070047
48
Yury Selivanov592ada92014-09-25 12:07:56 -040049# Minimum number of _scheduled timer handles before cleanup of
50# cancelled handles is performed.
51_MIN_SCHEDULED_TIMER_HANDLES = 100
52
53# Minimum fraction of _scheduled timer handles that are cancelled
54# before cleanup of cancelled handles is performed.
55_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070056
Victor Stinnerc94a93a2016-04-01 21:43:39 +020057# Exceptions which must not call the exception handler in fatal error
58# methods (_fatal_error())
59_FATAL_ERROR_IGNORE = (BrokenPipeError,
60 ConnectionResetError, ConnectionAbortedError)
61
62
Victor Stinner0e6f52a2014-06-20 17:34:15 +020063def _format_handle(handle):
64 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040065 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020066 # format the task
67 return repr(cb.__self__)
68 else:
69 return str(handle)
70
71
Victor Stinneracdb7822014-07-14 18:33:40 +020072def _format_pipe(fd):
73 if fd == subprocess.PIPE:
74 return '<pipe>'
75 elif fd == subprocess.STDOUT:
76 return '<stdout>'
77 else:
78 return repr(fd)
79
80
Yury Selivanov5587d7c2016-09-15 15:45:07 -040081def _set_reuseport(sock):
82 if not hasattr(socket, 'SO_REUSEPORT'):
83 raise ValueError('reuse_port not supported by socket module')
84 else:
85 try:
86 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
87 except OSError:
88 raise ValueError('reuse_port not supported by socket module, '
89 'SO_REUSEPORT defined but not implemented.')
90
91
Yury Selivanovd5c2a622015-12-16 19:31:17 -050092def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040093 # Try to skip getaddrinfo if "host" is already an IP. Users might have
94 # handled name resolution in their own code and pass in resolved IPs.
95 if not hasattr(socket, 'inet_pton'):
96 return
97
98 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
99 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500100 return None
101
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500102 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500103 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500104 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500105 proto = socket.IPPROTO_UDP
106 else:
107 return None
108
Yury Selivanova7146162016-06-02 16:51:07 -0400109 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400110 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700111 elif isinstance(port, bytes) and port == b'':
112 port = 0
113 elif isinstance(port, str) and port == '':
114 port = 0
115 else:
116 # If port's a service name like "http", don't skip getaddrinfo.
117 try:
118 port = int(port)
119 except (TypeError, ValueError):
120 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400121
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400122 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500123 afs = [socket.AF_INET]
124 if hasattr(socket, 'AF_INET6'):
125 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 else:
127 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500128
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400129 if isinstance(host, bytes):
130 host = host.decode('idna')
131 if '%' in host:
132 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
133 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500134 return None
135
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500137 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 socket.inet_pton(af, host)
139 # The host has already been resolved.
140 return af, type, proto, '', (host, port)
141 except OSError:
142 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500143
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400144 # "host" is not an IP address.
145 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500146
147
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100148def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500149 if not fut.cancelled():
150 exc = fut.exception()
151 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
152 # Issue #22429: run_forever() already finished, no need to
153 # stop it.
154 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500155 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100156
157
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700158class Server(events.AbstractServer):
159
160 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200161 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200163 self._active_count = 0
164 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700165
Victor Stinnere912e652014-07-12 03:11:53 +0200166 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500167 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200168
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200169 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200171 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700172
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200173 def _detach(self):
174 assert self._active_count > 0
175 self._active_count -= 1
176 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700177 self._wakeup()
178
179 def close(self):
180 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200181 if sockets is None:
182 return
183 self.sockets = None
184 for sock in sockets:
185 self._loop._stop_serving(sock)
186 if self._active_count == 0:
187 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530189 def get_loop(self):
190 return self._loop
191
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700192 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200193 waiters = self._waiters
194 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195 for waiter in waiters:
196 if not waiter.done():
197 waiter.set_result(waiter)
198
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200199 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200200 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700201 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400202 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200203 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200204 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700205
206
207class BaseEventLoop(events.AbstractEventLoop):
208
209 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400210 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200211 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800212 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 self._ready = collections.deque()
214 self._scheduled = []
215 self._default_executor = None
216 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100217 # Identifier of the thread running the event loop, or None if the
218 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100219 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100220 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500221 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800222 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200223 # In debug mode, if the execution of a callback or a step of a task
224 # exceed this duration in seconds, the slow callback/task is logged.
225 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100226 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400227 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800228 self._coroutine_origin_tracking_enabled = False
229 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700230
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500231 # A weak set of all asynchronous generators that are
232 # being iterated by the loop.
233 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700234 # Set to True when `loop.shutdown_asyncgens` is called.
235 self._asyncgens_shutdown_called = False
236
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200237 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500238 return (
239 f'<{self.__class__.__name__} running={self.is_running()} '
240 f'closed={self.is_closed()} debug={self.get_debug()}>'
241 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200242
Yury Selivanov7661db62016-05-16 15:38:39 -0400243 def create_future(self):
244 """Create a Future object attached to the loop."""
245 return futures.Future(loop=self)
246
Victor Stinner896a25a2014-07-08 11:29:25 +0200247 def create_task(self, coro):
248 """Schedule a coroutine object.
249
Victor Stinneracdb7822014-07-14 18:33:40 +0200250 Return a task object.
251 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100252 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400253 if self._task_factory is None:
254 task = tasks.Task(coro, loop=self)
255 if task._source_traceback:
256 del task._source_traceback[-1]
257 else:
258 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200259 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200260
Yury Selivanov740169c2015-05-11 14:23:38 -0400261 def set_task_factory(self, factory):
262 """Set a task factory that will be used by loop.create_task().
263
264 If factory is None the default task factory will be set.
265
266 If factory is a callable, it should have a signature matching
267 '(loop, coro)', where 'loop' will be a reference to the active
268 event loop, 'coro' will be a coroutine object. The callable
269 must return a Future.
270 """
271 if factory is not None and not callable(factory):
272 raise TypeError('task factory must be a callable or None')
273 self._task_factory = factory
274
275 def get_task_factory(self):
276 """Return a task factory, or None if the default one is in use."""
277 return self._task_factory
278
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279 def _make_socket_transport(self, sock, protocol, waiter=None, *,
280 extra=None, server=None):
281 """Create socket transport."""
282 raise NotImplementedError
283
Neil Aspinallf7686c12017-12-19 19:45:42 +0000284 def _make_ssl_transport(
285 self, rawsock, protocol, sslcontext, waiter=None,
286 *, server_side=False, server_hostname=None,
287 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500288 ssl_handshake_timeout=None,
289 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700290 """Create SSL transport."""
291 raise NotImplementedError
292
293 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200294 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700295 """Create datagram transport."""
296 raise NotImplementedError
297
298 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
299 extra=None):
300 """Create read pipe transport."""
301 raise NotImplementedError
302
303 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
304 extra=None):
305 """Create write pipe transport."""
306 raise NotImplementedError
307
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200308 async def _make_subprocess_transport(self, protocol, args, shell,
309 stdin, stdout, stderr, bufsize,
310 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311 """Create subprocess transport."""
312 raise NotImplementedError
313
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700314 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200315 """Write a byte to self-pipe, to wake up the event loop.
316
317 This may be called from a different thread.
318
319 The subclass is responsible for implementing the self-pipe.
320 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700321 raise NotImplementedError
322
323 def _process_events(self, event_list):
324 """Process selector events."""
325 raise NotImplementedError
326
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200327 def _check_closed(self):
328 if self._closed:
329 raise RuntimeError('Event loop is closed')
330
Yury Selivanoveb636452016-09-08 22:01:51 -0700331 def _asyncgen_finalizer_hook(self, agen):
332 self._asyncgens.discard(agen)
333 if not self.is_closed():
334 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400335 # Wake up the loop if the finalizer was called from
336 # a different thread.
337 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700338
339 def _asyncgen_firstiter_hook(self, agen):
340 if self._asyncgens_shutdown_called:
341 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500342 f"asynchronous generator {agen!r} was scheduled after "
343 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700344 ResourceWarning, source=self)
345
346 self._asyncgens.add(agen)
347
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200348 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700349 """Shutdown all active asynchronous generators."""
350 self._asyncgens_shutdown_called = True
351
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500352 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400353 # If Python version is <3.6 or we don't have any asynchronous
354 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700355 return
356
357 closing_agens = list(self._asyncgens)
358 self._asyncgens.clear()
359
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200360 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700361 *[ag.aclose() for ag in closing_agens],
362 return_exceptions=True,
363 loop=self)
364
Yury Selivanoveb636452016-09-08 22:01:51 -0700365 for result, agen in zip(results, closing_agens):
366 if isinstance(result, Exception):
367 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500368 'message': f'an error occurred during closing of '
369 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700370 'exception': result,
371 'asyncgen': agen
372 })
373
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700374 def run_forever(self):
375 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200376 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100377 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400378 raise RuntimeError('This event loop is already running')
379 if events._get_running_loop() is not None:
380 raise RuntimeError(
381 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800382 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100383 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500384
385 old_agen_hooks = sys.get_asyncgen_hooks()
386 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
387 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700388 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400389 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700390 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800391 self._run_once()
392 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700393 break
394 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800395 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100396 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400397 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800398 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500399 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700400
401 def run_until_complete(self, future):
402 """Run until the Future is done.
403
404 If the argument is a coroutine, it is wrapped in a Task.
405
Victor Stinneracdb7822014-07-14 18:33:40 +0200406 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700407 with the same coroutine twice -- it would wrap it in two
408 different Tasks and that can't be good.
409
410 Return the Future's result, or raise its exception.
411 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200412 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200413
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700414 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400415 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200416 if new_task:
417 # An exception is raised if the future didn't complete, so there
418 # is no need to log the "destroy pending task" message
419 future._log_destroy_pending = False
420
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100421 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200422 try:
423 self.run_forever()
424 except:
425 if new_task and future.done() and not future.cancelled():
426 # The coroutine raised a BaseException. Consume the exception
427 # to not log a warning, the caller doesn't have access to the
428 # local task.
429 future.exception()
430 raise
jimmylai21b3e042017-05-22 22:32:46 -0700431 finally:
432 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700433 if not future.done():
434 raise RuntimeError('Event loop stopped before Future completed.')
435
436 return future.result()
437
438 def stop(self):
439 """Stop running the event loop.
440
Guido van Rossum41f69f42015-11-19 13:28:47 -0800441 Every callback already scheduled will still run. This simply informs
442 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700443 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800444 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700445
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200446 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700447 """Close the event loop.
448
449 This clears the queues and shuts down the executor,
450 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200451
452 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700453 """
Victor Stinner956de692014-12-26 21:07:52 +0100454 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200455 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200456 if self._closed:
457 return
Victor Stinnere912e652014-07-12 03:11:53 +0200458 if self._debug:
459 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400460 self._closed = True
461 self._ready.clear()
462 self._scheduled.clear()
463 executor = self._default_executor
464 if executor is not None:
465 self._default_executor = None
466 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200467
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200468 def is_closed(self):
469 """Returns True if the event loop was closed."""
470 return self._closed
471
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900472 def __del__(self):
473 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500474 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900475 source=self)
476 if not self.is_running():
477 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100478
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200480 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100481 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700482
483 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200484 """Return the time according to the event loop's clock.
485
486 This is a float expressed in seconds since an epoch, but the
487 epoch, precision, accuracy and drift are unspecified and may
488 differ per event loop.
489 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 return time.monotonic()
491
Yury Selivanovf23746a2018-01-22 19:11:18 -0500492 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700493 """Arrange for a callback to be called at a given time.
494
495 Return a Handle: an opaque object with a cancel() method that
496 can be used to cancel the call.
497
498 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200499 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500
501 Each callback will be called exactly once. If two callbacks
502 are scheduled for exactly the same time, it undefined which
503 will be called first.
504
505 Any positional arguments after the callback will be passed to
506 the callback when it is called.
507 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500508 timer = self.call_at(self.time() + delay, callback, *args,
509 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200510 if timer._source_traceback:
511 del timer._source_traceback[-1]
512 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700513
Yury Selivanovf23746a2018-01-22 19:11:18 -0500514 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200515 """Like call_later(), but uses an absolute time.
516
517 Absolute time corresponds to the event loop's time() method.
518 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100519 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100520 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100521 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700522 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500523 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200524 if timer._source_traceback:
525 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400527 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 return timer
529
Yury Selivanovf23746a2018-01-22 19:11:18 -0500530 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 """Arrange for a callback to be called as soon as possible.
532
Victor Stinneracdb7822014-07-14 18:33:40 +0200533 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700534 order in which they are registered. Each callback will be
535 called exactly once.
536
537 Any positional arguments after the callback will be passed to
538 the callback when it is called.
539 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700540 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100541 if self._debug:
542 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700543 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500544 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200545 if handle._source_traceback:
546 del handle._source_traceback[-1]
547 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100548
Yury Selivanov491a9122016-11-03 15:09:24 -0700549 def _check_callback(self, callback, method):
550 if (coroutines.iscoroutine(callback) or
551 coroutines.iscoroutinefunction(callback)):
552 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500553 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700554 if not callable(callback):
555 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500556 f'a callable object was expected by {method}(), '
557 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700558
Yury Selivanovf23746a2018-01-22 19:11:18 -0500559 def _call_soon(self, callback, args, context):
560 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200561 if handle._source_traceback:
562 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700563 self._ready.append(handle)
564 return handle
565
Victor Stinner956de692014-12-26 21:07:52 +0100566 def _check_thread(self):
567 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100568
Victor Stinneracdb7822014-07-14 18:33:40 +0200569 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100570 likely behave incorrectly when the assumption is violated.
571
Victor Stinneracdb7822014-07-14 18:33:40 +0200572 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100573 responsible for checking this condition for performance reasons.
574 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100575 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200576 return
Victor Stinner956de692014-12-26 21:07:52 +0100577 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100578 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100579 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200580 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100581 "than the current one")
582
Yury Selivanovf23746a2018-01-22 19:11:18 -0500583 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200584 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700585 self._check_closed()
586 if self._debug:
587 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500588 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200589 if handle._source_traceback:
590 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591 self._write_to_self()
592 return handle
593
Yury Selivanov19a44f62017-12-14 20:53:26 -0500594 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100595 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700596 if self._debug:
597 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 if executor is None:
599 executor = self._default_executor
600 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400601 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700602 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500603 return await futures.wrap_future(
604 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605
606 def set_default_executor(self, executor):
607 self._default_executor = executor
608
Victor Stinnere912e652014-07-12 03:11:53 +0200609 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500610 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200611 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500612 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200613 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500614 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200615 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500616 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200617 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500618 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200619 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200620 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200621
622 t0 = self.time()
623 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
624 dt = self.time() - t0
625
Yury Selivanov6370f342017-12-10 18:36:12 -0500626 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200627 if dt >= self.slow_callback_duration:
628 logger.info(msg)
629 else:
630 logger.debug(msg)
631 return addrinfo
632
Yury Selivanov19a44f62017-12-14 20:53:26 -0500633 async def getaddrinfo(self, host, port, *,
634 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400635 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500636 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200637 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500638 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700639
Yury Selivanov19a44f62017-12-14 20:53:26 -0500640 return await self.run_in_executor(
641 None, getaddr_func, host, port, family, type, proto, flags)
642
643 async def getnameinfo(self, sockaddr, flags=0):
644 return await self.run_in_executor(
645 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200647 async def sock_sendfile(self, sock, file, offset=0, count=None,
648 *, fallback=True):
649 if self._debug and sock.gettimeout() != 0:
650 raise ValueError("the socket must be non-blocking")
651 self._check_sendfile_params(sock, file, offset, count)
652 try:
653 return await self._sock_sendfile_native(sock, file,
654 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200655 except events.SendfileNotAvailableError as exc:
656 if not fallback:
657 raise
658 return await self._sock_sendfile_fallback(sock, file,
659 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200660
661 async def _sock_sendfile_native(self, sock, file, offset, count):
662 # NB: sendfile syscall is not supported for SSL sockets and
663 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200664 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200665 f"syscall sendfile is not available for socket {sock!r} "
666 "and file {file!r} combination")
667
668 async def _sock_sendfile_fallback(self, sock, file, offset, count):
669 if offset:
670 file.seek(offset)
671 blocksize = min(count, 16384) if count else 16384
672 buf = bytearray(blocksize)
673 total_sent = 0
674 try:
675 while True:
676 if count:
677 blocksize = min(count - total_sent, blocksize)
678 if blocksize <= 0:
679 break
680 view = memoryview(buf)[:blocksize]
681 read = file.readinto(view)
682 if not read:
683 break # EOF
684 await self.sock_sendall(sock, view)
685 total_sent += read
686 return total_sent
687 finally:
688 if total_sent > 0 and hasattr(file, 'seek'):
689 file.seek(offset + total_sent)
690
691 def _check_sendfile_params(self, sock, file, offset, count):
692 if 'b' not in getattr(file, 'mode', 'b'):
693 raise ValueError("file should be opened in binary mode")
694 if not sock.type == socket.SOCK_STREAM:
695 raise ValueError("only SOCK_STREAM type sockets are supported")
696 if count is not None:
697 if not isinstance(count, int):
698 raise TypeError(
699 "count must be a positive integer (got {!r})".format(count))
700 if count <= 0:
701 raise ValueError(
702 "count must be a positive integer (got {!r})".format(count))
703 if not isinstance(offset, int):
704 raise TypeError(
705 "offset must be a non-negative integer (got {!r})".format(
706 offset))
707 if offset < 0:
708 raise ValueError(
709 "offset must be a non-negative integer (got {!r})".format(
710 offset))
711
Neil Aspinallf7686c12017-12-19 19:45:42 +0000712 async def create_connection(
713 self, protocol_factory, host=None, port=None,
714 *, ssl=None, family=0,
715 proto=0, flags=0, sock=None,
716 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200717 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200718 """Connect to a TCP server.
719
720 Create a streaming transport connection to a given Internet host and
721 port: socket family AF_INET or socket.AF_INET6 depending on host (or
722 family if specified), socket type SOCK_STREAM. protocol_factory must be
723 a callable returning a protocol instance.
724
725 This method is a coroutine which will try to establish the connection
726 in the background. When successful, the coroutine returns a
727 (transport, protocol) pair.
728 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700729 if server_hostname is not None and not ssl:
730 raise ValueError('server_hostname is only meaningful with ssl')
731
732 if server_hostname is None and ssl:
733 # Use host as default for server_hostname. It is an error
734 # if host is empty or not set, e.g. when an
735 # already-connected socket was passed or when only a port
736 # is given. To avoid this error, you can pass
737 # server_hostname='' -- this will bypass the hostname
738 # check. (This also means that if host is a numeric
739 # IP/IPv6 address, we will attempt to verify that exact
740 # address; this will probably fail, but it is possible to
741 # create a certificate for a specific IP address, so we
742 # don't judge it here.)
743 if not host:
744 raise ValueError('You must set server_hostname '
745 'when using ssl without a host')
746 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700747
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200748 if ssl_handshake_timeout is not None and not ssl:
749 raise ValueError(
750 'ssl_handshake_timeout is only meaningful with ssl')
751
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700752 if host is not None or port is not None:
753 if sock is not None:
754 raise ValueError(
755 'host/port and sock can not be specified at the same time')
756
Yury Selivanov19a44f62017-12-14 20:53:26 -0500757 infos = await self._ensure_resolved(
758 (host, port), family=family,
759 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700760 if not infos:
761 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500762
763 if local_addr is not None:
764 laddr_infos = await self._ensure_resolved(
765 local_addr, family=family,
766 type=socket.SOCK_STREAM, proto=proto,
767 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700768 if not laddr_infos:
769 raise OSError('getaddrinfo() returned empty list')
770
771 exceptions = []
772 for family, type, proto, cname, address in infos:
773 try:
774 sock = socket.socket(family=family, type=type, proto=proto)
775 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500776 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700777 for _, _, _, _, laddr in laddr_infos:
778 try:
779 sock.bind(laddr)
780 break
781 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500782 msg = (
783 f'error while attempting to bind on '
784 f'address {laddr!r}: '
785 f'{exc.strerror.lower()}'
786 )
787 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700788 exceptions.append(exc)
789 else:
790 sock.close()
791 sock = None
792 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200793 if self._debug:
794 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200795 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700796 except OSError as exc:
797 if sock is not None:
798 sock.close()
799 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200800 except:
801 if sock is not None:
802 sock.close()
803 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700804 else:
805 break
806 else:
807 if len(exceptions) == 1:
808 raise exceptions[0]
809 else:
810 # If they all have the same str(), raise one.
811 model = str(exceptions[0])
812 if all(str(exc) == model for exc in exceptions):
813 raise exceptions[0]
814 # Raise a combined exception so the user can see all
815 # the various error messages.
816 raise OSError('Multiple exceptions: {}'.format(
817 ', '.join(str(exc) for exc in exceptions)))
818
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500819 else:
820 if sock is None:
821 raise ValueError(
822 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500823 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500824 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
825 # are SOCK_STREAM.
826 # We support passing AF_UNIX sockets even though we have
827 # a dedicated API for that: create_unix_connection.
828 # Disallowing AF_UNIX in this method, breaks backwards
829 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500830 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500831 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700832
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200833 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000834 sock, protocol_factory, ssl, server_hostname,
835 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200836 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200837 # Get the socket from the transport because SSL transport closes
838 # the old socket and creates a new SSL socket
839 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200840 logger.debug("%r connected to %s:%r: (%r, %r)",
841 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500842 return transport, protocol
843
Neil Aspinallf7686c12017-12-19 19:45:42 +0000844 async def _create_connection_transport(
845 self, sock, protocol_factory, ssl,
846 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200847 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400848
849 sock.setblocking(False)
850
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700851 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400852 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700853 if ssl:
854 sslcontext = None if isinstance(ssl, bool) else ssl
855 transport = self._make_ssl_transport(
856 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000857 server_side=server_side, server_hostname=server_hostname,
858 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700859 else:
860 transport = self._make_socket_transport(sock, protocol, waiter)
861
Victor Stinner29ad0112015-01-15 00:04:21 +0100862 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200863 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100864 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100865 transport.close()
866 raise
867
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700868 return transport, protocol
869
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500870 async def start_tls(self, transport, protocol, sslcontext, *,
871 server_side=False,
872 server_hostname=None,
873 ssl_handshake_timeout=None):
874 """Upgrade transport to TLS.
875
876 Return a new transport that *protocol* should start using
877 immediately.
878 """
879 if ssl is None:
880 raise RuntimeError('Python ssl module is not available')
881
882 if not isinstance(sslcontext, ssl.SSLContext):
883 raise TypeError(
884 f'sslcontext is expected to be an instance of ssl.SSLContext, '
885 f'got {sslcontext!r}')
886
887 if not getattr(transport, '_start_tls_compatible', False):
888 raise TypeError(
889 f'transport {self!r} is not supported by start_tls()')
890
891 waiter = self.create_future()
892 ssl_protocol = sslproto.SSLProtocol(
893 self, protocol, sslcontext, waiter,
894 server_side, server_hostname,
895 ssl_handshake_timeout=ssl_handshake_timeout,
896 call_connection_made=False)
897
898 transport.set_protocol(ssl_protocol)
899 self.call_soon(ssl_protocol.connection_made, transport)
900 if not transport.is_reading():
901 self.call_soon(transport.resume_reading)
902
903 await waiter
904 return ssl_protocol._app_transport
905
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200906 async def create_datagram_endpoint(self, protocol_factory,
907 local_addr=None, remote_addr=None, *,
908 family=0, proto=0, flags=0,
909 reuse_address=None, reuse_port=None,
910 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700911 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700912 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500913 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500914 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500915 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700916 if (local_addr or remote_addr or
917 family or proto or flags or
918 reuse_address or reuse_port or allow_broadcast):
919 # show the problematic kwargs in exception msg
920 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
921 family=family, proto=proto, flags=flags,
922 reuse_address=reuse_address, reuse_port=reuse_port,
923 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500924 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700925 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500926 f'socket modifier keyword arguments can not be used '
927 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700928 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700929 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700930 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700931 if not (local_addr or remote_addr):
932 if family == 0:
933 raise ValueError('unexpected address family')
934 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100935 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
936 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100937 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100938 raise TypeError('string is expected')
939 addr_pairs_info = (((family, proto),
940 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700941 else:
942 # join address by (family, protocol)
943 addr_infos = collections.OrderedDict()
944 for idx, addr in ((0, local_addr), (1, remote_addr)):
945 if addr is not None:
946 assert isinstance(addr, tuple) and len(addr) == 2, (
947 '2-tuple is expected')
948
Yury Selivanov19a44f62017-12-14 20:53:26 -0500949 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400950 addr, family=family, type=socket.SOCK_DGRAM,
951 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700952 if not infos:
953 raise OSError('getaddrinfo() returned empty list')
954
955 for fam, _, pro, _, address in infos:
956 key = (fam, pro)
957 if key not in addr_infos:
958 addr_infos[key] = [None, None]
959 addr_infos[key][idx] = address
960
961 # each addr has to have info for each (family, proto) pair
962 addr_pairs_info = [
963 (key, addr_pair) for key, addr_pair in addr_infos.items()
964 if not ((local_addr and addr_pair[0] is None) or
965 (remote_addr and addr_pair[1] is None))]
966
967 if not addr_pairs_info:
968 raise ValueError('can not get address information')
969
970 exceptions = []
971
972 if reuse_address is None:
973 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
974
975 for ((family, proto),
976 (local_address, remote_address)) in addr_pairs_info:
977 sock = None
978 r_addr = None
979 try:
980 sock = socket.socket(
981 family=family, type=socket.SOCK_DGRAM, proto=proto)
982 if reuse_address:
983 sock.setsockopt(
984 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
985 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400986 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700987 if allow_broadcast:
988 sock.setsockopt(
989 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
990 sock.setblocking(False)
991
992 if local_addr:
993 sock.bind(local_address)
994 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200995 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700996 r_addr = remote_address
997 except OSError as exc:
998 if sock is not None:
999 sock.close()
1000 exceptions.append(exc)
1001 except:
1002 if sock is not None:
1003 sock.close()
1004 raise
1005 else:
1006 break
1007 else:
1008 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001009
1010 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001011 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001012 transport = self._make_datagram_transport(
1013 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001014 if self._debug:
1015 if local_addr:
1016 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1017 "created: (%r, %r)",
1018 local_addr, remote_addr, transport, protocol)
1019 else:
1020 logger.debug("Datagram endpoint remote_addr=%r created: "
1021 "(%r, %r)",
1022 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001023
1024 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001025 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001026 except:
1027 transport.close()
1028 raise
1029
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001030 return transport, protocol
1031
Yury Selivanov19a44f62017-12-14 20:53:26 -05001032 async def _ensure_resolved(self, address, *,
1033 family=0, type=socket.SOCK_STREAM,
1034 proto=0, flags=0, loop):
1035 host, port = address[:2]
1036 info = _ipaddr_info(host, port, family, type, proto)
1037 if info is not None:
1038 # "host" is already a resolved IP.
1039 return [info]
1040 else:
1041 return await loop.getaddrinfo(host, port, family=family, type=type,
1042 proto=proto, flags=flags)
1043
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001044 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001045 infos = await self._ensure_resolved((host, port), family=family,
1046 type=socket.SOCK_STREAM,
1047 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001048 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001049 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001050 return infos
1051
Neil Aspinallf7686c12017-12-19 19:45:42 +00001052 async def create_server(
1053 self, protocol_factory, host=None, port=None,
1054 *,
1055 family=socket.AF_UNSPEC,
1056 flags=socket.AI_PASSIVE,
1057 sock=None,
1058 backlog=100,
1059 ssl=None,
1060 reuse_address=None,
1061 reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001062 ssl_handshake_timeout=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001063 """Create a TCP server.
1064
Yury Selivanov6370f342017-12-10 18:36:12 -05001065 The host parameter can be a string, in that case the TCP server is
1066 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001067
1068 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001069 the TCP server is bound to all hosts of the sequence. If a host
1070 appears multiple times (possibly indirectly e.g. when hostnames
1071 resolve to the same IP address), the server is only bound once to that
1072 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001073
Victor Stinneracdb7822014-07-14 18:33:40 +02001074 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001075
1076 This method is a coroutine.
1077 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001078 if isinstance(ssl, bool):
1079 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001080
1081 if ssl_handshake_timeout is not None and ssl is None:
1082 raise ValueError(
1083 'ssl_handshake_timeout is only meaningful with ssl')
1084
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001085 if host is not None or port is not None:
1086 if sock is not None:
1087 raise ValueError(
1088 'host/port and sock can not be specified at the same time')
1089
1090 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1091 if reuse_address is None:
1092 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1093 sockets = []
1094 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001095 hosts = [None]
1096 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001097 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001098 hosts = [host]
1099 else:
1100 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001101
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001102 fs = [self._create_server_getaddrinfo(host, port, family=family,
1103 flags=flags)
1104 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001105 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001106 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001107
1108 completed = False
1109 try:
1110 for res in infos:
1111 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001112 try:
1113 sock = socket.socket(af, socktype, proto)
1114 except socket.error:
1115 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001116 if self._debug:
1117 logger.warning('create_server() failed to create '
1118 'socket.socket(%r, %r, %r)',
1119 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001120 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001121 sockets.append(sock)
1122 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001123 sock.setsockopt(
1124 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1125 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001126 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001127 # Disable IPv4/IPv6 dual stack support (enabled by
1128 # default on Linux) which makes a single socket
1129 # listen on both address families.
1130 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1131 sock.setsockopt(socket.IPPROTO_IPV6,
1132 socket.IPV6_V6ONLY,
1133 True)
1134 try:
1135 sock.bind(sa)
1136 except OSError as err:
1137 raise OSError(err.errno, 'error while attempting '
1138 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001139 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001140 completed = True
1141 finally:
1142 if not completed:
1143 for sock in sockets:
1144 sock.close()
1145 else:
1146 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001147 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001148 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001149 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001150 sockets = [sock]
1151
1152 server = Server(self, sockets)
1153 for sock in sockets:
1154 sock.listen(backlog)
1155 sock.setblocking(False)
Neil Aspinallf7686c12017-12-19 19:45:42 +00001156 self._start_serving(protocol_factory, sock, ssl, server, backlog,
1157 ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +02001158 if self._debug:
1159 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001160 return server
1161
Neil Aspinallf7686c12017-12-19 19:45:42 +00001162 async def connect_accepted_socket(
1163 self, protocol_factory, sock,
1164 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001165 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001166 """Handle an accepted connection.
1167
1168 This is used by servers that accept connections outside of
1169 asyncio but that use asyncio to handle connections.
1170
1171 This method is a coroutine. When completed, the coroutine
1172 returns a (transport, protocol) pair.
1173 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001174 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001175 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001176
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001177 if ssl_handshake_timeout is not None and not ssl:
1178 raise ValueError(
1179 'ssl_handshake_timeout is only meaningful with ssl')
1180
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001181 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001182 sock, protocol_factory, ssl, '', server_side=True,
1183 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001184 if self._debug:
1185 # Get the socket from the transport because SSL transport closes
1186 # the old socket and creates a new SSL socket
1187 sock = transport.get_extra_info('socket')
1188 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1189 return transport, protocol
1190
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001191 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001192 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001193 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001194 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001195
1196 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001197 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001198 except:
1199 transport.close()
1200 raise
1201
Victor Stinneracdb7822014-07-14 18:33:40 +02001202 if self._debug:
1203 logger.debug('Read pipe %r connected: (%r, %r)',
1204 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001205 return transport, protocol
1206
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001207 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001208 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001209 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001210 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001211
1212 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001213 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001214 except:
1215 transport.close()
1216 raise
1217
Victor Stinneracdb7822014-07-14 18:33:40 +02001218 if self._debug:
1219 logger.debug('Write pipe %r connected: (%r, %r)',
1220 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001221 return transport, protocol
1222
Victor Stinneracdb7822014-07-14 18:33:40 +02001223 def _log_subprocess(self, msg, stdin, stdout, stderr):
1224 info = [msg]
1225 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001226 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001227 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001228 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001229 else:
1230 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001231 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001232 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001233 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001234 logger.debug(' '.join(info))
1235
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001236 async def subprocess_shell(self, protocol_factory, cmd, *,
1237 stdin=subprocess.PIPE,
1238 stdout=subprocess.PIPE,
1239 stderr=subprocess.PIPE,
1240 universal_newlines=False,
1241 shell=True, bufsize=0,
1242 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001243 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001244 raise ValueError("cmd must be a string")
1245 if universal_newlines:
1246 raise ValueError("universal_newlines must be False")
1247 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001248 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001249 if bufsize != 0:
1250 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001251 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001252 if self._debug:
1253 # don't log parameters: they may contain sensitive information
1254 # (password) and may be too long
1255 debug_log = 'run shell command %r' % cmd
1256 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001257 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001258 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001259 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001260 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001261 return transport, protocol
1262
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001263 async def subprocess_exec(self, protocol_factory, program, *args,
1264 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1265 stderr=subprocess.PIPE, universal_newlines=False,
1266 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001267 if universal_newlines:
1268 raise ValueError("universal_newlines must be False")
1269 if shell:
1270 raise ValueError("shell must be False")
1271 if bufsize != 0:
1272 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001273 popen_args = (program,) + args
1274 for arg in popen_args:
1275 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001276 raise TypeError(
1277 f"program arguments must be a bytes or text string, "
1278 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001279 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001280 if self._debug:
1281 # don't log parameters: they may contain sensitive information
1282 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001283 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001284 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001285 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001286 protocol, popen_args, False, stdin, stdout, stderr,
1287 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001288 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001289 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001290 return transport, protocol
1291
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001292 def get_exception_handler(self):
1293 """Return an exception handler, or None if the default one is in use.
1294 """
1295 return self._exception_handler
1296
Yury Selivanov569efa22014-02-18 18:02:19 -05001297 def set_exception_handler(self, handler):
1298 """Set handler as the new event loop exception handler.
1299
1300 If handler is None, the default exception handler will
1301 be set.
1302
1303 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001304 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001305 will be a reference to the active event loop, 'context'
1306 will be a dict object (see `call_exception_handler()`
1307 documentation for details about context).
1308 """
1309 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001310 raise TypeError(f'A callable object or None is expected, '
1311 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001312 self._exception_handler = handler
1313
1314 def default_exception_handler(self, context):
1315 """Default exception handler.
1316
1317 This is called when an exception occurs and no exception
1318 handler is set, and can be called by a custom exception
1319 handler that wants to defer to the default behavior.
1320
Antoine Pitrou921e9432017-11-07 17:23:29 +01001321 This default handler logs the error message and other
1322 context-dependent information. In debug mode, a truncated
1323 stack trace is also appended showing where the given object
1324 (e.g. a handle or future or task) was created, if any.
1325
Victor Stinneracdb7822014-07-14 18:33:40 +02001326 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001327 `call_exception_handler()`.
1328 """
1329 message = context.get('message')
1330 if not message:
1331 message = 'Unhandled exception in event loop'
1332
1333 exception = context.get('exception')
1334 if exception is not None:
1335 exc_info = (type(exception), exception, exception.__traceback__)
1336 else:
1337 exc_info = False
1338
Yury Selivanov6370f342017-12-10 18:36:12 -05001339 if ('source_traceback' not in context and
1340 self._current_handle is not None and
1341 self._current_handle._source_traceback):
1342 context['handle_traceback'] = \
1343 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001344
Yury Selivanov569efa22014-02-18 18:02:19 -05001345 log_lines = [message]
1346 for key in sorted(context):
1347 if key in {'message', 'exception'}:
1348 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001349 value = context[key]
1350 if key == 'source_traceback':
1351 tb = ''.join(traceback.format_list(value))
1352 value = 'Object created at (most recent call last):\n'
1353 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001354 elif key == 'handle_traceback':
1355 tb = ''.join(traceback.format_list(value))
1356 value = 'Handle created at (most recent call last):\n'
1357 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001358 else:
1359 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001360 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001361
1362 logger.error('\n'.join(log_lines), exc_info=exc_info)
1363
1364 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001365 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001366
Victor Stinneracdb7822014-07-14 18:33:40 +02001367 The context argument is a dict containing the following keys:
1368
Yury Selivanov569efa22014-02-18 18:02:19 -05001369 - 'message': Error message;
1370 - 'exception' (optional): Exception object;
1371 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001372 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001373 - 'handle' (optional): Handle instance;
1374 - 'protocol' (optional): Protocol instance;
1375 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001376 - 'socket' (optional): Socket instance;
1377 - 'asyncgen' (optional): Asynchronous generator that caused
1378 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001379
Victor Stinneracdb7822014-07-14 18:33:40 +02001380 New keys maybe introduced in the future.
1381
1382 Note: do not overload this method in an event loop subclass.
1383 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001384 `set_exception_handler()` method.
1385 """
1386 if self._exception_handler is None:
1387 try:
1388 self.default_exception_handler(context)
1389 except Exception:
1390 # Second protection layer for unexpected errors
1391 # in the default implementation, as well as for subclassed
1392 # event loops with overloaded "default_exception_handler".
1393 logger.error('Exception in default exception handler',
1394 exc_info=True)
1395 else:
1396 try:
1397 self._exception_handler(self, context)
1398 except Exception as exc:
1399 # Exception in the user set custom exception handler.
1400 try:
1401 # Let's try default handler.
1402 self.default_exception_handler({
1403 'message': 'Unhandled error in exception handler',
1404 'exception': exc,
1405 'context': context,
1406 })
1407 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001408 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001409 # overloaded.
1410 logger.error('Exception in default exception handler '
1411 'while handling an unexpected error '
1412 'in custom exception handler',
1413 exc_info=True)
1414
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001415 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001416 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001417 assert isinstance(handle, events.Handle), 'A Handle is required here'
1418 if handle._cancelled:
1419 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001420 assert not isinstance(handle, events.TimerHandle)
1421 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001422
1423 def _add_callback_signalsafe(self, handle):
1424 """Like _add_callback() but called from a signal handler."""
1425 self._add_callback(handle)
1426 self._write_to_self()
1427
Yury Selivanov592ada92014-09-25 12:07:56 -04001428 def _timer_handle_cancelled(self, handle):
1429 """Notification that a TimerHandle has been cancelled."""
1430 if handle._scheduled:
1431 self._timer_cancelled_count += 1
1432
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001433 def _run_once(self):
1434 """Run one full iteration of the event loop.
1435
1436 This calls all currently ready callbacks, polls for I/O,
1437 schedules the resulting callbacks, and finally schedules
1438 'call_later' callbacks.
1439 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001440
Yury Selivanov592ada92014-09-25 12:07:56 -04001441 sched_count = len(self._scheduled)
1442 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1443 self._timer_cancelled_count / sched_count >
1444 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001445 # Remove delayed calls that were cancelled if their number
1446 # is too high
1447 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001448 for handle in self._scheduled:
1449 if handle._cancelled:
1450 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001451 else:
1452 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001453
Victor Stinner68da8fc2014-09-30 18:08:36 +02001454 heapq.heapify(new_scheduled)
1455 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001456 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001457 else:
1458 # Remove delayed calls that were cancelled from head of queue.
1459 while self._scheduled and self._scheduled[0]._cancelled:
1460 self._timer_cancelled_count -= 1
1461 handle = heapq.heappop(self._scheduled)
1462 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001463
1464 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001465 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001466 timeout = 0
1467 elif self._scheduled:
1468 # Compute the desired timeout.
1469 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001470 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001471
Victor Stinner770e48d2014-07-11 11:58:33 +02001472 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001473 t0 = self.time()
1474 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001475 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001476 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001477 level = logging.INFO
1478 else:
1479 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001480 nevent = len(event_list)
1481 if timeout is None:
1482 logger.log(level, 'poll took %.3f ms: %s events',
1483 dt * 1e3, nevent)
1484 elif nevent:
1485 logger.log(level,
1486 'poll %.3f ms took %.3f ms: %s events',
1487 timeout * 1e3, dt * 1e3, nevent)
1488 elif dt >= 1.0:
1489 logger.log(level,
1490 'poll %.3f ms took %.3f ms: timeout',
1491 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001492 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001493 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001494 self._process_events(event_list)
1495
1496 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001497 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001498 while self._scheduled:
1499 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001500 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001501 break
1502 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001503 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001504 self._ready.append(handle)
1505
1506 # This is the only place where callbacks are actually *called*.
1507 # All other places just add them to ready.
1508 # Note: We run all currently scheduled callbacks, but not any
1509 # callbacks scheduled by callbacks run this time around --
1510 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001511 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001512 ntodo = len(self._ready)
1513 for i in range(ntodo):
1514 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001515 if handle._cancelled:
1516 continue
1517 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001518 try:
1519 self._current_handle = handle
1520 t0 = self.time()
1521 handle._run()
1522 dt = self.time() - t0
1523 if dt >= self.slow_callback_duration:
1524 logger.warning('Executing %s took %.3f seconds',
1525 _format_handle(handle), dt)
1526 finally:
1527 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001528 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001529 handle._run()
1530 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001531
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001532 def _set_coroutine_origin_tracking(self, enabled):
1533 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001534 return
1535
Yury Selivanove8944cb2015-05-12 11:43:04 -04001536 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001537 self._coroutine_origin_tracking_saved_depth = (
1538 sys.get_coroutine_origin_tracking_depth())
1539 sys.set_coroutine_origin_tracking_depth(
1540 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001541 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001542 sys.set_coroutine_origin_tracking_depth(
1543 self._coroutine_origin_tracking_saved_depth)
1544
1545 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001546
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001547 def get_debug(self):
1548 return self._debug
1549
1550 def set_debug(self, enabled):
1551 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001552
Yury Selivanove8944cb2015-05-12 11:43:04 -04001553 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001554 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)