blob: a79e123e5113d9fc5410127ddb0514ae2472cfe9 [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
Andrew Svetlov7c684072018-01-27 21:22:47 +020041from . import protocols
Yury Selivanovf111b3d2017-12-30 00:35:36 -050042from . import sslproto
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070043from . import tasks
Andrew Svetlov7c684072018-01-27 21:22:47 +020044from . import transports
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070045from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046
47
Yury Selivanov6370f342017-12-10 18:36:12 -050048__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049
50
Yury Selivanov592ada92014-09-25 12:07:56 -040051# Minimum number of _scheduled timer handles before cleanup of
52# cancelled handles is performed.
53_MIN_SCHEDULED_TIMER_HANDLES = 100
54
55# Minimum fraction of _scheduled timer handles that are cancelled
56# before cleanup of cancelled handles is performed.
57_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070058
Victor Stinnerc94a93a2016-04-01 21:43:39 +020059# Exceptions which must not call the exception handler in fatal error
60# methods (_fatal_error())
61_FATAL_ERROR_IGNORE = (BrokenPipeError,
62 ConnectionResetError, ConnectionAbortedError)
63
Miss Islington (bot)3ed44142018-06-28 19:16:48 -070064_HAS_IPv6 = hasattr(socket, 'AF_INET6')
65
Miss Islington (bot)172a81e2018-07-31 08:29:07 -070066# Maximum timeout passed to select to avoid OS limitations
67MAXIMUM_SELECT_TIMEOUT = 24 * 3600
68
Victor Stinnerc94a93a2016-04-01 21:43:39 +020069
Victor Stinner0e6f52a2014-06-20 17:34:15 +020070def _format_handle(handle):
71 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040072 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020073 # format the task
74 return repr(cb.__self__)
75 else:
76 return str(handle)
77
78
Victor Stinneracdb7822014-07-14 18:33:40 +020079def _format_pipe(fd):
80 if fd == subprocess.PIPE:
81 return '<pipe>'
82 elif fd == subprocess.STDOUT:
83 return '<stdout>'
84 else:
85 return repr(fd)
86
87
Yury Selivanov5587d7c2016-09-15 15:45:07 -040088def _set_reuseport(sock):
89 if not hasattr(socket, 'SO_REUSEPORT'):
90 raise ValueError('reuse_port not supported by socket module')
91 else:
92 try:
93 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
94 except OSError:
95 raise ValueError('reuse_port not supported by socket module, '
96 'SO_REUSEPORT defined but not implemented.')
97
98
Yury Selivanovd5c2a622015-12-16 19:31:17 -050099def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400100 # Try to skip getaddrinfo if "host" is already an IP. Users might have
101 # handled name resolution in their own code and pass in resolved IPs.
102 if not hasattr(socket, 'inet_pton'):
103 return
104
105 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
106 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 return None
108
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500109 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500110 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500111 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500112 proto = socket.IPPROTO_UDP
113 else:
114 return None
115
Yury Selivanova7146162016-06-02 16:51:07 -0400116 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400117 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700118 elif isinstance(port, bytes) and port == b'':
119 port = 0
120 elif isinstance(port, str) and port == '':
121 port = 0
122 else:
123 # If port's a service name like "http", don't skip getaddrinfo.
124 try:
125 port = int(port)
126 except (TypeError, ValueError):
127 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400128
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400129 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500130 afs = [socket.AF_INET]
Miss Islington (bot)3ed44142018-06-28 19:16:48 -0700131 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500132 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400133 else:
134 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500135
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 if isinstance(host, bytes):
137 host = host.decode('idna')
138 if '%' in host:
139 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
140 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500141 return None
142
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400143 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500144 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400145 socket.inet_pton(af, host)
146 # The host has already been resolved.
Miss Islington (bot)3ed44142018-06-28 19:16:48 -0700147 if _HAS_IPv6 and af == socket.AF_INET6:
148 return af, type, proto, '', (host, port, 0, 0)
149 else:
150 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 except OSError:
152 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500153
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400154 # "host" is not an IP address.
155 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500156
157
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100158def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500159 if not fut.cancelled():
160 exc = fut.exception()
161 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
162 # Issue #22429: run_forever() already finished, no need to
163 # stop it.
164 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500165 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100166
167
Andrew Svetlov7c684072018-01-27 21:22:47 +0200168class _SendfileFallbackProtocol(protocols.Protocol):
169 def __init__(self, transp):
170 if not isinstance(transp, transports._FlowControlMixin):
171 raise TypeError("transport should be _FlowControlMixin instance")
172 self._transport = transp
173 self._proto = transp.get_protocol()
174 self._should_resume_reading = transp.is_reading()
175 self._should_resume_writing = transp._protocol_paused
176 transp.pause_reading()
177 transp.set_protocol(self)
178 if self._should_resume_writing:
179 self._write_ready_fut = self._transport._loop.create_future()
180 else:
181 self._write_ready_fut = None
182
183 async def drain(self):
184 if self._transport.is_closing():
185 raise ConnectionError("Connection closed by peer")
186 fut = self._write_ready_fut
187 if fut is None:
188 return
189 await fut
190
191 def connection_made(self, transport):
192 raise RuntimeError("Invalid state: "
193 "connection should have been established already.")
194
195 def connection_lost(self, exc):
196 if self._write_ready_fut is not None:
197 # Never happens if peer disconnects after sending the whole content
198 # Thus disconnection is always an exception from user perspective
199 if exc is None:
200 self._write_ready_fut.set_exception(
201 ConnectionError("Connection is closed by peer"))
202 else:
203 self._write_ready_fut.set_exception(exc)
204 self._proto.connection_lost(exc)
205
206 def pause_writing(self):
207 if self._write_ready_fut is not None:
208 return
209 self._write_ready_fut = self._transport._loop.create_future()
210
211 def resume_writing(self):
212 if self._write_ready_fut is None:
213 return
214 self._write_ready_fut.set_result(False)
215 self._write_ready_fut = None
216
217 def data_received(self, data):
218 raise RuntimeError("Invalid state: reading should be paused")
219
220 def eof_received(self):
221 raise RuntimeError("Invalid state: reading should be paused")
222
223 async def restore(self):
224 self._transport.set_protocol(self._proto)
225 if self._should_resume_reading:
226 self._transport.resume_reading()
227 if self._write_ready_fut is not None:
228 # Cancel the future.
229 # Basically it has no effect because protocol is switched back,
230 # no code should wait for it anymore.
231 self._write_ready_fut.cancel()
232 if self._should_resume_writing:
233 self._proto.resume_writing()
234
235
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700236class Server(events.AbstractServer):
237
Yury Selivanovc9070d02018-01-25 18:08:09 -0500238 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
239 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200240 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500241 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200242 self._active_count = 0
243 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500244 self._protocol_factory = protocol_factory
245 self._backlog = backlog
246 self._ssl_context = ssl_context
247 self._ssl_handshake_timeout = ssl_handshake_timeout
248 self._serving = False
249 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250
Victor Stinnere912e652014-07-12 03:11:53 +0200251 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500252 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200253
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200254 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500255 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200256 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700257
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200258 def _detach(self):
259 assert self._active_count > 0
260 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500261 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262 self._wakeup()
263
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200265 waiters = self._waiters
266 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700267 for waiter in waiters:
268 if not waiter.done():
269 waiter.set_result(waiter)
270
Yury Selivanovc9070d02018-01-25 18:08:09 -0500271 def _start_serving(self):
272 if self._serving:
273 return
274 self._serving = True
275 for sock in self._sockets:
276 sock.listen(self._backlog)
277 self._loop._start_serving(
278 self._protocol_factory, sock, self._ssl_context,
279 self, self._backlog, self._ssl_handshake_timeout)
280
281 def get_loop(self):
282 return self._loop
283
284 def is_serving(self):
285 return self._serving
286
287 @property
288 def sockets(self):
289 if self._sockets is None:
290 return []
291 return list(self._sockets)
292
293 def close(self):
294 sockets = self._sockets
295 if sockets is None:
296 return
297 self._sockets = None
298
299 for sock in sockets:
300 self._loop._stop_serving(sock)
301
302 self._serving = False
303
304 if (self._serving_forever_fut is not None and
305 not self._serving_forever_fut.done()):
306 self._serving_forever_fut.cancel()
307 self._serving_forever_fut = None
308
309 if self._active_count == 0:
310 self._wakeup()
311
312 async def start_serving(self):
313 self._start_serving()
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -0700314 # Skip one loop iteration so that all 'loop.add_reader'
315 # go through.
316 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500317
318 async def serve_forever(self):
319 if self._serving_forever_fut is not None:
320 raise RuntimeError(
321 f'server {self!r} is already being awaited on serve_forever()')
322 if self._sockets is None:
323 raise RuntimeError(f'server {self!r} is closed')
324
325 self._start_serving()
326 self._serving_forever_fut = self._loop.create_future()
327
328 try:
329 await self._serving_forever_fut
330 except futures.CancelledError:
331 try:
332 self.close()
333 await self.wait_closed()
334 finally:
335 raise
336 finally:
337 self._serving_forever_fut = None
338
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200339 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500340 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700341 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400342 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200343 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200344 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700345
346
347class BaseEventLoop(events.AbstractEventLoop):
348
349 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400350 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200351 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800352 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700353 self._ready = collections.deque()
354 self._scheduled = []
355 self._default_executor = None
356 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100357 # Identifier of the thread running the event loop, or None if the
358 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100359 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100360 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500361 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800362 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200363 # In debug mode, if the execution of a callback or a step of a task
364 # exceed this duration in seconds, the slow callback/task is logged.
365 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100366 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400367 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800368 self._coroutine_origin_tracking_enabled = False
369 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700370
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500371 # A weak set of all asynchronous generators that are
372 # being iterated by the loop.
373 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700374 # Set to True when `loop.shutdown_asyncgens` is called.
375 self._asyncgens_shutdown_called = False
376
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200377 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500378 return (
379 f'<{self.__class__.__name__} running={self.is_running()} '
380 f'closed={self.is_closed()} debug={self.get_debug()}>'
381 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200382
Yury Selivanov7661db62016-05-16 15:38:39 -0400383 def create_future(self):
384 """Create a Future object attached to the loop."""
385 return futures.Future(loop=self)
386
Victor Stinner896a25a2014-07-08 11:29:25 +0200387 def create_task(self, coro):
388 """Schedule a coroutine object.
389
Victor Stinneracdb7822014-07-14 18:33:40 +0200390 Return a task object.
391 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100392 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400393 if self._task_factory is None:
394 task = tasks.Task(coro, loop=self)
395 if task._source_traceback:
396 del task._source_traceback[-1]
397 else:
398 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200399 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200400
Yury Selivanov740169c2015-05-11 14:23:38 -0400401 def set_task_factory(self, factory):
402 """Set a task factory that will be used by loop.create_task().
403
404 If factory is None the default task factory will be set.
405
406 If factory is a callable, it should have a signature matching
407 '(loop, coro)', where 'loop' will be a reference to the active
408 event loop, 'coro' will be a coroutine object. The callable
409 must return a Future.
410 """
411 if factory is not None and not callable(factory):
412 raise TypeError('task factory must be a callable or None')
413 self._task_factory = factory
414
415 def get_task_factory(self):
416 """Return a task factory, or None if the default one is in use."""
417 return self._task_factory
418
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700419 def _make_socket_transport(self, sock, protocol, waiter=None, *,
420 extra=None, server=None):
421 """Create socket transport."""
422 raise NotImplementedError
423
Neil Aspinallf7686c12017-12-19 19:45:42 +0000424 def _make_ssl_transport(
425 self, rawsock, protocol, sslcontext, waiter=None,
426 *, server_side=False, server_hostname=None,
427 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500428 ssl_handshake_timeout=None,
429 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700430 """Create SSL transport."""
431 raise NotImplementedError
432
433 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200434 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700435 """Create datagram transport."""
436 raise NotImplementedError
437
438 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
439 extra=None):
440 """Create read pipe transport."""
441 raise NotImplementedError
442
443 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
444 extra=None):
445 """Create write pipe transport."""
446 raise NotImplementedError
447
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200448 async def _make_subprocess_transport(self, protocol, args, shell,
449 stdin, stdout, stderr, bufsize,
450 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700451 """Create subprocess transport."""
452 raise NotImplementedError
453
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700454 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200455 """Write a byte to self-pipe, to wake up the event loop.
456
457 This may be called from a different thread.
458
459 The subclass is responsible for implementing the self-pipe.
460 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700461 raise NotImplementedError
462
463 def _process_events(self, event_list):
464 """Process selector events."""
465 raise NotImplementedError
466
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200467 def _check_closed(self):
468 if self._closed:
469 raise RuntimeError('Event loop is closed')
470
Yury Selivanoveb636452016-09-08 22:01:51 -0700471 def _asyncgen_finalizer_hook(self, agen):
472 self._asyncgens.discard(agen)
473 if not self.is_closed():
474 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400475 # Wake up the loop if the finalizer was called from
476 # a different thread.
477 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700478
479 def _asyncgen_firstiter_hook(self, agen):
480 if self._asyncgens_shutdown_called:
481 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500482 f"asynchronous generator {agen!r} was scheduled after "
483 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700484 ResourceWarning, source=self)
485
486 self._asyncgens.add(agen)
487
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200488 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700489 """Shutdown all active asynchronous generators."""
490 self._asyncgens_shutdown_called = True
491
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500492 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400493 # If Python version is <3.6 or we don't have any asynchronous
494 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700495 return
496
497 closing_agens = list(self._asyncgens)
498 self._asyncgens.clear()
499
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200500 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700501 *[ag.aclose() for ag in closing_agens],
502 return_exceptions=True,
503 loop=self)
504
Yury Selivanoveb636452016-09-08 22:01:51 -0700505 for result, agen in zip(results, closing_agens):
506 if isinstance(result, Exception):
507 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500508 'message': f'an error occurred during closing of '
509 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700510 'exception': result,
511 'asyncgen': agen
512 })
513
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 def run_forever(self):
515 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200516 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100517 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400518 raise RuntimeError('This event loop is already running')
519 if events._get_running_loop() is not None:
520 raise RuntimeError(
521 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800522 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100523 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500524
525 old_agen_hooks = sys.get_asyncgen_hooks()
526 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
527 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400529 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800531 self._run_once()
532 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 break
534 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800535 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100536 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400537 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800538 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500539 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700540
541 def run_until_complete(self, future):
542 """Run until the Future is done.
543
544 If the argument is a coroutine, it is wrapped in a Task.
545
Victor Stinneracdb7822014-07-14 18:33:40 +0200546 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700547 with the same coroutine twice -- it would wrap it in two
548 different Tasks and that can't be good.
549
550 Return the Future's result, or raise its exception.
551 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200552 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200553
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700554 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400555 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200556 if new_task:
557 # An exception is raised if the future didn't complete, so there
558 # is no need to log the "destroy pending task" message
559 future._log_destroy_pending = False
560
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100561 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200562 try:
563 self.run_forever()
564 except:
565 if new_task and future.done() and not future.cancelled():
566 # The coroutine raised a BaseException. Consume the exception
567 # to not log a warning, the caller doesn't have access to the
568 # local task.
569 future.exception()
570 raise
jimmylai21b3e042017-05-22 22:32:46 -0700571 finally:
572 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573 if not future.done():
574 raise RuntimeError('Event loop stopped before Future completed.')
575
576 return future.result()
577
578 def stop(self):
579 """Stop running the event loop.
580
Guido van Rossum41f69f42015-11-19 13:28:47 -0800581 Every callback already scheduled will still run. This simply informs
582 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700583 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800584 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200586 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700587 """Close the event loop.
588
589 This clears the queues and shuts down the executor,
590 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200591
592 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700593 """
Victor Stinner956de692014-12-26 21:07:52 +0100594 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200595 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200596 if self._closed:
597 return
Victor Stinnere912e652014-07-12 03:11:53 +0200598 if self._debug:
599 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400600 self._closed = True
601 self._ready.clear()
602 self._scheduled.clear()
603 executor = self._default_executor
604 if executor is not None:
605 self._default_executor = None
606 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200607
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200608 def is_closed(self):
609 """Returns True if the event loop was closed."""
610 return self._closed
611
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900612 def __del__(self):
613 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500614 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900615 source=self)
616 if not self.is_running():
617 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100618
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700619 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200620 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100621 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622
623 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200624 """Return the time according to the event loop's clock.
625
626 This is a float expressed in seconds since an epoch, but the
627 epoch, precision, accuracy and drift are unspecified and may
628 differ per event loop.
629 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630 return time.monotonic()
631
Yury Selivanovf23746a2018-01-22 19:11:18 -0500632 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700633 """Arrange for a callback to be called at a given time.
634
635 Return a Handle: an opaque object with a cancel() method that
636 can be used to cancel the call.
637
638 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200639 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700640
641 Each callback will be called exactly once. If two callbacks
642 are scheduled for exactly the same time, it undefined which
643 will be called first.
644
645 Any positional arguments after the callback will be passed to
646 the callback when it is called.
647 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500648 timer = self.call_at(self.time() + delay, callback, *args,
649 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200650 if timer._source_traceback:
651 del timer._source_traceback[-1]
652 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700653
Yury Selivanovf23746a2018-01-22 19:11:18 -0500654 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200655 """Like call_later(), but uses an absolute time.
656
657 Absolute time corresponds to the event loop's time() method.
658 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100659 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100660 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100661 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700662 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500663 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200664 if timer._source_traceback:
665 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700666 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400667 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700668 return timer
669
Yury Selivanovf23746a2018-01-22 19:11:18 -0500670 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700671 """Arrange for a callback to be called as soon as possible.
672
Victor Stinneracdb7822014-07-14 18:33:40 +0200673 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700674 order in which they are registered. Each callback will be
675 called exactly once.
676
677 Any positional arguments after the callback will be passed to
678 the callback when it is called.
679 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700680 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100681 if self._debug:
682 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700683 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500684 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200685 if handle._source_traceback:
686 del handle._source_traceback[-1]
687 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100688
Yury Selivanov491a9122016-11-03 15:09:24 -0700689 def _check_callback(self, callback, method):
690 if (coroutines.iscoroutine(callback) or
691 coroutines.iscoroutinefunction(callback)):
692 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500693 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700694 if not callable(callback):
695 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500696 f'a callable object was expected by {method}(), '
697 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700698
Yury Selivanovf23746a2018-01-22 19:11:18 -0500699 def _call_soon(self, callback, args, context):
700 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200701 if handle._source_traceback:
702 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700703 self._ready.append(handle)
704 return handle
705
Victor Stinner956de692014-12-26 21:07:52 +0100706 def _check_thread(self):
707 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100708
Victor Stinneracdb7822014-07-14 18:33:40 +0200709 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100710 likely behave incorrectly when the assumption is violated.
711
Victor Stinneracdb7822014-07-14 18:33:40 +0200712 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100713 responsible for checking this condition for performance reasons.
714 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100715 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200716 return
Victor Stinner956de692014-12-26 21:07:52 +0100717 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100718 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100719 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200720 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100721 "than the current one")
722
Yury Selivanovf23746a2018-01-22 19:11:18 -0500723 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200724 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700725 self._check_closed()
726 if self._debug:
727 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500728 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200729 if handle._source_traceback:
730 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700731 self._write_to_self()
732 return handle
733
Yury Selivanovbec23722018-01-28 14:09:40 -0500734 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100735 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700736 if self._debug:
737 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700738 if executor is None:
739 executor = self._default_executor
740 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400741 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700742 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500743 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500744 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700745
746 def set_default_executor(self, executor):
747 self._default_executor = executor
748
Victor Stinnere912e652014-07-12 03:11:53 +0200749 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500750 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200751 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500752 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200753 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500754 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200755 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500756 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200757 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500758 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200759 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200760 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200761
762 t0 = self.time()
763 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
764 dt = self.time() - t0
765
Yury Selivanov6370f342017-12-10 18:36:12 -0500766 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200767 if dt >= self.slow_callback_duration:
768 logger.info(msg)
769 else:
770 logger.debug(msg)
771 return addrinfo
772
Yury Selivanov19a44f62017-12-14 20:53:26 -0500773 async def getaddrinfo(self, host, port, *,
774 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400775 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500776 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200777 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500778 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700779
Yury Selivanov19a44f62017-12-14 20:53:26 -0500780 return await self.run_in_executor(
781 None, getaddr_func, host, port, family, type, proto, flags)
782
783 async def getnameinfo(self, sockaddr, flags=0):
784 return await self.run_in_executor(
785 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700786
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200787 async def sock_sendfile(self, sock, file, offset=0, count=None,
788 *, fallback=True):
789 if self._debug and sock.gettimeout() != 0:
790 raise ValueError("the socket must be non-blocking")
791 self._check_sendfile_params(sock, file, offset, count)
792 try:
793 return await self._sock_sendfile_native(sock, file,
794 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200795 except events.SendfileNotAvailableError as exc:
796 if not fallback:
797 raise
798 return await self._sock_sendfile_fallback(sock, file,
799 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200800
801 async def _sock_sendfile_native(self, sock, file, offset, count):
802 # NB: sendfile syscall is not supported for SSL sockets and
803 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200804 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200805 f"syscall sendfile is not available for socket {sock!r} "
806 "and file {file!r} combination")
807
808 async def _sock_sendfile_fallback(self, sock, file, offset, count):
809 if offset:
810 file.seek(offset)
Miss Islington (bot)420092e2018-05-28 18:42:45 -0700811 blocksize = (
812 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
813 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
814 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200815 buf = bytearray(blocksize)
816 total_sent = 0
817 try:
818 while True:
819 if count:
820 blocksize = min(count - total_sent, blocksize)
821 if blocksize <= 0:
822 break
823 view = memoryview(buf)[:blocksize]
Miss Islington (bot)420092e2018-05-28 18:42:45 -0700824 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200825 if not read:
826 break # EOF
827 await self.sock_sendall(sock, view)
828 total_sent += read
829 return total_sent
830 finally:
831 if total_sent > 0 and hasattr(file, 'seek'):
832 file.seek(offset + total_sent)
833
834 def _check_sendfile_params(self, sock, file, offset, count):
835 if 'b' not in getattr(file, 'mode', 'b'):
836 raise ValueError("file should be opened in binary mode")
837 if not sock.type == socket.SOCK_STREAM:
838 raise ValueError("only SOCK_STREAM type sockets are supported")
839 if count is not None:
840 if not isinstance(count, int):
841 raise TypeError(
842 "count must be a positive integer (got {!r})".format(count))
843 if count <= 0:
844 raise ValueError(
845 "count must be a positive integer (got {!r})".format(count))
846 if not isinstance(offset, int):
847 raise TypeError(
848 "offset must be a non-negative integer (got {!r})".format(
849 offset))
850 if offset < 0:
851 raise ValueError(
852 "offset must be a non-negative integer (got {!r})".format(
853 offset))
854
Neil Aspinallf7686c12017-12-19 19:45:42 +0000855 async def create_connection(
856 self, protocol_factory, host=None, port=None,
857 *, ssl=None, family=0,
858 proto=0, flags=0, sock=None,
859 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200860 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200861 """Connect to a TCP server.
862
863 Create a streaming transport connection to a given Internet host and
864 port: socket family AF_INET or socket.AF_INET6 depending on host (or
865 family if specified), socket type SOCK_STREAM. protocol_factory must be
866 a callable returning a protocol instance.
867
868 This method is a coroutine which will try to establish the connection
869 in the background. When successful, the coroutine returns a
870 (transport, protocol) pair.
871 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700872 if server_hostname is not None and not ssl:
873 raise ValueError('server_hostname is only meaningful with ssl')
874
875 if server_hostname is None and ssl:
876 # Use host as default for server_hostname. It is an error
877 # if host is empty or not set, e.g. when an
878 # already-connected socket was passed or when only a port
879 # is given. To avoid this error, you can pass
880 # server_hostname='' -- this will bypass the hostname
881 # check. (This also means that if host is a numeric
882 # IP/IPv6 address, we will attempt to verify that exact
883 # address; this will probably fail, but it is possible to
884 # create a certificate for a specific IP address, so we
885 # don't judge it here.)
886 if not host:
887 raise ValueError('You must set server_hostname '
888 'when using ssl without a host')
889 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700890
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200891 if ssl_handshake_timeout is not None and not ssl:
892 raise ValueError(
893 'ssl_handshake_timeout is only meaningful with ssl')
894
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700895 if host is not None or port is not None:
896 if sock is not None:
897 raise ValueError(
898 'host/port and sock can not be specified at the same time')
899
Yury Selivanov19a44f62017-12-14 20:53:26 -0500900 infos = await self._ensure_resolved(
901 (host, port), family=family,
902 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700903 if not infos:
904 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500905
906 if local_addr is not None:
907 laddr_infos = await self._ensure_resolved(
908 local_addr, family=family,
909 type=socket.SOCK_STREAM, proto=proto,
910 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700911 if not laddr_infos:
912 raise OSError('getaddrinfo() returned empty list')
913
914 exceptions = []
915 for family, type, proto, cname, address in infos:
916 try:
917 sock = socket.socket(family=family, type=type, proto=proto)
918 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500919 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700920 for _, _, _, _, laddr in laddr_infos:
921 try:
922 sock.bind(laddr)
923 break
924 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500925 msg = (
926 f'error while attempting to bind on '
927 f'address {laddr!r}: '
928 f'{exc.strerror.lower()}'
929 )
930 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700931 exceptions.append(exc)
932 else:
933 sock.close()
934 sock = None
935 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200936 if self._debug:
937 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200938 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700939 except OSError as exc:
940 if sock is not None:
941 sock.close()
942 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200943 except:
944 if sock is not None:
945 sock.close()
946 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700947 else:
948 break
949 else:
950 if len(exceptions) == 1:
951 raise exceptions[0]
952 else:
953 # If they all have the same str(), raise one.
954 model = str(exceptions[0])
955 if all(str(exc) == model for exc in exceptions):
956 raise exceptions[0]
957 # Raise a combined exception so the user can see all
958 # the various error messages.
959 raise OSError('Multiple exceptions: {}'.format(
960 ', '.join(str(exc) for exc in exceptions)))
961
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500962 else:
963 if sock is None:
964 raise ValueError(
965 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500966 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500967 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
968 # are SOCK_STREAM.
969 # We support passing AF_UNIX sockets even though we have
970 # a dedicated API for that: create_unix_connection.
971 # Disallowing AF_UNIX in this method, breaks backwards
972 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500973 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500974 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700975
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200976 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000977 sock, protocol_factory, ssl, server_hostname,
978 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200979 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200980 # Get the socket from the transport because SSL transport closes
981 # the old socket and creates a new SSL socket
982 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200983 logger.debug("%r connected to %s:%r: (%r, %r)",
984 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500985 return transport, protocol
986
Neil Aspinallf7686c12017-12-19 19:45:42 +0000987 async def _create_connection_transport(
988 self, sock, protocol_factory, ssl,
989 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200990 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400991
992 sock.setblocking(False)
993
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700994 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400995 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700996 if ssl:
997 sslcontext = None if isinstance(ssl, bool) else ssl
998 transport = self._make_ssl_transport(
999 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001000 server_side=server_side, server_hostname=server_hostname,
1001 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001002 else:
1003 transport = self._make_socket_transport(sock, protocol, waiter)
1004
Victor Stinner29ad0112015-01-15 00:04:21 +01001005 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001006 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001007 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001008 transport.close()
1009 raise
1010
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001011 return transport, protocol
1012
Andrew Svetlov7c684072018-01-27 21:22:47 +02001013 async def sendfile(self, transport, file, offset=0, count=None,
1014 *, fallback=True):
1015 """Send a file to transport.
1016
1017 Return the total number of bytes which were sent.
1018
1019 The method uses high-performance os.sendfile if available.
1020
1021 file must be a regular file object opened in binary mode.
1022
1023 offset tells from where to start reading the file. If specified,
1024 count is the total number of bytes to transmit as opposed to
1025 sending the file until EOF is reached. File position is updated on
1026 return or also in case of error in which case file.tell()
1027 can be used to figure out the number of bytes
1028 which were sent.
1029
1030 fallback set to True makes asyncio to manually read and send
1031 the file when the platform does not support the sendfile syscall
1032 (e.g. Windows or SSL socket on Unix).
1033
1034 Raise SendfileNotAvailableError if the system does not support
1035 sendfile syscall and fallback is False.
1036 """
1037 if transport.is_closing():
1038 raise RuntimeError("Transport is closing")
1039 mode = getattr(transport, '_sendfile_compatible',
1040 constants._SendfileMode.UNSUPPORTED)
1041 if mode is constants._SendfileMode.UNSUPPORTED:
1042 raise RuntimeError(
1043 f"sendfile is not supported for transport {transport!r}")
1044 if mode is constants._SendfileMode.TRY_NATIVE:
1045 try:
1046 return await self._sendfile_native(transport, file,
1047 offset, count)
1048 except events.SendfileNotAvailableError as exc:
1049 if not fallback:
1050 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001051
1052 if not fallback:
1053 raise RuntimeError(
1054 f"fallback is disabled and native sendfile is not "
1055 f"supported for transport {transport!r}")
1056
Andrew Svetlov7c684072018-01-27 21:22:47 +02001057 return await self._sendfile_fallback(transport, file,
1058 offset, count)
1059
1060 async def _sendfile_native(self, transp, file, offset, count):
1061 raise events.SendfileNotAvailableError(
1062 "sendfile syscall is not supported")
1063
1064 async def _sendfile_fallback(self, transp, file, offset, count):
1065 if offset:
1066 file.seek(offset)
1067 blocksize = min(count, 16384) if count else 16384
1068 buf = bytearray(blocksize)
1069 total_sent = 0
1070 proto = _SendfileFallbackProtocol(transp)
1071 try:
1072 while True:
1073 if count:
1074 blocksize = min(count - total_sent, blocksize)
1075 if blocksize <= 0:
1076 return total_sent
1077 view = memoryview(buf)[:blocksize]
1078 read = file.readinto(view)
1079 if not read:
1080 return total_sent # EOF
1081 await proto.drain()
1082 transp.write(view)
1083 total_sent += read
1084 finally:
1085 if total_sent > 0 and hasattr(file, 'seek'):
1086 file.seek(offset + total_sent)
1087 await proto.restore()
1088
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001089 async def start_tls(self, transport, protocol, sslcontext, *,
1090 server_side=False,
1091 server_hostname=None,
1092 ssl_handshake_timeout=None):
1093 """Upgrade transport to TLS.
1094
1095 Return a new transport that *protocol* should start using
1096 immediately.
1097 """
1098 if ssl is None:
1099 raise RuntimeError('Python ssl module is not available')
1100
1101 if not isinstance(sslcontext, ssl.SSLContext):
1102 raise TypeError(
1103 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1104 f'got {sslcontext!r}')
1105
1106 if not getattr(transport, '_start_tls_compatible', False):
1107 raise TypeError(
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001108 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001109
1110 waiter = self.create_future()
1111 ssl_protocol = sslproto.SSLProtocol(
1112 self, protocol, sslcontext, waiter,
1113 server_side, server_hostname,
1114 ssl_handshake_timeout=ssl_handshake_timeout,
1115 call_connection_made=False)
1116
Miss Islington (bot)eca08592018-05-28 22:59:03 -07001117 # Pause early so that "ssl_protocol.data_received()" doesn't
1118 # have a chance to get called before "ssl_protocol.connection_made()".
1119 transport.pause_reading()
1120
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001121 transport.set_protocol(ssl_protocol)
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001122 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1123 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001124
Miss Islington (bot)87936d02018-06-04 09:05:46 -07001125 try:
1126 await waiter
1127 except Exception:
1128 transport.close()
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001129 conmade_cb.cancel()
1130 resume_cb.cancel()
Miss Islington (bot)87936d02018-06-04 09:05:46 -07001131 raise
1132
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001133 return ssl_protocol._app_transport
1134
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001135 async def create_datagram_endpoint(self, protocol_factory,
1136 local_addr=None, remote_addr=None, *,
1137 family=0, proto=0, flags=0,
1138 reuse_address=None, reuse_port=None,
1139 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001140 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001141 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001142 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001143 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001144 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001145 if (local_addr or remote_addr or
1146 family or proto or flags or
1147 reuse_address or reuse_port or allow_broadcast):
1148 # show the problematic kwargs in exception msg
1149 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1150 family=family, proto=proto, flags=flags,
1151 reuse_address=reuse_address, reuse_port=reuse_port,
1152 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001153 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001154 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001155 f'socket modifier keyword arguments can not be used '
1156 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001157 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001158 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001159 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001160 if not (local_addr or remote_addr):
1161 if family == 0:
1162 raise ValueError('unexpected address family')
1163 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001164 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1165 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001166 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001167 raise TypeError('string is expected')
1168 addr_pairs_info = (((family, proto),
1169 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001170 else:
1171 # join address by (family, protocol)
1172 addr_infos = collections.OrderedDict()
1173 for idx, addr in ((0, local_addr), (1, remote_addr)):
1174 if addr is not None:
1175 assert isinstance(addr, tuple) and len(addr) == 2, (
1176 '2-tuple is expected')
1177
Yury Selivanov19a44f62017-12-14 20:53:26 -05001178 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001179 addr, family=family, type=socket.SOCK_DGRAM,
1180 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001181 if not infos:
1182 raise OSError('getaddrinfo() returned empty list')
1183
1184 for fam, _, pro, _, address in infos:
1185 key = (fam, pro)
1186 if key not in addr_infos:
1187 addr_infos[key] = [None, None]
1188 addr_infos[key][idx] = address
1189
1190 # each addr has to have info for each (family, proto) pair
1191 addr_pairs_info = [
1192 (key, addr_pair) for key, addr_pair in addr_infos.items()
1193 if not ((local_addr and addr_pair[0] is None) or
1194 (remote_addr and addr_pair[1] is None))]
1195
1196 if not addr_pairs_info:
1197 raise ValueError('can not get address information')
1198
1199 exceptions = []
1200
1201 if reuse_address is None:
1202 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1203
1204 for ((family, proto),
1205 (local_address, remote_address)) in addr_pairs_info:
1206 sock = None
1207 r_addr = None
1208 try:
1209 sock = socket.socket(
1210 family=family, type=socket.SOCK_DGRAM, proto=proto)
1211 if reuse_address:
1212 sock.setsockopt(
1213 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1214 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001215 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001216 if allow_broadcast:
1217 sock.setsockopt(
1218 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1219 sock.setblocking(False)
1220
1221 if local_addr:
1222 sock.bind(local_address)
1223 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001224 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001225 r_addr = remote_address
1226 except OSError as exc:
1227 if sock is not None:
1228 sock.close()
1229 exceptions.append(exc)
1230 except:
1231 if sock is not None:
1232 sock.close()
1233 raise
1234 else:
1235 break
1236 else:
1237 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001238
1239 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001240 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001241 transport = self._make_datagram_transport(
1242 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001243 if self._debug:
1244 if local_addr:
1245 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1246 "created: (%r, %r)",
1247 local_addr, remote_addr, transport, protocol)
1248 else:
1249 logger.debug("Datagram endpoint remote_addr=%r created: "
1250 "(%r, %r)",
1251 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001252
1253 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001254 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001255 except:
1256 transport.close()
1257 raise
1258
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001259 return transport, protocol
1260
Yury Selivanov19a44f62017-12-14 20:53:26 -05001261 async def _ensure_resolved(self, address, *,
1262 family=0, type=socket.SOCK_STREAM,
1263 proto=0, flags=0, loop):
1264 host, port = address[:2]
1265 info = _ipaddr_info(host, port, family, type, proto)
1266 if info is not None:
1267 # "host" is already a resolved IP.
1268 return [info]
1269 else:
1270 return await loop.getaddrinfo(host, port, family=family, type=type,
1271 proto=proto, flags=flags)
1272
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001273 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001274 infos = await self._ensure_resolved((host, port), family=family,
1275 type=socket.SOCK_STREAM,
1276 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001277 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001278 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001279 return infos
1280
Neil Aspinallf7686c12017-12-19 19:45:42 +00001281 async def create_server(
1282 self, protocol_factory, host=None, port=None,
1283 *,
1284 family=socket.AF_UNSPEC,
1285 flags=socket.AI_PASSIVE,
1286 sock=None,
1287 backlog=100,
1288 ssl=None,
1289 reuse_address=None,
1290 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001291 ssl_handshake_timeout=None,
1292 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001293 """Create a TCP server.
1294
Yury Selivanov6370f342017-12-10 18:36:12 -05001295 The host parameter can be a string, in that case the TCP server is
1296 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001297
1298 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001299 the TCP server is bound to all hosts of the sequence. If a host
1300 appears multiple times (possibly indirectly e.g. when hostnames
1301 resolve to the same IP address), the server is only bound once to that
1302 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001303
Victor Stinneracdb7822014-07-14 18:33:40 +02001304 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001305
1306 This method is a coroutine.
1307 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001308 if isinstance(ssl, bool):
1309 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001310
1311 if ssl_handshake_timeout is not None and ssl is None:
1312 raise ValueError(
1313 'ssl_handshake_timeout is only meaningful with ssl')
1314
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001315 if host is not None or port is not None:
1316 if sock is not None:
1317 raise ValueError(
1318 'host/port and sock can not be specified at the same time')
1319
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001320 if reuse_address is None:
1321 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1322 sockets = []
1323 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001324 hosts = [None]
1325 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001326 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001327 hosts = [host]
1328 else:
1329 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001330
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001331 fs = [self._create_server_getaddrinfo(host, port, family=family,
1332 flags=flags)
1333 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001334 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001335 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001336
1337 completed = False
1338 try:
1339 for res in infos:
1340 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001341 try:
1342 sock = socket.socket(af, socktype, proto)
1343 except socket.error:
1344 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001345 if self._debug:
1346 logger.warning('create_server() failed to create '
1347 'socket.socket(%r, %r, %r)',
1348 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001349 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001350 sockets.append(sock)
1351 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001352 sock.setsockopt(
1353 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1354 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001355 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001356 # Disable IPv4/IPv6 dual stack support (enabled by
1357 # default on Linux) which makes a single socket
1358 # listen on both address families.
Miss Islington (bot)3ed44142018-06-28 19:16:48 -07001359 if (_HAS_IPv6 and
1360 af == socket.AF_INET6 and
1361 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001362 sock.setsockopt(socket.IPPROTO_IPV6,
1363 socket.IPV6_V6ONLY,
1364 True)
1365 try:
1366 sock.bind(sa)
1367 except OSError as err:
1368 raise OSError(err.errno, 'error while attempting '
1369 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001370 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001371 completed = True
1372 finally:
1373 if not completed:
1374 for sock in sockets:
1375 sock.close()
1376 else:
1377 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001378 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001379 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001380 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001381 sockets = [sock]
1382
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001383 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001384 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001385
1386 server = Server(self, sockets, protocol_factory,
1387 ssl, backlog, ssl_handshake_timeout)
1388 if start_serving:
1389 server._start_serving()
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -07001390 # Skip one loop iteration so that all 'loop.add_reader'
1391 # go through.
1392 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001393
Victor Stinnere912e652014-07-12 03:11:53 +02001394 if self._debug:
1395 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001396 return server
1397
Neil Aspinallf7686c12017-12-19 19:45:42 +00001398 async def connect_accepted_socket(
1399 self, protocol_factory, sock,
1400 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001401 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001402 """Handle an accepted connection.
1403
1404 This is used by servers that accept connections outside of
1405 asyncio but that use asyncio to handle connections.
1406
1407 This method is a coroutine. When completed, the coroutine
1408 returns a (transport, protocol) pair.
1409 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001410 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001411 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001412
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001413 if ssl_handshake_timeout is not None and not ssl:
1414 raise ValueError(
1415 'ssl_handshake_timeout is only meaningful with ssl')
1416
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001417 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001418 sock, protocol_factory, ssl, '', server_side=True,
1419 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001420 if self._debug:
1421 # Get the socket from the transport because SSL transport closes
1422 # the old socket and creates a new SSL socket
1423 sock = transport.get_extra_info('socket')
1424 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1425 return transport, protocol
1426
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001427 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001428 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001429 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001430 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001431
1432 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001433 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001434 except:
1435 transport.close()
1436 raise
1437
Victor Stinneracdb7822014-07-14 18:33:40 +02001438 if self._debug:
1439 logger.debug('Read pipe %r connected: (%r, %r)',
1440 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001441 return transport, protocol
1442
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001443 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001444 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001445 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001446 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001447
1448 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001449 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001450 except:
1451 transport.close()
1452 raise
1453
Victor Stinneracdb7822014-07-14 18:33:40 +02001454 if self._debug:
1455 logger.debug('Write pipe %r connected: (%r, %r)',
1456 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001457 return transport, protocol
1458
Victor Stinneracdb7822014-07-14 18:33:40 +02001459 def _log_subprocess(self, msg, stdin, stdout, stderr):
1460 info = [msg]
1461 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001462 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001463 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001464 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001465 else:
1466 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001467 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001468 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001469 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001470 logger.debug(' '.join(info))
1471
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001472 async def subprocess_shell(self, protocol_factory, cmd, *,
1473 stdin=subprocess.PIPE,
1474 stdout=subprocess.PIPE,
1475 stderr=subprocess.PIPE,
1476 universal_newlines=False,
1477 shell=True, bufsize=0,
1478 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001479 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001480 raise ValueError("cmd must be a string")
1481 if universal_newlines:
1482 raise ValueError("universal_newlines must be False")
1483 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001484 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001485 if bufsize != 0:
1486 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001487 protocol = protocol_factory()
Miss Islington (bot)21f4c782018-06-08 15:42:07 -07001488 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001489 if self._debug:
1490 # don't log parameters: they may contain sensitive information
1491 # (password) and may be too long
1492 debug_log = 'run shell command %r' % cmd
1493 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001494 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001495 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Miss Islington (bot)21f4c782018-06-08 15:42:07 -07001496 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001497 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001498 return transport, protocol
1499
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001500 async def subprocess_exec(self, protocol_factory, program, *args,
1501 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1502 stderr=subprocess.PIPE, universal_newlines=False,
1503 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001504 if universal_newlines:
1505 raise ValueError("universal_newlines must be False")
1506 if shell:
1507 raise ValueError("shell must be False")
1508 if bufsize != 0:
1509 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001510 popen_args = (program,) + args
1511 for arg in popen_args:
1512 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001513 raise TypeError(
1514 f"program arguments must be a bytes or text string, "
1515 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001516 protocol = protocol_factory()
Miss Islington (bot)21f4c782018-06-08 15:42:07 -07001517 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001518 if self._debug:
1519 # don't log parameters: they may contain sensitive information
1520 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001521 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001522 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001523 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001524 protocol, popen_args, False, stdin, stdout, stderr,
1525 bufsize, **kwargs)
Miss Islington (bot)21f4c782018-06-08 15:42:07 -07001526 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001527 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001528 return transport, protocol
1529
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001530 def get_exception_handler(self):
1531 """Return an exception handler, or None if the default one is in use.
1532 """
1533 return self._exception_handler
1534
Yury Selivanov569efa22014-02-18 18:02:19 -05001535 def set_exception_handler(self, handler):
1536 """Set handler as the new event loop exception handler.
1537
1538 If handler is None, the default exception handler will
1539 be set.
1540
1541 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001542 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001543 will be a reference to the active event loop, 'context'
1544 will be a dict object (see `call_exception_handler()`
1545 documentation for details about context).
1546 """
1547 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001548 raise TypeError(f'A callable object or None is expected, '
1549 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001550 self._exception_handler = handler
1551
1552 def default_exception_handler(self, context):
1553 """Default exception handler.
1554
1555 This is called when an exception occurs and no exception
1556 handler is set, and can be called by a custom exception
1557 handler that wants to defer to the default behavior.
1558
Antoine Pitrou921e9432017-11-07 17:23:29 +01001559 This default handler logs the error message and other
1560 context-dependent information. In debug mode, a truncated
1561 stack trace is also appended showing where the given object
1562 (e.g. a handle or future or task) was created, if any.
1563
Victor Stinneracdb7822014-07-14 18:33:40 +02001564 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001565 `call_exception_handler()`.
1566 """
1567 message = context.get('message')
1568 if not message:
1569 message = 'Unhandled exception in event loop'
1570
1571 exception = context.get('exception')
1572 if exception is not None:
1573 exc_info = (type(exception), exception, exception.__traceback__)
1574 else:
1575 exc_info = False
1576
Yury Selivanov6370f342017-12-10 18:36:12 -05001577 if ('source_traceback' not in context and
1578 self._current_handle is not None and
1579 self._current_handle._source_traceback):
1580 context['handle_traceback'] = \
1581 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001582
Yury Selivanov569efa22014-02-18 18:02:19 -05001583 log_lines = [message]
1584 for key in sorted(context):
1585 if key in {'message', 'exception'}:
1586 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001587 value = context[key]
1588 if key == 'source_traceback':
1589 tb = ''.join(traceback.format_list(value))
1590 value = 'Object created at (most recent call last):\n'
1591 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001592 elif key == 'handle_traceback':
1593 tb = ''.join(traceback.format_list(value))
1594 value = 'Handle created at (most recent call last):\n'
1595 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001596 else:
1597 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001598 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001599
1600 logger.error('\n'.join(log_lines), exc_info=exc_info)
1601
1602 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001603 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001604
Victor Stinneracdb7822014-07-14 18:33:40 +02001605 The context argument is a dict containing the following keys:
1606
Yury Selivanov569efa22014-02-18 18:02:19 -05001607 - 'message': Error message;
1608 - 'exception' (optional): Exception object;
1609 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001610 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001611 - 'handle' (optional): Handle instance;
1612 - 'protocol' (optional): Protocol instance;
1613 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001614 - 'socket' (optional): Socket instance;
1615 - 'asyncgen' (optional): Asynchronous generator that caused
1616 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001617
Victor Stinneracdb7822014-07-14 18:33:40 +02001618 New keys maybe introduced in the future.
1619
1620 Note: do not overload this method in an event loop subclass.
1621 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001622 `set_exception_handler()` method.
1623 """
1624 if self._exception_handler is None:
1625 try:
1626 self.default_exception_handler(context)
1627 except Exception:
1628 # Second protection layer for unexpected errors
1629 # in the default implementation, as well as for subclassed
1630 # event loops with overloaded "default_exception_handler".
1631 logger.error('Exception in default exception handler',
1632 exc_info=True)
1633 else:
1634 try:
1635 self._exception_handler(self, context)
1636 except Exception as exc:
1637 # Exception in the user set custom exception handler.
1638 try:
1639 # Let's try default handler.
1640 self.default_exception_handler({
1641 'message': 'Unhandled error in exception handler',
1642 'exception': exc,
1643 'context': context,
1644 })
1645 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001646 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001647 # overloaded.
1648 logger.error('Exception in default exception handler '
1649 'while handling an unexpected error '
1650 'in custom exception handler',
1651 exc_info=True)
1652
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001653 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001654 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001655 assert isinstance(handle, events.Handle), 'A Handle is required here'
1656 if handle._cancelled:
1657 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001658 assert not isinstance(handle, events.TimerHandle)
1659 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001660
1661 def _add_callback_signalsafe(self, handle):
1662 """Like _add_callback() but called from a signal handler."""
1663 self._add_callback(handle)
1664 self._write_to_self()
1665
Yury Selivanov592ada92014-09-25 12:07:56 -04001666 def _timer_handle_cancelled(self, handle):
1667 """Notification that a TimerHandle has been cancelled."""
1668 if handle._scheduled:
1669 self._timer_cancelled_count += 1
1670
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001671 def _run_once(self):
1672 """Run one full iteration of the event loop.
1673
1674 This calls all currently ready callbacks, polls for I/O,
1675 schedules the resulting callbacks, and finally schedules
1676 'call_later' callbacks.
1677 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001678
Yury Selivanov592ada92014-09-25 12:07:56 -04001679 sched_count = len(self._scheduled)
1680 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1681 self._timer_cancelled_count / sched_count >
1682 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001683 # Remove delayed calls that were cancelled if their number
1684 # is too high
1685 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001686 for handle in self._scheduled:
1687 if handle._cancelled:
1688 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001689 else:
1690 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001691
Victor Stinner68da8fc2014-09-30 18:08:36 +02001692 heapq.heapify(new_scheduled)
1693 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001694 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001695 else:
1696 # Remove delayed calls that were cancelled from head of queue.
1697 while self._scheduled and self._scheduled[0]._cancelled:
1698 self._timer_cancelled_count -= 1
1699 handle = heapq.heappop(self._scheduled)
1700 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001701
1702 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001703 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001704 timeout = 0
1705 elif self._scheduled:
1706 # Compute the desired timeout.
1707 when = self._scheduled[0]._when
Miss Islington (bot)172a81e2018-07-31 08:29:07 -07001708 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001709
Victor Stinner770e48d2014-07-11 11:58:33 +02001710 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001711 t0 = self.time()
1712 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001713 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001714 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001715 level = logging.INFO
1716 else:
1717 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001718 nevent = len(event_list)
1719 if timeout is None:
1720 logger.log(level, 'poll took %.3f ms: %s events',
1721 dt * 1e3, nevent)
1722 elif nevent:
1723 logger.log(level,
1724 'poll %.3f ms took %.3f ms: %s events',
1725 timeout * 1e3, dt * 1e3, nevent)
1726 elif dt >= 1.0:
1727 logger.log(level,
1728 'poll %.3f ms took %.3f ms: timeout',
1729 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001730 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001731 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001732 self._process_events(event_list)
1733
1734 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001735 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001736 while self._scheduled:
1737 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001738 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001739 break
1740 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001741 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001742 self._ready.append(handle)
1743
1744 # This is the only place where callbacks are actually *called*.
1745 # All other places just add them to ready.
1746 # Note: We run all currently scheduled callbacks, but not any
1747 # callbacks scheduled by callbacks run this time around --
1748 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001749 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001750 ntodo = len(self._ready)
1751 for i in range(ntodo):
1752 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001753 if handle._cancelled:
1754 continue
1755 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001756 try:
1757 self._current_handle = handle
1758 t0 = self.time()
1759 handle._run()
1760 dt = self.time() - t0
1761 if dt >= self.slow_callback_duration:
1762 logger.warning('Executing %s took %.3f seconds',
1763 _format_handle(handle), dt)
1764 finally:
1765 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001766 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001767 handle._run()
1768 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001769
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001770 def _set_coroutine_origin_tracking(self, enabled):
1771 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001772 return
1773
Yury Selivanove8944cb2015-05-12 11:43:04 -04001774 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001775 self._coroutine_origin_tracking_saved_depth = (
1776 sys.get_coroutine_origin_tracking_depth())
1777 sys.set_coroutine_origin_tracking_depth(
1778 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001779 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001780 sys.set_coroutine_origin_tracking_depth(
1781 self._coroutine_origin_tracking_saved_depth)
1782
1783 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001784
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001785 def get_debug(self):
1786 return self._debug
1787
1788 def set_debug(self, enabled):
1789 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001790
Yury Selivanove8944cb2015-05-12 11:43:04 -04001791 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001792 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)