blob: 94eb3089e938e03fde09aa5f38ba8143b4d8b261 [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
Yury Selivanovc9070d02018-01-25 18:08:09 -0500160 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
161 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200162 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500163 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200164 self._active_count = 0
165 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500166 self._protocol_factory = protocol_factory
167 self._backlog = backlog
168 self._ssl_context = ssl_context
169 self._ssl_handshake_timeout = ssl_handshake_timeout
170 self._serving = False
171 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700172
Victor Stinnere912e652014-07-12 03:11:53 +0200173 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500174 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200175
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200176 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500177 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200178 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700179
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200180 def _detach(self):
181 assert self._active_count > 0
182 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500183 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700184 self._wakeup()
185
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 waiters = self._waiters
188 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700189 for waiter in waiters:
190 if not waiter.done():
191 waiter.set_result(waiter)
192
Yury Selivanovc9070d02018-01-25 18:08:09 -0500193 def _start_serving(self):
194 if self._serving:
195 return
196 self._serving = True
197 for sock in self._sockets:
198 sock.listen(self._backlog)
199 self._loop._start_serving(
200 self._protocol_factory, sock, self._ssl_context,
201 self, self._backlog, self._ssl_handshake_timeout)
202
203 def get_loop(self):
204 return self._loop
205
206 def is_serving(self):
207 return self._serving
208
209 @property
210 def sockets(self):
211 if self._sockets is None:
212 return []
213 return list(self._sockets)
214
215 def close(self):
216 sockets = self._sockets
217 if sockets is None:
218 return
219 self._sockets = None
220
221 for sock in sockets:
222 self._loop._stop_serving(sock)
223
224 self._serving = False
225
226 if (self._serving_forever_fut is not None and
227 not self._serving_forever_fut.done()):
228 self._serving_forever_fut.cancel()
229 self._serving_forever_fut = None
230
231 if self._active_count == 0:
232 self._wakeup()
233
234 async def start_serving(self):
235 self._start_serving()
236
237 async def serve_forever(self):
238 if self._serving_forever_fut is not None:
239 raise RuntimeError(
240 f'server {self!r} is already being awaited on serve_forever()')
241 if self._sockets is None:
242 raise RuntimeError(f'server {self!r} is closed')
243
244 self._start_serving()
245 self._serving_forever_fut = self._loop.create_future()
246
247 try:
248 await self._serving_forever_fut
249 except futures.CancelledError:
250 try:
251 self.close()
252 await self.wait_closed()
253 finally:
254 raise
255 finally:
256 self._serving_forever_fut = None
257
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200258 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500259 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700260 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400261 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200262 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200263 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264
265
266class BaseEventLoop(events.AbstractEventLoop):
267
268 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400269 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200270 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800271 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700272 self._ready = collections.deque()
273 self._scheduled = []
274 self._default_executor = None
275 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100276 # Identifier of the thread running the event loop, or None if the
277 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100278 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100279 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500280 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800281 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200282 # In debug mode, if the execution of a callback or a step of a task
283 # exceed this duration in seconds, the slow callback/task is logged.
284 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100285 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400286 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800287 self._coroutine_origin_tracking_enabled = False
288 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700289
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500290 # A weak set of all asynchronous generators that are
291 # being iterated by the loop.
292 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700293 # Set to True when `loop.shutdown_asyncgens` is called.
294 self._asyncgens_shutdown_called = False
295
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200296 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500297 return (
298 f'<{self.__class__.__name__} running={self.is_running()} '
299 f'closed={self.is_closed()} debug={self.get_debug()}>'
300 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200301
Yury Selivanov7661db62016-05-16 15:38:39 -0400302 def create_future(self):
303 """Create a Future object attached to the loop."""
304 return futures.Future(loop=self)
305
Victor Stinner896a25a2014-07-08 11:29:25 +0200306 def create_task(self, coro):
307 """Schedule a coroutine object.
308
Victor Stinneracdb7822014-07-14 18:33:40 +0200309 Return a task object.
310 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100311 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400312 if self._task_factory is None:
313 task = tasks.Task(coro, loop=self)
314 if task._source_traceback:
315 del task._source_traceback[-1]
316 else:
317 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200318 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200319
Yury Selivanov740169c2015-05-11 14:23:38 -0400320 def set_task_factory(self, factory):
321 """Set a task factory that will be used by loop.create_task().
322
323 If factory is None the default task factory will be set.
324
325 If factory is a callable, it should have a signature matching
326 '(loop, coro)', where 'loop' will be a reference to the active
327 event loop, 'coro' will be a coroutine object. The callable
328 must return a Future.
329 """
330 if factory is not None and not callable(factory):
331 raise TypeError('task factory must be a callable or None')
332 self._task_factory = factory
333
334 def get_task_factory(self):
335 """Return a task factory, or None if the default one is in use."""
336 return self._task_factory
337
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700338 def _make_socket_transport(self, sock, protocol, waiter=None, *,
339 extra=None, server=None):
340 """Create socket transport."""
341 raise NotImplementedError
342
Neil Aspinallf7686c12017-12-19 19:45:42 +0000343 def _make_ssl_transport(
344 self, rawsock, protocol, sslcontext, waiter=None,
345 *, server_side=False, server_hostname=None,
346 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500347 ssl_handshake_timeout=None,
348 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700349 """Create SSL transport."""
350 raise NotImplementedError
351
352 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200353 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700354 """Create datagram transport."""
355 raise NotImplementedError
356
357 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
358 extra=None):
359 """Create read pipe transport."""
360 raise NotImplementedError
361
362 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
363 extra=None):
364 """Create write pipe transport."""
365 raise NotImplementedError
366
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200367 async def _make_subprocess_transport(self, protocol, args, shell,
368 stdin, stdout, stderr, bufsize,
369 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700370 """Create subprocess transport."""
371 raise NotImplementedError
372
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700373 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200374 """Write a byte to self-pipe, to wake up the event loop.
375
376 This may be called from a different thread.
377
378 The subclass is responsible for implementing the self-pipe.
379 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380 raise NotImplementedError
381
382 def _process_events(self, event_list):
383 """Process selector events."""
384 raise NotImplementedError
385
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200386 def _check_closed(self):
387 if self._closed:
388 raise RuntimeError('Event loop is closed')
389
Yury Selivanoveb636452016-09-08 22:01:51 -0700390 def _asyncgen_finalizer_hook(self, agen):
391 self._asyncgens.discard(agen)
392 if not self.is_closed():
393 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400394 # Wake up the loop if the finalizer was called from
395 # a different thread.
396 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700397
398 def _asyncgen_firstiter_hook(self, agen):
399 if self._asyncgens_shutdown_called:
400 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500401 f"asynchronous generator {agen!r} was scheduled after "
402 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700403 ResourceWarning, source=self)
404
405 self._asyncgens.add(agen)
406
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200407 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700408 """Shutdown all active asynchronous generators."""
409 self._asyncgens_shutdown_called = True
410
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500411 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400412 # If Python version is <3.6 or we don't have any asynchronous
413 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700414 return
415
416 closing_agens = list(self._asyncgens)
417 self._asyncgens.clear()
418
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200419 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700420 *[ag.aclose() for ag in closing_agens],
421 return_exceptions=True,
422 loop=self)
423
Yury Selivanoveb636452016-09-08 22:01:51 -0700424 for result, agen in zip(results, closing_agens):
425 if isinstance(result, Exception):
426 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500427 'message': f'an error occurred during closing of '
428 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700429 'exception': result,
430 'asyncgen': agen
431 })
432
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700433 def run_forever(self):
434 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200435 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100436 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400437 raise RuntimeError('This event loop is already running')
438 if events._get_running_loop() is not None:
439 raise RuntimeError(
440 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800441 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100442 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500443
444 old_agen_hooks = sys.get_asyncgen_hooks()
445 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
446 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400448 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700449 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800450 self._run_once()
451 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700452 break
453 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800454 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100455 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400456 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800457 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500458 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459
460 def run_until_complete(self, future):
461 """Run until the Future is done.
462
463 If the argument is a coroutine, it is wrapped in a Task.
464
Victor Stinneracdb7822014-07-14 18:33:40 +0200465 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 with the same coroutine twice -- it would wrap it in two
467 different Tasks and that can't be good.
468
469 Return the Future's result, or raise its exception.
470 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200471 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200472
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700473 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400474 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200475 if new_task:
476 # An exception is raised if the future didn't complete, so there
477 # is no need to log the "destroy pending task" message
478 future._log_destroy_pending = False
479
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100480 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200481 try:
482 self.run_forever()
483 except:
484 if new_task and future.done() and not future.cancelled():
485 # The coroutine raised a BaseException. Consume the exception
486 # to not log a warning, the caller doesn't have access to the
487 # local task.
488 future.exception()
489 raise
jimmylai21b3e042017-05-22 22:32:46 -0700490 finally:
491 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700492 if not future.done():
493 raise RuntimeError('Event loop stopped before Future completed.')
494
495 return future.result()
496
497 def stop(self):
498 """Stop running the event loop.
499
Guido van Rossum41f69f42015-11-19 13:28:47 -0800500 Every callback already scheduled will still run. This simply informs
501 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700502 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800503 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200505 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700506 """Close the event loop.
507
508 This clears the queues and shuts down the executor,
509 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200510
511 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700512 """
Victor Stinner956de692014-12-26 21:07:52 +0100513 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200514 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200515 if self._closed:
516 return
Victor Stinnere912e652014-07-12 03:11:53 +0200517 if self._debug:
518 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400519 self._closed = True
520 self._ready.clear()
521 self._scheduled.clear()
522 executor = self._default_executor
523 if executor is not None:
524 self._default_executor = None
525 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200526
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200527 def is_closed(self):
528 """Returns True if the event loop was closed."""
529 return self._closed
530
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900531 def __del__(self):
532 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500533 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900534 source=self)
535 if not self.is_running():
536 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100537
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200539 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100540 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700541
542 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200543 """Return the time according to the event loop's clock.
544
545 This is a float expressed in seconds since an epoch, but the
546 epoch, precision, accuracy and drift are unspecified and may
547 differ per event loop.
548 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 return time.monotonic()
550
Yury Selivanovf23746a2018-01-22 19:11:18 -0500551 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552 """Arrange for a callback to be called at a given time.
553
554 Return a Handle: an opaque object with a cancel() method that
555 can be used to cancel the call.
556
557 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200558 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700559
560 Each callback will be called exactly once. If two callbacks
561 are scheduled for exactly the same time, it undefined which
562 will be called first.
563
564 Any positional arguments after the callback will be passed to
565 the callback when it is called.
566 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500567 timer = self.call_at(self.time() + delay, callback, *args,
568 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200569 if timer._source_traceback:
570 del timer._source_traceback[-1]
571 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700572
Yury Selivanovf23746a2018-01-22 19:11:18 -0500573 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200574 """Like call_later(), but uses an absolute time.
575
576 Absolute time corresponds to the event loop's time() method.
577 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100578 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100579 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100580 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700581 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500582 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200583 if timer._source_traceback:
584 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400586 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587 return timer
588
Yury Selivanovf23746a2018-01-22 19:11:18 -0500589 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700590 """Arrange for a callback to be called as soon as possible.
591
Victor Stinneracdb7822014-07-14 18:33:40 +0200592 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700593 order in which they are registered. Each callback will be
594 called exactly once.
595
596 Any positional arguments after the callback will be passed to
597 the callback when it is called.
598 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700599 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100600 if self._debug:
601 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700602 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500603 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200604 if handle._source_traceback:
605 del handle._source_traceback[-1]
606 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100607
Yury Selivanov491a9122016-11-03 15:09:24 -0700608 def _check_callback(self, callback, method):
609 if (coroutines.iscoroutine(callback) or
610 coroutines.iscoroutinefunction(callback)):
611 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500612 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700613 if not callable(callback):
614 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500615 f'a callable object was expected by {method}(), '
616 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700617
Yury Selivanovf23746a2018-01-22 19:11:18 -0500618 def _call_soon(self, callback, args, context):
619 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200620 if handle._source_traceback:
621 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622 self._ready.append(handle)
623 return handle
624
Victor Stinner956de692014-12-26 21:07:52 +0100625 def _check_thread(self):
626 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100627
Victor Stinneracdb7822014-07-14 18:33:40 +0200628 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100629 likely behave incorrectly when the assumption is violated.
630
Victor Stinneracdb7822014-07-14 18:33:40 +0200631 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100632 responsible for checking this condition for performance reasons.
633 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100634 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200635 return
Victor Stinner956de692014-12-26 21:07:52 +0100636 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100637 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100638 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200639 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100640 "than the current one")
641
Yury Selivanovf23746a2018-01-22 19:11:18 -0500642 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200643 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700644 self._check_closed()
645 if self._debug:
646 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500647 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200648 if handle._source_traceback:
649 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700650 self._write_to_self()
651 return handle
652
Yury Selivanov19a44f62017-12-14 20:53:26 -0500653 async def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100654 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700655 if self._debug:
656 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657 if executor is None:
658 executor = self._default_executor
659 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400660 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700661 self._default_executor = executor
Yury Selivanov19a44f62017-12-14 20:53:26 -0500662 return await futures.wrap_future(
663 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664
665 def set_default_executor(self, executor):
666 self._default_executor = executor
667
Victor Stinnere912e652014-07-12 03:11:53 +0200668 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500669 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200670 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500671 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200672 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500673 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200674 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500675 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200676 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500677 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200678 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200679 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200680
681 t0 = self.time()
682 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
683 dt = self.time() - t0
684
Yury Selivanov6370f342017-12-10 18:36:12 -0500685 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200686 if dt >= self.slow_callback_duration:
687 logger.info(msg)
688 else:
689 logger.debug(msg)
690 return addrinfo
691
Yury Selivanov19a44f62017-12-14 20:53:26 -0500692 async def getaddrinfo(self, host, port, *,
693 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400694 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500695 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200696 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500697 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700698
Yury Selivanov19a44f62017-12-14 20:53:26 -0500699 return await self.run_in_executor(
700 None, getaddr_func, host, port, family, type, proto, flags)
701
702 async def getnameinfo(self, sockaddr, flags=0):
703 return await self.run_in_executor(
704 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200706 async def sock_sendfile(self, sock, file, offset=0, count=None,
707 *, fallback=True):
708 if self._debug and sock.gettimeout() != 0:
709 raise ValueError("the socket must be non-blocking")
710 self._check_sendfile_params(sock, file, offset, count)
711 try:
712 return await self._sock_sendfile_native(sock, file,
713 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200714 except events.SendfileNotAvailableError as exc:
715 if not fallback:
716 raise
717 return await self._sock_sendfile_fallback(sock, file,
718 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200719
720 async def _sock_sendfile_native(self, sock, file, offset, count):
721 # NB: sendfile syscall is not supported for SSL sockets and
722 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200723 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200724 f"syscall sendfile is not available for socket {sock!r} "
725 "and file {file!r} combination")
726
727 async def _sock_sendfile_fallback(self, sock, file, offset, count):
728 if offset:
729 file.seek(offset)
730 blocksize = min(count, 16384) if count else 16384
731 buf = bytearray(blocksize)
732 total_sent = 0
733 try:
734 while True:
735 if count:
736 blocksize = min(count - total_sent, blocksize)
737 if blocksize <= 0:
738 break
739 view = memoryview(buf)[:blocksize]
740 read = file.readinto(view)
741 if not read:
742 break # EOF
743 await self.sock_sendall(sock, view)
744 total_sent += read
745 return total_sent
746 finally:
747 if total_sent > 0 and hasattr(file, 'seek'):
748 file.seek(offset + total_sent)
749
750 def _check_sendfile_params(self, sock, file, offset, count):
751 if 'b' not in getattr(file, 'mode', 'b'):
752 raise ValueError("file should be opened in binary mode")
753 if not sock.type == socket.SOCK_STREAM:
754 raise ValueError("only SOCK_STREAM type sockets are supported")
755 if count is not None:
756 if not isinstance(count, int):
757 raise TypeError(
758 "count must be a positive integer (got {!r})".format(count))
759 if count <= 0:
760 raise ValueError(
761 "count must be a positive integer (got {!r})".format(count))
762 if not isinstance(offset, int):
763 raise TypeError(
764 "offset must be a non-negative integer (got {!r})".format(
765 offset))
766 if offset < 0:
767 raise ValueError(
768 "offset must be a non-negative integer (got {!r})".format(
769 offset))
770
Neil Aspinallf7686c12017-12-19 19:45:42 +0000771 async def create_connection(
772 self, protocol_factory, host=None, port=None,
773 *, ssl=None, family=0,
774 proto=0, flags=0, sock=None,
775 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200776 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200777 """Connect to a TCP server.
778
779 Create a streaming transport connection to a given Internet host and
780 port: socket family AF_INET or socket.AF_INET6 depending on host (or
781 family if specified), socket type SOCK_STREAM. protocol_factory must be
782 a callable returning a protocol instance.
783
784 This method is a coroutine which will try to establish the connection
785 in the background. When successful, the coroutine returns a
786 (transport, protocol) pair.
787 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700788 if server_hostname is not None and not ssl:
789 raise ValueError('server_hostname is only meaningful with ssl')
790
791 if server_hostname is None and ssl:
792 # Use host as default for server_hostname. It is an error
793 # if host is empty or not set, e.g. when an
794 # already-connected socket was passed or when only a port
795 # is given. To avoid this error, you can pass
796 # server_hostname='' -- this will bypass the hostname
797 # check. (This also means that if host is a numeric
798 # IP/IPv6 address, we will attempt to verify that exact
799 # address; this will probably fail, but it is possible to
800 # create a certificate for a specific IP address, so we
801 # don't judge it here.)
802 if not host:
803 raise ValueError('You must set server_hostname '
804 'when using ssl without a host')
805 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700806
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200807 if ssl_handshake_timeout is not None and not ssl:
808 raise ValueError(
809 'ssl_handshake_timeout is only meaningful with ssl')
810
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700811 if host is not None or port is not None:
812 if sock is not None:
813 raise ValueError(
814 'host/port and sock can not be specified at the same time')
815
Yury Selivanov19a44f62017-12-14 20:53:26 -0500816 infos = await self._ensure_resolved(
817 (host, port), family=family,
818 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700819 if not infos:
820 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500821
822 if local_addr is not None:
823 laddr_infos = await self._ensure_resolved(
824 local_addr, family=family,
825 type=socket.SOCK_STREAM, proto=proto,
826 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700827 if not laddr_infos:
828 raise OSError('getaddrinfo() returned empty list')
829
830 exceptions = []
831 for family, type, proto, cname, address in infos:
832 try:
833 sock = socket.socket(family=family, type=type, proto=proto)
834 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500835 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700836 for _, _, _, _, laddr in laddr_infos:
837 try:
838 sock.bind(laddr)
839 break
840 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500841 msg = (
842 f'error while attempting to bind on '
843 f'address {laddr!r}: '
844 f'{exc.strerror.lower()}'
845 )
846 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700847 exceptions.append(exc)
848 else:
849 sock.close()
850 sock = None
851 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200852 if self._debug:
853 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200854 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700855 except OSError as exc:
856 if sock is not None:
857 sock.close()
858 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200859 except:
860 if sock is not None:
861 sock.close()
862 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700863 else:
864 break
865 else:
866 if len(exceptions) == 1:
867 raise exceptions[0]
868 else:
869 # If they all have the same str(), raise one.
870 model = str(exceptions[0])
871 if all(str(exc) == model for exc in exceptions):
872 raise exceptions[0]
873 # Raise a combined exception so the user can see all
874 # the various error messages.
875 raise OSError('Multiple exceptions: {}'.format(
876 ', '.join(str(exc) for exc in exceptions)))
877
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500878 else:
879 if sock is None:
880 raise ValueError(
881 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500882 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500883 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
884 # are SOCK_STREAM.
885 # We support passing AF_UNIX sockets even though we have
886 # a dedicated API for that: create_unix_connection.
887 # Disallowing AF_UNIX in this method, breaks backwards
888 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500889 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500890 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700891
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200892 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000893 sock, protocol_factory, ssl, server_hostname,
894 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200895 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200896 # Get the socket from the transport because SSL transport closes
897 # the old socket and creates a new SSL socket
898 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200899 logger.debug("%r connected to %s:%r: (%r, %r)",
900 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500901 return transport, protocol
902
Neil Aspinallf7686c12017-12-19 19:45:42 +0000903 async def _create_connection_transport(
904 self, sock, protocol_factory, ssl,
905 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200906 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400907
908 sock.setblocking(False)
909
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700910 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400911 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700912 if ssl:
913 sslcontext = None if isinstance(ssl, bool) else ssl
914 transport = self._make_ssl_transport(
915 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000916 server_side=server_side, server_hostname=server_hostname,
917 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700918 else:
919 transport = self._make_socket_transport(sock, protocol, waiter)
920
Victor Stinner29ad0112015-01-15 00:04:21 +0100921 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200922 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100923 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100924 transport.close()
925 raise
926
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700927 return transport, protocol
928
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500929 async def start_tls(self, transport, protocol, sslcontext, *,
930 server_side=False,
931 server_hostname=None,
932 ssl_handshake_timeout=None):
933 """Upgrade transport to TLS.
934
935 Return a new transport that *protocol* should start using
936 immediately.
937 """
938 if ssl is None:
939 raise RuntimeError('Python ssl module is not available')
940
941 if not isinstance(sslcontext, ssl.SSLContext):
942 raise TypeError(
943 f'sslcontext is expected to be an instance of ssl.SSLContext, '
944 f'got {sslcontext!r}')
945
946 if not getattr(transport, '_start_tls_compatible', False):
947 raise TypeError(
948 f'transport {self!r} is not supported by start_tls()')
949
950 waiter = self.create_future()
951 ssl_protocol = sslproto.SSLProtocol(
952 self, protocol, sslcontext, waiter,
953 server_side, server_hostname,
954 ssl_handshake_timeout=ssl_handshake_timeout,
955 call_connection_made=False)
956
957 transport.set_protocol(ssl_protocol)
958 self.call_soon(ssl_protocol.connection_made, transport)
959 if not transport.is_reading():
960 self.call_soon(transport.resume_reading)
961
962 await waiter
963 return ssl_protocol._app_transport
964
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200965 async def create_datagram_endpoint(self, protocol_factory,
966 local_addr=None, remote_addr=None, *,
967 family=0, proto=0, flags=0,
968 reuse_address=None, reuse_port=None,
969 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700970 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700971 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500972 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500973 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500974 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700975 if (local_addr or remote_addr or
976 family or proto or flags or
977 reuse_address or reuse_port or allow_broadcast):
978 # show the problematic kwargs in exception msg
979 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
980 family=family, proto=proto, flags=flags,
981 reuse_address=reuse_address, reuse_port=reuse_port,
982 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -0500983 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700984 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500985 f'socket modifier keyword arguments can not be used '
986 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700987 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700988 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700989 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700990 if not (local_addr or remote_addr):
991 if family == 0:
992 raise ValueError('unexpected address family')
993 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100994 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
995 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100996 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100997 raise TypeError('string is expected')
998 addr_pairs_info = (((family, proto),
999 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001000 else:
1001 # join address by (family, protocol)
1002 addr_infos = collections.OrderedDict()
1003 for idx, addr in ((0, local_addr), (1, remote_addr)):
1004 if addr is not None:
1005 assert isinstance(addr, tuple) and len(addr) == 2, (
1006 '2-tuple is expected')
1007
Yury Selivanov19a44f62017-12-14 20:53:26 -05001008 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001009 addr, family=family, type=socket.SOCK_DGRAM,
1010 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001011 if not infos:
1012 raise OSError('getaddrinfo() returned empty list')
1013
1014 for fam, _, pro, _, address in infos:
1015 key = (fam, pro)
1016 if key not in addr_infos:
1017 addr_infos[key] = [None, None]
1018 addr_infos[key][idx] = address
1019
1020 # each addr has to have info for each (family, proto) pair
1021 addr_pairs_info = [
1022 (key, addr_pair) for key, addr_pair in addr_infos.items()
1023 if not ((local_addr and addr_pair[0] is None) or
1024 (remote_addr and addr_pair[1] is None))]
1025
1026 if not addr_pairs_info:
1027 raise ValueError('can not get address information')
1028
1029 exceptions = []
1030
1031 if reuse_address is None:
1032 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1033
1034 for ((family, proto),
1035 (local_address, remote_address)) in addr_pairs_info:
1036 sock = None
1037 r_addr = None
1038 try:
1039 sock = socket.socket(
1040 family=family, type=socket.SOCK_DGRAM, proto=proto)
1041 if reuse_address:
1042 sock.setsockopt(
1043 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1044 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001045 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001046 if allow_broadcast:
1047 sock.setsockopt(
1048 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1049 sock.setblocking(False)
1050
1051 if local_addr:
1052 sock.bind(local_address)
1053 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001054 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001055 r_addr = remote_address
1056 except OSError as exc:
1057 if sock is not None:
1058 sock.close()
1059 exceptions.append(exc)
1060 except:
1061 if sock is not None:
1062 sock.close()
1063 raise
1064 else:
1065 break
1066 else:
1067 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001068
1069 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001070 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001071 transport = self._make_datagram_transport(
1072 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001073 if self._debug:
1074 if local_addr:
1075 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1076 "created: (%r, %r)",
1077 local_addr, remote_addr, transport, protocol)
1078 else:
1079 logger.debug("Datagram endpoint remote_addr=%r created: "
1080 "(%r, %r)",
1081 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001082
1083 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001084 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001085 except:
1086 transport.close()
1087 raise
1088
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001089 return transport, protocol
1090
Yury Selivanov19a44f62017-12-14 20:53:26 -05001091 async def _ensure_resolved(self, address, *,
1092 family=0, type=socket.SOCK_STREAM,
1093 proto=0, flags=0, loop):
1094 host, port = address[:2]
1095 info = _ipaddr_info(host, port, family, type, proto)
1096 if info is not None:
1097 # "host" is already a resolved IP.
1098 return [info]
1099 else:
1100 return await loop.getaddrinfo(host, port, family=family, type=type,
1101 proto=proto, flags=flags)
1102
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001103 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001104 infos = await self._ensure_resolved((host, port), family=family,
1105 type=socket.SOCK_STREAM,
1106 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001107 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001108 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001109 return infos
1110
Neil Aspinallf7686c12017-12-19 19:45:42 +00001111 async def create_server(
1112 self, protocol_factory, host=None, port=None,
1113 *,
1114 family=socket.AF_UNSPEC,
1115 flags=socket.AI_PASSIVE,
1116 sock=None,
1117 backlog=100,
1118 ssl=None,
1119 reuse_address=None,
1120 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001121 ssl_handshake_timeout=None,
1122 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001123 """Create a TCP server.
1124
Yury Selivanov6370f342017-12-10 18:36:12 -05001125 The host parameter can be a string, in that case the TCP server is
1126 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001127
1128 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001129 the TCP server is bound to all hosts of the sequence. If a host
1130 appears multiple times (possibly indirectly e.g. when hostnames
1131 resolve to the same IP address), the server is only bound once to that
1132 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001133
Victor Stinneracdb7822014-07-14 18:33:40 +02001134 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001135
1136 This method is a coroutine.
1137 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001138 if isinstance(ssl, bool):
1139 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001140
1141 if ssl_handshake_timeout is not None and ssl is None:
1142 raise ValueError(
1143 'ssl_handshake_timeout is only meaningful with ssl')
1144
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001145 if host is not None or port is not None:
1146 if sock is not None:
1147 raise ValueError(
1148 'host/port and sock can not be specified at the same time')
1149
1150 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1151 if reuse_address is None:
1152 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1153 sockets = []
1154 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001155 hosts = [None]
1156 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001157 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001158 hosts = [host]
1159 else:
1160 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001161
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001162 fs = [self._create_server_getaddrinfo(host, port, family=family,
1163 flags=flags)
1164 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001165 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001166 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001167
1168 completed = False
1169 try:
1170 for res in infos:
1171 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001172 try:
1173 sock = socket.socket(af, socktype, proto)
1174 except socket.error:
1175 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001176 if self._debug:
1177 logger.warning('create_server() failed to create '
1178 'socket.socket(%r, %r, %r)',
1179 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001180 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001181 sockets.append(sock)
1182 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001183 sock.setsockopt(
1184 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1185 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001186 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001187 # Disable IPv4/IPv6 dual stack support (enabled by
1188 # default on Linux) which makes a single socket
1189 # listen on both address families.
1190 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1191 sock.setsockopt(socket.IPPROTO_IPV6,
1192 socket.IPV6_V6ONLY,
1193 True)
1194 try:
1195 sock.bind(sa)
1196 except OSError as err:
1197 raise OSError(err.errno, 'error while attempting '
1198 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001199 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001200 completed = True
1201 finally:
1202 if not completed:
1203 for sock in sockets:
1204 sock.close()
1205 else:
1206 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001207 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001208 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001209 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001210 sockets = [sock]
1211
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001212 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001213 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001214
1215 server = Server(self, sockets, protocol_factory,
1216 ssl, backlog, ssl_handshake_timeout)
1217 if start_serving:
1218 server._start_serving()
1219
Victor Stinnere912e652014-07-12 03:11:53 +02001220 if self._debug:
1221 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001222 return server
1223
Neil Aspinallf7686c12017-12-19 19:45:42 +00001224 async def connect_accepted_socket(
1225 self, protocol_factory, sock,
1226 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001227 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001228 """Handle an accepted connection.
1229
1230 This is used by servers that accept connections outside of
1231 asyncio but that use asyncio to handle connections.
1232
1233 This method is a coroutine. When completed, the coroutine
1234 returns a (transport, protocol) pair.
1235 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001236 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001237 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001238
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001239 if ssl_handshake_timeout is not None and not ssl:
1240 raise ValueError(
1241 'ssl_handshake_timeout is only meaningful with ssl')
1242
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001243 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001244 sock, protocol_factory, ssl, '', server_side=True,
1245 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001246 if self._debug:
1247 # Get the socket from the transport because SSL transport closes
1248 # the old socket and creates a new SSL socket
1249 sock = transport.get_extra_info('socket')
1250 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1251 return transport, protocol
1252
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001253 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001254 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001255 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001256 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001257
1258 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001259 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001260 except:
1261 transport.close()
1262 raise
1263
Victor Stinneracdb7822014-07-14 18:33:40 +02001264 if self._debug:
1265 logger.debug('Read pipe %r connected: (%r, %r)',
1266 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001267 return transport, protocol
1268
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001269 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001270 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001271 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001272 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001273
1274 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001275 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001276 except:
1277 transport.close()
1278 raise
1279
Victor Stinneracdb7822014-07-14 18:33:40 +02001280 if self._debug:
1281 logger.debug('Write pipe %r connected: (%r, %r)',
1282 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001283 return transport, protocol
1284
Victor Stinneracdb7822014-07-14 18:33:40 +02001285 def _log_subprocess(self, msg, stdin, stdout, stderr):
1286 info = [msg]
1287 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001288 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001289 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001290 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001291 else:
1292 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001293 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001294 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001295 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001296 logger.debug(' '.join(info))
1297
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001298 async def subprocess_shell(self, protocol_factory, cmd, *,
1299 stdin=subprocess.PIPE,
1300 stdout=subprocess.PIPE,
1301 stderr=subprocess.PIPE,
1302 universal_newlines=False,
1303 shell=True, bufsize=0,
1304 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001305 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001306 raise ValueError("cmd must be a string")
1307 if universal_newlines:
1308 raise ValueError("universal_newlines must be False")
1309 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001310 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001311 if bufsize != 0:
1312 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001313 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001314 if self._debug:
1315 # don't log parameters: they may contain sensitive information
1316 # (password) and may be too long
1317 debug_log = 'run shell command %r' % cmd
1318 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001319 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001320 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001321 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001322 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323 return transport, protocol
1324
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001325 async def subprocess_exec(self, protocol_factory, program, *args,
1326 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1327 stderr=subprocess.PIPE, universal_newlines=False,
1328 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001329 if universal_newlines:
1330 raise ValueError("universal_newlines must be False")
1331 if shell:
1332 raise ValueError("shell must be False")
1333 if bufsize != 0:
1334 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001335 popen_args = (program,) + args
1336 for arg in popen_args:
1337 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001338 raise TypeError(
1339 f"program arguments must be a bytes or text string, "
1340 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001341 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001342 if self._debug:
1343 # don't log parameters: they may contain sensitive information
1344 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001345 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001346 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001347 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001348 protocol, popen_args, False, stdin, stdout, stderr,
1349 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001350 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001351 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001352 return transport, protocol
1353
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001354 def get_exception_handler(self):
1355 """Return an exception handler, or None if the default one is in use.
1356 """
1357 return self._exception_handler
1358
Yury Selivanov569efa22014-02-18 18:02:19 -05001359 def set_exception_handler(self, handler):
1360 """Set handler as the new event loop exception handler.
1361
1362 If handler is None, the default exception handler will
1363 be set.
1364
1365 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001366 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001367 will be a reference to the active event loop, 'context'
1368 will be a dict object (see `call_exception_handler()`
1369 documentation for details about context).
1370 """
1371 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001372 raise TypeError(f'A callable object or None is expected, '
1373 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001374 self._exception_handler = handler
1375
1376 def default_exception_handler(self, context):
1377 """Default exception handler.
1378
1379 This is called when an exception occurs and no exception
1380 handler is set, and can be called by a custom exception
1381 handler that wants to defer to the default behavior.
1382
Antoine Pitrou921e9432017-11-07 17:23:29 +01001383 This default handler logs the error message and other
1384 context-dependent information. In debug mode, a truncated
1385 stack trace is also appended showing where the given object
1386 (e.g. a handle or future or task) was created, if any.
1387
Victor Stinneracdb7822014-07-14 18:33:40 +02001388 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001389 `call_exception_handler()`.
1390 """
1391 message = context.get('message')
1392 if not message:
1393 message = 'Unhandled exception in event loop'
1394
1395 exception = context.get('exception')
1396 if exception is not None:
1397 exc_info = (type(exception), exception, exception.__traceback__)
1398 else:
1399 exc_info = False
1400
Yury Selivanov6370f342017-12-10 18:36:12 -05001401 if ('source_traceback' not in context and
1402 self._current_handle is not None and
1403 self._current_handle._source_traceback):
1404 context['handle_traceback'] = \
1405 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001406
Yury Selivanov569efa22014-02-18 18:02:19 -05001407 log_lines = [message]
1408 for key in sorted(context):
1409 if key in {'message', 'exception'}:
1410 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001411 value = context[key]
1412 if key == 'source_traceback':
1413 tb = ''.join(traceback.format_list(value))
1414 value = 'Object created at (most recent call last):\n'
1415 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001416 elif key == 'handle_traceback':
1417 tb = ''.join(traceback.format_list(value))
1418 value = 'Handle created at (most recent call last):\n'
1419 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001420 else:
1421 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001422 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001423
1424 logger.error('\n'.join(log_lines), exc_info=exc_info)
1425
1426 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001427 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001428
Victor Stinneracdb7822014-07-14 18:33:40 +02001429 The context argument is a dict containing the following keys:
1430
Yury Selivanov569efa22014-02-18 18:02:19 -05001431 - 'message': Error message;
1432 - 'exception' (optional): Exception object;
1433 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001434 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001435 - 'handle' (optional): Handle instance;
1436 - 'protocol' (optional): Protocol instance;
1437 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001438 - 'socket' (optional): Socket instance;
1439 - 'asyncgen' (optional): Asynchronous generator that caused
1440 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001441
Victor Stinneracdb7822014-07-14 18:33:40 +02001442 New keys maybe introduced in the future.
1443
1444 Note: do not overload this method in an event loop subclass.
1445 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001446 `set_exception_handler()` method.
1447 """
1448 if self._exception_handler is None:
1449 try:
1450 self.default_exception_handler(context)
1451 except Exception:
1452 # Second protection layer for unexpected errors
1453 # in the default implementation, as well as for subclassed
1454 # event loops with overloaded "default_exception_handler".
1455 logger.error('Exception in default exception handler',
1456 exc_info=True)
1457 else:
1458 try:
1459 self._exception_handler(self, context)
1460 except Exception as exc:
1461 # Exception in the user set custom exception handler.
1462 try:
1463 # Let's try default handler.
1464 self.default_exception_handler({
1465 'message': 'Unhandled error in exception handler',
1466 'exception': exc,
1467 'context': context,
1468 })
1469 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001470 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001471 # overloaded.
1472 logger.error('Exception in default exception handler '
1473 'while handling an unexpected error '
1474 'in custom exception handler',
1475 exc_info=True)
1476
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001477 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001478 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001479 assert isinstance(handle, events.Handle), 'A Handle is required here'
1480 if handle._cancelled:
1481 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001482 assert not isinstance(handle, events.TimerHandle)
1483 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001484
1485 def _add_callback_signalsafe(self, handle):
1486 """Like _add_callback() but called from a signal handler."""
1487 self._add_callback(handle)
1488 self._write_to_self()
1489
Yury Selivanov592ada92014-09-25 12:07:56 -04001490 def _timer_handle_cancelled(self, handle):
1491 """Notification that a TimerHandle has been cancelled."""
1492 if handle._scheduled:
1493 self._timer_cancelled_count += 1
1494
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001495 def _run_once(self):
1496 """Run one full iteration of the event loop.
1497
1498 This calls all currently ready callbacks, polls for I/O,
1499 schedules the resulting callbacks, and finally schedules
1500 'call_later' callbacks.
1501 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001502
Yury Selivanov592ada92014-09-25 12:07:56 -04001503 sched_count = len(self._scheduled)
1504 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1505 self._timer_cancelled_count / sched_count >
1506 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001507 # Remove delayed calls that were cancelled if their number
1508 # is too high
1509 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001510 for handle in self._scheduled:
1511 if handle._cancelled:
1512 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001513 else:
1514 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001515
Victor Stinner68da8fc2014-09-30 18:08:36 +02001516 heapq.heapify(new_scheduled)
1517 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001518 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001519 else:
1520 # Remove delayed calls that were cancelled from head of queue.
1521 while self._scheduled and self._scheduled[0]._cancelled:
1522 self._timer_cancelled_count -= 1
1523 handle = heapq.heappop(self._scheduled)
1524 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001525
1526 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001527 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001528 timeout = 0
1529 elif self._scheduled:
1530 # Compute the desired timeout.
1531 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001532 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001533
Victor Stinner770e48d2014-07-11 11:58:33 +02001534 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001535 t0 = self.time()
1536 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001537 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001538 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001539 level = logging.INFO
1540 else:
1541 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001542 nevent = len(event_list)
1543 if timeout is None:
1544 logger.log(level, 'poll took %.3f ms: %s events',
1545 dt * 1e3, nevent)
1546 elif nevent:
1547 logger.log(level,
1548 'poll %.3f ms took %.3f ms: %s events',
1549 timeout * 1e3, dt * 1e3, nevent)
1550 elif dt >= 1.0:
1551 logger.log(level,
1552 'poll %.3f ms took %.3f ms: timeout',
1553 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001554 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001555 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001556 self._process_events(event_list)
1557
1558 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001559 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001560 while self._scheduled:
1561 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001562 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001563 break
1564 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001565 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001566 self._ready.append(handle)
1567
1568 # This is the only place where callbacks are actually *called*.
1569 # All other places just add them to ready.
1570 # Note: We run all currently scheduled callbacks, but not any
1571 # callbacks scheduled by callbacks run this time around --
1572 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001573 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001574 ntodo = len(self._ready)
1575 for i in range(ntodo):
1576 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001577 if handle._cancelled:
1578 continue
1579 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001580 try:
1581 self._current_handle = handle
1582 t0 = self.time()
1583 handle._run()
1584 dt = self.time() - t0
1585 if dt >= self.slow_callback_duration:
1586 logger.warning('Executing %s took %.3f seconds',
1587 _format_handle(handle), dt)
1588 finally:
1589 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001590 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001591 handle._run()
1592 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001593
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001594 def _set_coroutine_origin_tracking(self, enabled):
1595 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001596 return
1597
Yury Selivanove8944cb2015-05-12 11:43:04 -04001598 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001599 self._coroutine_origin_tracking_saved_depth = (
1600 sys.get_coroutine_origin_tracking_depth())
1601 sys.set_coroutine_origin_tracking_depth(
1602 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001603 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001604 sys.set_coroutine_origin_tracking_depth(
1605 self._coroutine_origin_tracking_saved_depth)
1606
1607 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001608
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001609 def get_debug(self):
1610 return self._debug
1611
1612 def set_debug(self, enabled):
1613 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001614
Yury Selivanove8944cb2015-05-12 11:43:04 -04001615 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001616 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)