blob: 75989a7641b8bbfd4e20848ae220dbad00da24e6 [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
Yury Selivanovd904c232018-06-28 21:59:32 -040064_HAS_IPv6 = hasattr(socket, 'AF_INET6')
65
Victor Stinnerc94a93a2016-04-01 21:43:39 +020066
Victor Stinner0e6f52a2014-06-20 17:34:15 +020067def _format_handle(handle):
68 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040069 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020070 # format the task
71 return repr(cb.__self__)
72 else:
73 return str(handle)
74
75
Victor Stinneracdb7822014-07-14 18:33:40 +020076def _format_pipe(fd):
77 if fd == subprocess.PIPE:
78 return '<pipe>'
79 elif fd == subprocess.STDOUT:
80 return '<stdout>'
81 else:
82 return repr(fd)
83
84
Yury Selivanov5587d7c2016-09-15 15:45:07 -040085def _set_reuseport(sock):
86 if not hasattr(socket, 'SO_REUSEPORT'):
87 raise ValueError('reuse_port not supported by socket module')
88 else:
89 try:
90 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
91 except OSError:
92 raise ValueError('reuse_port not supported by socket module, '
93 'SO_REUSEPORT defined but not implemented.')
94
95
Yury Selivanovd5c2a622015-12-16 19:31:17 -050096def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040097 # Try to skip getaddrinfo if "host" is already an IP. Users might have
98 # handled name resolution in their own code and pass in resolved IPs.
99 if not hasattr(socket, 'inet_pton'):
100 return
101
102 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
103 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500104 return None
105
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500106 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500108 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500109 proto = socket.IPPROTO_UDP
110 else:
111 return None
112
Yury Selivanova7146162016-06-02 16:51:07 -0400113 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400114 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700115 elif isinstance(port, bytes) and port == b'':
116 port = 0
117 elif isinstance(port, str) and port == '':
118 port = 0
119 else:
120 # If port's a service name like "http", don't skip getaddrinfo.
121 try:
122 port = int(port)
123 except (TypeError, ValueError):
124 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400125
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500127 afs = [socket.AF_INET]
Yury Selivanovd904c232018-06-28 21:59:32 -0400128 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500129 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400130 else:
131 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500132
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400133 if isinstance(host, bytes):
134 host = host.decode('idna')
135 if '%' in host:
136 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
137 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500138 return None
139
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500141 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400142 socket.inet_pton(af, host)
143 # The host has already been resolved.
Yury Selivanovd904c232018-06-28 21:59:32 -0400144 if _HAS_IPv6 and af == socket.AF_INET6:
145 return af, type, proto, '', (host, port, 0, 0)
146 else:
147 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400148 except OSError:
149 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500150
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 # "host" is not an IP address.
152 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500153
154
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100155def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500156 if not fut.cancelled():
157 exc = fut.exception()
158 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
159 # Issue #22429: run_forever() already finished, no need to
160 # stop it.
161 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500162 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100163
164
Andrew Svetlov7c684072018-01-27 21:22:47 +0200165class _SendfileFallbackProtocol(protocols.Protocol):
166 def __init__(self, transp):
167 if not isinstance(transp, transports._FlowControlMixin):
168 raise TypeError("transport should be _FlowControlMixin instance")
169 self._transport = transp
170 self._proto = transp.get_protocol()
171 self._should_resume_reading = transp.is_reading()
172 self._should_resume_writing = transp._protocol_paused
173 transp.pause_reading()
174 transp.set_protocol(self)
175 if self._should_resume_writing:
176 self._write_ready_fut = self._transport._loop.create_future()
177 else:
178 self._write_ready_fut = None
179
180 async def drain(self):
181 if self._transport.is_closing():
182 raise ConnectionError("Connection closed by peer")
183 fut = self._write_ready_fut
184 if fut is None:
185 return
186 await fut
187
188 def connection_made(self, transport):
189 raise RuntimeError("Invalid state: "
190 "connection should have been established already.")
191
192 def connection_lost(self, exc):
193 if self._write_ready_fut is not None:
194 # Never happens if peer disconnects after sending the whole content
195 # Thus disconnection is always an exception from user perspective
196 if exc is None:
197 self._write_ready_fut.set_exception(
198 ConnectionError("Connection is closed by peer"))
199 else:
200 self._write_ready_fut.set_exception(exc)
201 self._proto.connection_lost(exc)
202
203 def pause_writing(self):
204 if self._write_ready_fut is not None:
205 return
206 self._write_ready_fut = self._transport._loop.create_future()
207
208 def resume_writing(self):
209 if self._write_ready_fut is None:
210 return
211 self._write_ready_fut.set_result(False)
212 self._write_ready_fut = None
213
214 def data_received(self, data):
215 raise RuntimeError("Invalid state: reading should be paused")
216
217 def eof_received(self):
218 raise RuntimeError("Invalid state: reading should be paused")
219
220 async def restore(self):
221 self._transport.set_protocol(self._proto)
222 if self._should_resume_reading:
223 self._transport.resume_reading()
224 if self._write_ready_fut is not None:
225 # Cancel the future.
226 # Basically it has no effect because protocol is switched back,
227 # no code should wait for it anymore.
228 self._write_ready_fut.cancel()
229 if self._should_resume_writing:
230 self._proto.resume_writing()
231
232
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700233class Server(events.AbstractServer):
234
Yury Selivanovc9070d02018-01-25 18:08:09 -0500235 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
236 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200237 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500238 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200239 self._active_count = 0
240 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500241 self._protocol_factory = protocol_factory
242 self._backlog = backlog
243 self._ssl_context = ssl_context
244 self._ssl_handshake_timeout = ssl_handshake_timeout
245 self._serving = False
246 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700247
Victor Stinnere912e652014-07-12 03:11:53 +0200248 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500249 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200250
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200251 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500252 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200253 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700254
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200255 def _detach(self):
256 assert self._active_count > 0
257 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500258 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700259 self._wakeup()
260
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700261 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200262 waiters = self._waiters
263 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264 for waiter in waiters:
265 if not waiter.done():
266 waiter.set_result(waiter)
267
Yury Selivanovc9070d02018-01-25 18:08:09 -0500268 def _start_serving(self):
269 if self._serving:
270 return
271 self._serving = True
272 for sock in self._sockets:
273 sock.listen(self._backlog)
274 self._loop._start_serving(
275 self._protocol_factory, sock, self._ssl_context,
276 self, self._backlog, self._ssl_handshake_timeout)
277
278 def get_loop(self):
279 return self._loop
280
281 def is_serving(self):
282 return self._serving
283
284 @property
285 def sockets(self):
286 if self._sockets is None:
287 return []
288 return list(self._sockets)
289
290 def close(self):
291 sockets = self._sockets
292 if sockets is None:
293 return
294 self._sockets = None
295
296 for sock in sockets:
297 self._loop._stop_serving(sock)
298
299 self._serving = False
300
301 if (self._serving_forever_fut is not None and
302 not self._serving_forever_fut.done()):
303 self._serving_forever_fut.cancel()
304 self._serving_forever_fut = None
305
306 if self._active_count == 0:
307 self._wakeup()
308
309 async def start_serving(self):
310 self._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -0400311 # Skip one loop iteration so that all 'loop.add_reader'
312 # go through.
313 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500314
315 async def serve_forever(self):
316 if self._serving_forever_fut is not None:
317 raise RuntimeError(
318 f'server {self!r} is already being awaited on serve_forever()')
319 if self._sockets is None:
320 raise RuntimeError(f'server {self!r} is closed')
321
322 self._start_serving()
323 self._serving_forever_fut = self._loop.create_future()
324
325 try:
326 await self._serving_forever_fut
327 except futures.CancelledError:
328 try:
329 self.close()
330 await self.wait_closed()
331 finally:
332 raise
333 finally:
334 self._serving_forever_fut = None
335
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200336 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500337 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700338 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400339 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200340 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200341 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700342
343
344class BaseEventLoop(events.AbstractEventLoop):
345
346 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400347 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200348 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800349 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700350 self._ready = collections.deque()
351 self._scheduled = []
352 self._default_executor = None
353 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100354 # Identifier of the thread running the event loop, or None if the
355 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100356 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100357 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500358 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800359 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200360 # In debug mode, if the execution of a callback or a step of a task
361 # exceed this duration in seconds, the slow callback/task is logged.
362 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100363 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400364 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800365 self._coroutine_origin_tracking_enabled = False
366 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700367
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500368 # A weak set of all asynchronous generators that are
369 # being iterated by the loop.
370 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700371 # Set to True when `loop.shutdown_asyncgens` is called.
372 self._asyncgens_shutdown_called = False
373
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200374 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500375 return (
376 f'<{self.__class__.__name__} running={self.is_running()} '
377 f'closed={self.is_closed()} debug={self.get_debug()}>'
378 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200379
Yury Selivanov7661db62016-05-16 15:38:39 -0400380 def create_future(self):
381 """Create a Future object attached to the loop."""
382 return futures.Future(loop=self)
383
Victor Stinner896a25a2014-07-08 11:29:25 +0200384 def create_task(self, coro):
385 """Schedule a coroutine object.
386
Victor Stinneracdb7822014-07-14 18:33:40 +0200387 Return a task object.
388 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100389 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400390 if self._task_factory is None:
391 task = tasks.Task(coro, loop=self)
392 if task._source_traceback:
393 del task._source_traceback[-1]
394 else:
395 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200396 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200397
Yury Selivanov740169c2015-05-11 14:23:38 -0400398 def set_task_factory(self, factory):
399 """Set a task factory that will be used by loop.create_task().
400
401 If factory is None the default task factory will be set.
402
403 If factory is a callable, it should have a signature matching
404 '(loop, coro)', where 'loop' will be a reference to the active
405 event loop, 'coro' will be a coroutine object. The callable
406 must return a Future.
407 """
408 if factory is not None and not callable(factory):
409 raise TypeError('task factory must be a callable or None')
410 self._task_factory = factory
411
412 def get_task_factory(self):
413 """Return a task factory, or None if the default one is in use."""
414 return self._task_factory
415
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700416 def _make_socket_transport(self, sock, protocol, waiter=None, *,
417 extra=None, server=None):
418 """Create socket transport."""
419 raise NotImplementedError
420
Neil Aspinallf7686c12017-12-19 19:45:42 +0000421 def _make_ssl_transport(
422 self, rawsock, protocol, sslcontext, waiter=None,
423 *, server_side=False, server_hostname=None,
424 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500425 ssl_handshake_timeout=None,
426 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700427 """Create SSL transport."""
428 raise NotImplementedError
429
430 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200431 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700432 """Create datagram transport."""
433 raise NotImplementedError
434
435 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
436 extra=None):
437 """Create read pipe transport."""
438 raise NotImplementedError
439
440 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
441 extra=None):
442 """Create write pipe transport."""
443 raise NotImplementedError
444
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200445 async def _make_subprocess_transport(self, protocol, args, shell,
446 stdin, stdout, stderr, bufsize,
447 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700448 """Create subprocess transport."""
449 raise NotImplementedError
450
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700451 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200452 """Write a byte to self-pipe, to wake up the event loop.
453
454 This may be called from a different thread.
455
456 The subclass is responsible for implementing the self-pipe.
457 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700458 raise NotImplementedError
459
460 def _process_events(self, event_list):
461 """Process selector events."""
462 raise NotImplementedError
463
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200464 def _check_closed(self):
465 if self._closed:
466 raise RuntimeError('Event loop is closed')
467
Yury Selivanoveb636452016-09-08 22:01:51 -0700468 def _asyncgen_finalizer_hook(self, agen):
469 self._asyncgens.discard(agen)
470 if not self.is_closed():
471 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400472 # Wake up the loop if the finalizer was called from
473 # a different thread.
474 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700475
476 def _asyncgen_firstiter_hook(self, agen):
477 if self._asyncgens_shutdown_called:
478 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500479 f"asynchronous generator {agen!r} was scheduled after "
480 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700481 ResourceWarning, source=self)
482
483 self._asyncgens.add(agen)
484
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200485 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700486 """Shutdown all active asynchronous generators."""
487 self._asyncgens_shutdown_called = True
488
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500489 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400490 # If Python version is <3.6 or we don't have any asynchronous
491 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700492 return
493
494 closing_agens = list(self._asyncgens)
495 self._asyncgens.clear()
496
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200497 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700498 *[ag.aclose() for ag in closing_agens],
499 return_exceptions=True,
500 loop=self)
501
Yury Selivanoveb636452016-09-08 22:01:51 -0700502 for result, agen in zip(results, closing_agens):
503 if isinstance(result, Exception):
504 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500505 'message': f'an error occurred during closing of '
506 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700507 'exception': result,
508 'asyncgen': agen
509 })
510
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700511 def run_forever(self):
512 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200513 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100514 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400515 raise RuntimeError('This event loop is already running')
516 if events._get_running_loop() is not None:
517 raise RuntimeError(
518 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800519 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100520 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500521
522 old_agen_hooks = sys.get_asyncgen_hooks()
523 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
524 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400526 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700527 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800528 self._run_once()
529 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530 break
531 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800532 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100533 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400534 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800535 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500536 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537
538 def run_until_complete(self, future):
539 """Run until the Future is done.
540
541 If the argument is a coroutine, it is wrapped in a Task.
542
Victor Stinneracdb7822014-07-14 18:33:40 +0200543 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544 with the same coroutine twice -- it would wrap it in two
545 different Tasks and that can't be good.
546
547 Return the Future's result, or raise its exception.
548 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200549 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200550
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700551 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400552 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200553 if new_task:
554 # An exception is raised if the future didn't complete, so there
555 # is no need to log the "destroy pending task" message
556 future._log_destroy_pending = False
557
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100558 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200559 try:
560 self.run_forever()
561 except:
562 if new_task and future.done() and not future.cancelled():
563 # The coroutine raised a BaseException. Consume the exception
564 # to not log a warning, the caller doesn't have access to the
565 # local task.
566 future.exception()
567 raise
jimmylai21b3e042017-05-22 22:32:46 -0700568 finally:
569 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700570 if not future.done():
571 raise RuntimeError('Event loop stopped before Future completed.')
572
573 return future.result()
574
575 def stop(self):
576 """Stop running the event loop.
577
Guido van Rossum41f69f42015-11-19 13:28:47 -0800578 Every callback already scheduled will still run. This simply informs
579 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700580 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800581 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700582
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200583 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700584 """Close the event loop.
585
586 This clears the queues and shuts down the executor,
587 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200588
589 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700590 """
Victor Stinner956de692014-12-26 21:07:52 +0100591 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200592 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200593 if self._closed:
594 return
Victor Stinnere912e652014-07-12 03:11:53 +0200595 if self._debug:
596 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400597 self._closed = True
598 self._ready.clear()
599 self._scheduled.clear()
600 executor = self._default_executor
601 if executor is not None:
602 self._default_executor = None
603 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200604
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200605 def is_closed(self):
606 """Returns True if the event loop was closed."""
607 return self._closed
608
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900609 def __del__(self):
610 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500611 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900612 source=self)
613 if not self.is_running():
614 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100615
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700616 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200617 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100618 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700619
620 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200621 """Return the time according to the event loop's clock.
622
623 This is a float expressed in seconds since an epoch, but the
624 epoch, precision, accuracy and drift are unspecified and may
625 differ per event loop.
626 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700627 return time.monotonic()
628
Yury Selivanovf23746a2018-01-22 19:11:18 -0500629 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630 """Arrange for a callback to be called at a given time.
631
632 Return a Handle: an opaque object with a cancel() method that
633 can be used to cancel the call.
634
635 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200636 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637
638 Each callback will be called exactly once. If two callbacks
639 are scheduled for exactly the same time, it undefined which
640 will be called first.
641
642 Any positional arguments after the callback will be passed to
643 the callback when it is called.
644 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500645 timer = self.call_at(self.time() + delay, callback, *args,
646 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200647 if timer._source_traceback:
648 del timer._source_traceback[-1]
649 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700650
Yury Selivanovf23746a2018-01-22 19:11:18 -0500651 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200652 """Like call_later(), but uses an absolute time.
653
654 Absolute time corresponds to the event loop's time() method.
655 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100656 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100657 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100658 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700659 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500660 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200661 if timer._source_traceback:
662 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700663 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400664 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665 return timer
666
Yury Selivanovf23746a2018-01-22 19:11:18 -0500667 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700668 """Arrange for a callback to be called as soon as possible.
669
Victor Stinneracdb7822014-07-14 18:33:40 +0200670 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700671 order in which they are registered. Each callback will be
672 called exactly once.
673
674 Any positional arguments after the callback will be passed to
675 the callback when it is called.
676 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700677 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100678 if self._debug:
679 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700680 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500681 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200682 if handle._source_traceback:
683 del handle._source_traceback[-1]
684 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100685
Yury Selivanov491a9122016-11-03 15:09:24 -0700686 def _check_callback(self, callback, method):
687 if (coroutines.iscoroutine(callback) or
688 coroutines.iscoroutinefunction(callback)):
689 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500690 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700691 if not callable(callback):
692 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500693 f'a callable object was expected by {method}(), '
694 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700695
Yury Selivanovf23746a2018-01-22 19:11:18 -0500696 def _call_soon(self, callback, args, context):
697 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200698 if handle._source_traceback:
699 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700700 self._ready.append(handle)
701 return handle
702
Victor Stinner956de692014-12-26 21:07:52 +0100703 def _check_thread(self):
704 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100705
Victor Stinneracdb7822014-07-14 18:33:40 +0200706 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100707 likely behave incorrectly when the assumption is violated.
708
Victor Stinneracdb7822014-07-14 18:33:40 +0200709 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100710 responsible for checking this condition for performance reasons.
711 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100712 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200713 return
Victor Stinner956de692014-12-26 21:07:52 +0100714 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100715 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100716 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200717 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100718 "than the current one")
719
Yury Selivanovf23746a2018-01-22 19:11:18 -0500720 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200721 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700722 self._check_closed()
723 if self._debug:
724 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500725 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200726 if handle._source_traceback:
727 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700728 self._write_to_self()
729 return handle
730
Yury Selivanovbec23722018-01-28 14:09:40 -0500731 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100732 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700733 if self._debug:
734 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700735 if executor is None:
736 executor = self._default_executor
737 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400738 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700739 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500740 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500741 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700742
743 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100744 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
745 warnings.warn(
746 'Using the default executor that is not an instance of '
747 'ThreadPoolExecutor is deprecated and will be prohibited '
748 'in Python 3.9',
749 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700750 self._default_executor = executor
751
Victor Stinnere912e652014-07-12 03:11:53 +0200752 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500753 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200754 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500755 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200756 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500757 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200758 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500759 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200760 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500761 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200762 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200763 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200764
765 t0 = self.time()
766 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
767 dt = self.time() - t0
768
Yury Selivanov6370f342017-12-10 18:36:12 -0500769 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200770 if dt >= self.slow_callback_duration:
771 logger.info(msg)
772 else:
773 logger.debug(msg)
774 return addrinfo
775
Yury Selivanov19a44f62017-12-14 20:53:26 -0500776 async def getaddrinfo(self, host, port, *,
777 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400778 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500779 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200780 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500781 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700782
Yury Selivanov19a44f62017-12-14 20:53:26 -0500783 return await self.run_in_executor(
784 None, getaddr_func, host, port, family, type, proto, flags)
785
786 async def getnameinfo(self, sockaddr, flags=0):
787 return await self.run_in_executor(
788 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700789
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200790 async def sock_sendfile(self, sock, file, offset=0, count=None,
791 *, fallback=True):
792 if self._debug and sock.gettimeout() != 0:
793 raise ValueError("the socket must be non-blocking")
794 self._check_sendfile_params(sock, file, offset, count)
795 try:
796 return await self._sock_sendfile_native(sock, file,
797 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200798 except events.SendfileNotAvailableError as exc:
799 if not fallback:
800 raise
801 return await self._sock_sendfile_fallback(sock, file,
802 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200803
804 async def _sock_sendfile_native(self, sock, file, offset, count):
805 # NB: sendfile syscall is not supported for SSL sockets and
806 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200807 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200808 f"syscall sendfile is not available for socket {sock!r} "
809 "and file {file!r} combination")
810
811 async def _sock_sendfile_fallback(self, sock, file, offset, count):
812 if offset:
813 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400814 blocksize = (
815 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
816 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
817 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200818 buf = bytearray(blocksize)
819 total_sent = 0
820 try:
821 while True:
822 if count:
823 blocksize = min(count - total_sent, blocksize)
824 if blocksize <= 0:
825 break
826 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400827 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200828 if not read:
829 break # EOF
830 await self.sock_sendall(sock, view)
831 total_sent += read
832 return total_sent
833 finally:
834 if total_sent > 0 and hasattr(file, 'seek'):
835 file.seek(offset + total_sent)
836
837 def _check_sendfile_params(self, sock, file, offset, count):
838 if 'b' not in getattr(file, 'mode', 'b'):
839 raise ValueError("file should be opened in binary mode")
840 if not sock.type == socket.SOCK_STREAM:
841 raise ValueError("only SOCK_STREAM type sockets are supported")
842 if count is not None:
843 if not isinstance(count, int):
844 raise TypeError(
845 "count must be a positive integer (got {!r})".format(count))
846 if count <= 0:
847 raise ValueError(
848 "count must be a positive integer (got {!r})".format(count))
849 if not isinstance(offset, int):
850 raise TypeError(
851 "offset must be a non-negative integer (got {!r})".format(
852 offset))
853 if offset < 0:
854 raise ValueError(
855 "offset must be a non-negative integer (got {!r})".format(
856 offset))
857
Neil Aspinallf7686c12017-12-19 19:45:42 +0000858 async def create_connection(
859 self, protocol_factory, host=None, port=None,
860 *, ssl=None, family=0,
861 proto=0, flags=0, sock=None,
862 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200863 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200864 """Connect to a TCP server.
865
866 Create a streaming transport connection to a given Internet host and
867 port: socket family AF_INET or socket.AF_INET6 depending on host (or
868 family if specified), socket type SOCK_STREAM. protocol_factory must be
869 a callable returning a protocol instance.
870
871 This method is a coroutine which will try to establish the connection
872 in the background. When successful, the coroutine returns a
873 (transport, protocol) pair.
874 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700875 if server_hostname is not None and not ssl:
876 raise ValueError('server_hostname is only meaningful with ssl')
877
878 if server_hostname is None and ssl:
879 # Use host as default for server_hostname. It is an error
880 # if host is empty or not set, e.g. when an
881 # already-connected socket was passed or when only a port
882 # is given. To avoid this error, you can pass
883 # server_hostname='' -- this will bypass the hostname
884 # check. (This also means that if host is a numeric
885 # IP/IPv6 address, we will attempt to verify that exact
886 # address; this will probably fail, but it is possible to
887 # create a certificate for a specific IP address, so we
888 # don't judge it here.)
889 if not host:
890 raise ValueError('You must set server_hostname '
891 'when using ssl without a host')
892 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700893
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200894 if ssl_handshake_timeout is not None and not ssl:
895 raise ValueError(
896 'ssl_handshake_timeout is only meaningful with ssl')
897
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700898 if host is not None or port is not None:
899 if sock is not None:
900 raise ValueError(
901 'host/port and sock can not be specified at the same time')
902
Yury Selivanov19a44f62017-12-14 20:53:26 -0500903 infos = await self._ensure_resolved(
904 (host, port), family=family,
905 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700906 if not infos:
907 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500908
909 if local_addr is not None:
910 laddr_infos = await self._ensure_resolved(
911 local_addr, family=family,
912 type=socket.SOCK_STREAM, proto=proto,
913 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700914 if not laddr_infos:
915 raise OSError('getaddrinfo() returned empty list')
916
917 exceptions = []
918 for family, type, proto, cname, address in infos:
919 try:
920 sock = socket.socket(family=family, type=type, proto=proto)
921 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500922 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700923 for _, _, _, _, laddr in laddr_infos:
924 try:
925 sock.bind(laddr)
926 break
927 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500928 msg = (
929 f'error while attempting to bind on '
930 f'address {laddr!r}: '
931 f'{exc.strerror.lower()}'
932 )
933 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700934 exceptions.append(exc)
935 else:
936 sock.close()
937 sock = None
938 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200939 if self._debug:
940 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200941 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700942 except OSError as exc:
943 if sock is not None:
944 sock.close()
945 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200946 except:
947 if sock is not None:
948 sock.close()
949 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700950 else:
951 break
952 else:
953 if len(exceptions) == 1:
954 raise exceptions[0]
955 else:
956 # If they all have the same str(), raise one.
957 model = str(exceptions[0])
958 if all(str(exc) == model for exc in exceptions):
959 raise exceptions[0]
960 # Raise a combined exception so the user can see all
961 # the various error messages.
962 raise OSError('Multiple exceptions: {}'.format(
963 ', '.join(str(exc) for exc in exceptions)))
964
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500965 else:
966 if sock is None:
967 raise ValueError(
968 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500969 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500970 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
971 # are SOCK_STREAM.
972 # We support passing AF_UNIX sockets even though we have
973 # a dedicated API for that: create_unix_connection.
974 # Disallowing AF_UNIX in this method, breaks backwards
975 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500976 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500977 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700978
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200979 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000980 sock, protocol_factory, ssl, server_hostname,
981 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200982 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200983 # Get the socket from the transport because SSL transport closes
984 # the old socket and creates a new SSL socket
985 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200986 logger.debug("%r connected to %s:%r: (%r, %r)",
987 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500988 return transport, protocol
989
Neil Aspinallf7686c12017-12-19 19:45:42 +0000990 async def _create_connection_transport(
991 self, sock, protocol_factory, ssl,
992 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200993 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400994
995 sock.setblocking(False)
996
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700997 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400998 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700999 if ssl:
1000 sslcontext = None if isinstance(ssl, bool) else ssl
1001 transport = self._make_ssl_transport(
1002 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001003 server_side=server_side, server_hostname=server_hostname,
1004 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001005 else:
1006 transport = self._make_socket_transport(sock, protocol, waiter)
1007
Victor Stinner29ad0112015-01-15 00:04:21 +01001008 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001009 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001010 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001011 transport.close()
1012 raise
1013
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001014 return transport, protocol
1015
Andrew Svetlov7c684072018-01-27 21:22:47 +02001016 async def sendfile(self, transport, file, offset=0, count=None,
1017 *, fallback=True):
1018 """Send a file to transport.
1019
1020 Return the total number of bytes which were sent.
1021
1022 The method uses high-performance os.sendfile if available.
1023
1024 file must be a regular file object opened in binary mode.
1025
1026 offset tells from where to start reading the file. If specified,
1027 count is the total number of bytes to transmit as opposed to
1028 sending the file until EOF is reached. File position is updated on
1029 return or also in case of error in which case file.tell()
1030 can be used to figure out the number of bytes
1031 which were sent.
1032
1033 fallback set to True makes asyncio to manually read and send
1034 the file when the platform does not support the sendfile syscall
1035 (e.g. Windows or SSL socket on Unix).
1036
1037 Raise SendfileNotAvailableError if the system does not support
1038 sendfile syscall and fallback is False.
1039 """
1040 if transport.is_closing():
1041 raise RuntimeError("Transport is closing")
1042 mode = getattr(transport, '_sendfile_compatible',
1043 constants._SendfileMode.UNSUPPORTED)
1044 if mode is constants._SendfileMode.UNSUPPORTED:
1045 raise RuntimeError(
1046 f"sendfile is not supported for transport {transport!r}")
1047 if mode is constants._SendfileMode.TRY_NATIVE:
1048 try:
1049 return await self._sendfile_native(transport, file,
1050 offset, count)
1051 except events.SendfileNotAvailableError as exc:
1052 if not fallback:
1053 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001054
1055 if not fallback:
1056 raise RuntimeError(
1057 f"fallback is disabled and native sendfile is not "
1058 f"supported for transport {transport!r}")
1059
Andrew Svetlov7c684072018-01-27 21:22:47 +02001060 return await self._sendfile_fallback(transport, file,
1061 offset, count)
1062
1063 async def _sendfile_native(self, transp, file, offset, count):
1064 raise events.SendfileNotAvailableError(
1065 "sendfile syscall is not supported")
1066
1067 async def _sendfile_fallback(self, transp, file, offset, count):
1068 if offset:
1069 file.seek(offset)
1070 blocksize = min(count, 16384) if count else 16384
1071 buf = bytearray(blocksize)
1072 total_sent = 0
1073 proto = _SendfileFallbackProtocol(transp)
1074 try:
1075 while True:
1076 if count:
1077 blocksize = min(count - total_sent, blocksize)
1078 if blocksize <= 0:
1079 return total_sent
1080 view = memoryview(buf)[:blocksize]
1081 read = file.readinto(view)
1082 if not read:
1083 return total_sent # EOF
1084 await proto.drain()
1085 transp.write(view)
1086 total_sent += read
1087 finally:
1088 if total_sent > 0 and hasattr(file, 'seek'):
1089 file.seek(offset + total_sent)
1090 await proto.restore()
1091
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001092 async def start_tls(self, transport, protocol, sslcontext, *,
1093 server_side=False,
1094 server_hostname=None,
1095 ssl_handshake_timeout=None):
1096 """Upgrade transport to TLS.
1097
1098 Return a new transport that *protocol* should start using
1099 immediately.
1100 """
1101 if ssl is None:
1102 raise RuntimeError('Python ssl module is not available')
1103
1104 if not isinstance(sslcontext, ssl.SSLContext):
1105 raise TypeError(
1106 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1107 f'got {sslcontext!r}')
1108
1109 if not getattr(transport, '_start_tls_compatible', False):
1110 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001111 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001112
1113 waiter = self.create_future()
1114 ssl_protocol = sslproto.SSLProtocol(
1115 self, protocol, sslcontext, waiter,
1116 server_side, server_hostname,
1117 ssl_handshake_timeout=ssl_handshake_timeout,
1118 call_connection_made=False)
1119
Yury Selivanovf2955872018-05-29 01:00:12 -04001120 # Pause early so that "ssl_protocol.data_received()" doesn't
1121 # have a chance to get called before "ssl_protocol.connection_made()".
1122 transport.pause_reading()
1123
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001124 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001125 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1126 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001127
Yury Selivanov96026432018-06-04 11:32:35 -04001128 try:
1129 await waiter
1130 except Exception:
1131 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001132 conmade_cb.cancel()
1133 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001134 raise
1135
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001136 return ssl_protocol._app_transport
1137
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001138 async def create_datagram_endpoint(self, protocol_factory,
1139 local_addr=None, remote_addr=None, *,
1140 family=0, proto=0, flags=0,
1141 reuse_address=None, reuse_port=None,
1142 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001143 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001144 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001145 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001146 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001147 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001148 if (local_addr or remote_addr or
1149 family or proto or flags or
1150 reuse_address or reuse_port or allow_broadcast):
1151 # show the problematic kwargs in exception msg
1152 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1153 family=family, proto=proto, flags=flags,
1154 reuse_address=reuse_address, reuse_port=reuse_port,
1155 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001156 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001157 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001158 f'socket modifier keyword arguments can not be used '
1159 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001160 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001161 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001162 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001163 if not (local_addr or remote_addr):
1164 if family == 0:
1165 raise ValueError('unexpected address family')
1166 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001167 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1168 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001169 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001170 raise TypeError('string is expected')
1171 addr_pairs_info = (((family, proto),
1172 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001173 else:
1174 # join address by (family, protocol)
1175 addr_infos = collections.OrderedDict()
1176 for idx, addr in ((0, local_addr), (1, remote_addr)):
1177 if addr is not None:
1178 assert isinstance(addr, tuple) and len(addr) == 2, (
1179 '2-tuple is expected')
1180
Yury Selivanov19a44f62017-12-14 20:53:26 -05001181 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001182 addr, family=family, type=socket.SOCK_DGRAM,
1183 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001184 if not infos:
1185 raise OSError('getaddrinfo() returned empty list')
1186
1187 for fam, _, pro, _, address in infos:
1188 key = (fam, pro)
1189 if key not in addr_infos:
1190 addr_infos[key] = [None, None]
1191 addr_infos[key][idx] = address
1192
1193 # each addr has to have info for each (family, proto) pair
1194 addr_pairs_info = [
1195 (key, addr_pair) for key, addr_pair in addr_infos.items()
1196 if not ((local_addr and addr_pair[0] is None) or
1197 (remote_addr and addr_pair[1] is None))]
1198
1199 if not addr_pairs_info:
1200 raise ValueError('can not get address information')
1201
1202 exceptions = []
1203
1204 if reuse_address is None:
1205 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1206
1207 for ((family, proto),
1208 (local_address, remote_address)) in addr_pairs_info:
1209 sock = None
1210 r_addr = None
1211 try:
1212 sock = socket.socket(
1213 family=family, type=socket.SOCK_DGRAM, proto=proto)
1214 if reuse_address:
1215 sock.setsockopt(
1216 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1217 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001218 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001219 if allow_broadcast:
1220 sock.setsockopt(
1221 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1222 sock.setblocking(False)
1223
1224 if local_addr:
1225 sock.bind(local_address)
1226 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001227 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001228 r_addr = remote_address
1229 except OSError as exc:
1230 if sock is not None:
1231 sock.close()
1232 exceptions.append(exc)
1233 except:
1234 if sock is not None:
1235 sock.close()
1236 raise
1237 else:
1238 break
1239 else:
1240 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001241
1242 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001243 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001244 transport = self._make_datagram_transport(
1245 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001246 if self._debug:
1247 if local_addr:
1248 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1249 "created: (%r, %r)",
1250 local_addr, remote_addr, transport, protocol)
1251 else:
1252 logger.debug("Datagram endpoint remote_addr=%r created: "
1253 "(%r, %r)",
1254 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001255
1256 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001257 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001258 except:
1259 transport.close()
1260 raise
1261
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001262 return transport, protocol
1263
Yury Selivanov19a44f62017-12-14 20:53:26 -05001264 async def _ensure_resolved(self, address, *,
1265 family=0, type=socket.SOCK_STREAM,
1266 proto=0, flags=0, loop):
1267 host, port = address[:2]
1268 info = _ipaddr_info(host, port, family, type, proto)
1269 if info is not None:
1270 # "host" is already a resolved IP.
1271 return [info]
1272 else:
1273 return await loop.getaddrinfo(host, port, family=family, type=type,
1274 proto=proto, flags=flags)
1275
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001276 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001277 infos = await self._ensure_resolved((host, port), family=family,
1278 type=socket.SOCK_STREAM,
1279 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001280 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001281 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001282 return infos
1283
Neil Aspinallf7686c12017-12-19 19:45:42 +00001284 async def create_server(
1285 self, protocol_factory, host=None, port=None,
1286 *,
1287 family=socket.AF_UNSPEC,
1288 flags=socket.AI_PASSIVE,
1289 sock=None,
1290 backlog=100,
1291 ssl=None,
1292 reuse_address=None,
1293 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001294 ssl_handshake_timeout=None,
1295 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001296 """Create a TCP server.
1297
Yury Selivanov6370f342017-12-10 18:36:12 -05001298 The host parameter can be a string, in that case the TCP server is
1299 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001300
1301 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001302 the TCP server is bound to all hosts of the sequence. If a host
1303 appears multiple times (possibly indirectly e.g. when hostnames
1304 resolve to the same IP address), the server is only bound once to that
1305 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001306
Victor Stinneracdb7822014-07-14 18:33:40 +02001307 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001308
1309 This method is a coroutine.
1310 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001311 if isinstance(ssl, bool):
1312 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001313
1314 if ssl_handshake_timeout is not None and ssl is None:
1315 raise ValueError(
1316 'ssl_handshake_timeout is only meaningful with ssl')
1317
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001318 if host is not None or port is not None:
1319 if sock is not None:
1320 raise ValueError(
1321 'host/port and sock can not be specified at the same time')
1322
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323 if reuse_address is None:
1324 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1325 sockets = []
1326 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001327 hosts = [None]
1328 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001329 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001330 hosts = [host]
1331 else:
1332 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001333
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001334 fs = [self._create_server_getaddrinfo(host, port, family=family,
1335 flags=flags)
1336 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001337 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001338 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001339
1340 completed = False
1341 try:
1342 for res in infos:
1343 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001344 try:
1345 sock = socket.socket(af, socktype, proto)
1346 except socket.error:
1347 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001348 if self._debug:
1349 logger.warning('create_server() failed to create '
1350 'socket.socket(%r, %r, %r)',
1351 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001352 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001353 sockets.append(sock)
1354 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001355 sock.setsockopt(
1356 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1357 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001358 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001359 # Disable IPv4/IPv6 dual stack support (enabled by
1360 # default on Linux) which makes a single socket
1361 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001362 if (_HAS_IPv6 and
1363 af == socket.AF_INET6 and
1364 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001365 sock.setsockopt(socket.IPPROTO_IPV6,
1366 socket.IPV6_V6ONLY,
1367 True)
1368 try:
1369 sock.bind(sa)
1370 except OSError as err:
1371 raise OSError(err.errno, 'error while attempting '
1372 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001373 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001374 completed = True
1375 finally:
1376 if not completed:
1377 for sock in sockets:
1378 sock.close()
1379 else:
1380 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001381 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001382 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001383 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001384 sockets = [sock]
1385
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001386 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001387 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001388
1389 server = Server(self, sockets, protocol_factory,
1390 ssl, backlog, ssl_handshake_timeout)
1391 if start_serving:
1392 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001393 # Skip one loop iteration so that all 'loop.add_reader'
1394 # go through.
1395 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001396
Victor Stinnere912e652014-07-12 03:11:53 +02001397 if self._debug:
1398 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001399 return server
1400
Neil Aspinallf7686c12017-12-19 19:45:42 +00001401 async def connect_accepted_socket(
1402 self, protocol_factory, sock,
1403 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001404 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001405 """Handle an accepted connection.
1406
1407 This is used by servers that accept connections outside of
1408 asyncio but that use asyncio to handle connections.
1409
1410 This method is a coroutine. When completed, the coroutine
1411 returns a (transport, protocol) pair.
1412 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001413 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001414 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001415
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001416 if ssl_handshake_timeout is not None and not ssl:
1417 raise ValueError(
1418 'ssl_handshake_timeout is only meaningful with ssl')
1419
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001420 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001421 sock, protocol_factory, ssl, '', server_side=True,
1422 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001423 if self._debug:
1424 # Get the socket from the transport because SSL transport closes
1425 # the old socket and creates a new SSL socket
1426 sock = transport.get_extra_info('socket')
1427 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1428 return transport, protocol
1429
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001430 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001431 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001432 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001433 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001434
1435 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001436 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001437 except:
1438 transport.close()
1439 raise
1440
Victor Stinneracdb7822014-07-14 18:33:40 +02001441 if self._debug:
1442 logger.debug('Read pipe %r connected: (%r, %r)',
1443 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001444 return transport, protocol
1445
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001446 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001447 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001448 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001449 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001450
1451 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001452 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001453 except:
1454 transport.close()
1455 raise
1456
Victor Stinneracdb7822014-07-14 18:33:40 +02001457 if self._debug:
1458 logger.debug('Write pipe %r connected: (%r, %r)',
1459 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001460 return transport, protocol
1461
Victor Stinneracdb7822014-07-14 18:33:40 +02001462 def _log_subprocess(self, msg, stdin, stdout, stderr):
1463 info = [msg]
1464 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001465 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001466 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001467 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001468 else:
1469 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001470 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001471 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001472 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001473 logger.debug(' '.join(info))
1474
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001475 async def subprocess_shell(self, protocol_factory, cmd, *,
1476 stdin=subprocess.PIPE,
1477 stdout=subprocess.PIPE,
1478 stderr=subprocess.PIPE,
1479 universal_newlines=False,
1480 shell=True, bufsize=0,
1481 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001482 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001483 raise ValueError("cmd must be a string")
1484 if universal_newlines:
1485 raise ValueError("universal_newlines must be False")
1486 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001487 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001488 if bufsize != 0:
1489 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001490 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001491 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001492 if self._debug:
1493 # don't log parameters: they may contain sensitive information
1494 # (password) and may be too long
1495 debug_log = 'run shell command %r' % cmd
1496 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001497 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001498 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001499 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001500 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001501 return transport, protocol
1502
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001503 async def subprocess_exec(self, protocol_factory, program, *args,
1504 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1505 stderr=subprocess.PIPE, universal_newlines=False,
1506 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001507 if universal_newlines:
1508 raise ValueError("universal_newlines must be False")
1509 if shell:
1510 raise ValueError("shell must be False")
1511 if bufsize != 0:
1512 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001513 popen_args = (program,) + args
1514 for arg in popen_args:
1515 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001516 raise TypeError(
1517 f"program arguments must be a bytes or text string, "
1518 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001519 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001520 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001521 if self._debug:
1522 # don't log parameters: they may contain sensitive information
1523 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001524 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001525 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001526 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001527 protocol, popen_args, False, stdin, stdout, stderr,
1528 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001529 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001530 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001531 return transport, protocol
1532
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001533 def get_exception_handler(self):
1534 """Return an exception handler, or None if the default one is in use.
1535 """
1536 return self._exception_handler
1537
Yury Selivanov569efa22014-02-18 18:02:19 -05001538 def set_exception_handler(self, handler):
1539 """Set handler as the new event loop exception handler.
1540
1541 If handler is None, the default exception handler will
1542 be set.
1543
1544 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001545 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001546 will be a reference to the active event loop, 'context'
1547 will be a dict object (see `call_exception_handler()`
1548 documentation for details about context).
1549 """
1550 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001551 raise TypeError(f'A callable object or None is expected, '
1552 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001553 self._exception_handler = handler
1554
1555 def default_exception_handler(self, context):
1556 """Default exception handler.
1557
1558 This is called when an exception occurs and no exception
1559 handler is set, and can be called by a custom exception
1560 handler that wants to defer to the default behavior.
1561
Antoine Pitrou921e9432017-11-07 17:23:29 +01001562 This default handler logs the error message and other
1563 context-dependent information. In debug mode, a truncated
1564 stack trace is also appended showing where the given object
1565 (e.g. a handle or future or task) was created, if any.
1566
Victor Stinneracdb7822014-07-14 18:33:40 +02001567 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001568 `call_exception_handler()`.
1569 """
1570 message = context.get('message')
1571 if not message:
1572 message = 'Unhandled exception in event loop'
1573
1574 exception = context.get('exception')
1575 if exception is not None:
1576 exc_info = (type(exception), exception, exception.__traceback__)
1577 else:
1578 exc_info = False
1579
Yury Selivanov6370f342017-12-10 18:36:12 -05001580 if ('source_traceback' not in context and
1581 self._current_handle is not None and
1582 self._current_handle._source_traceback):
1583 context['handle_traceback'] = \
1584 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001585
Yury Selivanov569efa22014-02-18 18:02:19 -05001586 log_lines = [message]
1587 for key in sorted(context):
1588 if key in {'message', 'exception'}:
1589 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001590 value = context[key]
1591 if key == 'source_traceback':
1592 tb = ''.join(traceback.format_list(value))
1593 value = 'Object created at (most recent call last):\n'
1594 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001595 elif key == 'handle_traceback':
1596 tb = ''.join(traceback.format_list(value))
1597 value = 'Handle created at (most recent call last):\n'
1598 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001599 else:
1600 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001601 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001602
1603 logger.error('\n'.join(log_lines), exc_info=exc_info)
1604
1605 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001606 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001607
Victor Stinneracdb7822014-07-14 18:33:40 +02001608 The context argument is a dict containing the following keys:
1609
Yury Selivanov569efa22014-02-18 18:02:19 -05001610 - 'message': Error message;
1611 - 'exception' (optional): Exception object;
1612 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001613 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001614 - 'handle' (optional): Handle instance;
1615 - 'protocol' (optional): Protocol instance;
1616 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001617 - 'socket' (optional): Socket instance;
1618 - 'asyncgen' (optional): Asynchronous generator that caused
1619 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001620
Victor Stinneracdb7822014-07-14 18:33:40 +02001621 New keys maybe introduced in the future.
1622
1623 Note: do not overload this method in an event loop subclass.
1624 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001625 `set_exception_handler()` method.
1626 """
1627 if self._exception_handler is None:
1628 try:
1629 self.default_exception_handler(context)
1630 except Exception:
1631 # Second protection layer for unexpected errors
1632 # in the default implementation, as well as for subclassed
1633 # event loops with overloaded "default_exception_handler".
1634 logger.error('Exception in default exception handler',
1635 exc_info=True)
1636 else:
1637 try:
1638 self._exception_handler(self, context)
1639 except Exception as exc:
1640 # Exception in the user set custom exception handler.
1641 try:
1642 # Let's try default handler.
1643 self.default_exception_handler({
1644 'message': 'Unhandled error in exception handler',
1645 'exception': exc,
1646 'context': context,
1647 })
1648 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001649 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001650 # overloaded.
1651 logger.error('Exception in default exception handler '
1652 'while handling an unexpected error '
1653 'in custom exception handler',
1654 exc_info=True)
1655
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001656 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001657 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001658 assert isinstance(handle, events.Handle), 'A Handle is required here'
1659 if handle._cancelled:
1660 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001661 assert not isinstance(handle, events.TimerHandle)
1662 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001663
1664 def _add_callback_signalsafe(self, handle):
1665 """Like _add_callback() but called from a signal handler."""
1666 self._add_callback(handle)
1667 self._write_to_self()
1668
Yury Selivanov592ada92014-09-25 12:07:56 -04001669 def _timer_handle_cancelled(self, handle):
1670 """Notification that a TimerHandle has been cancelled."""
1671 if handle._scheduled:
1672 self._timer_cancelled_count += 1
1673
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001674 def _run_once(self):
1675 """Run one full iteration of the event loop.
1676
1677 This calls all currently ready callbacks, polls for I/O,
1678 schedules the resulting callbacks, and finally schedules
1679 'call_later' callbacks.
1680 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001681
Yury Selivanov592ada92014-09-25 12:07:56 -04001682 sched_count = len(self._scheduled)
1683 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1684 self._timer_cancelled_count / sched_count >
1685 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001686 # Remove delayed calls that were cancelled if their number
1687 # is too high
1688 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001689 for handle in self._scheduled:
1690 if handle._cancelled:
1691 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001692 else:
1693 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001694
Victor Stinner68da8fc2014-09-30 18:08:36 +02001695 heapq.heapify(new_scheduled)
1696 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001697 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001698 else:
1699 # Remove delayed calls that were cancelled from head of queue.
1700 while self._scheduled and self._scheduled[0]._cancelled:
1701 self._timer_cancelled_count -= 1
1702 handle = heapq.heappop(self._scheduled)
1703 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001704
1705 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001706 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001707 timeout = 0
1708 elif self._scheduled:
1709 # Compute the desired timeout.
1710 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001711 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001712
Victor Stinner770e48d2014-07-11 11:58:33 +02001713 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001714 t0 = self.time()
1715 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001716 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001717 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001718 level = logging.INFO
1719 else:
1720 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001721 nevent = len(event_list)
1722 if timeout is None:
1723 logger.log(level, 'poll took %.3f ms: %s events',
1724 dt * 1e3, nevent)
1725 elif nevent:
1726 logger.log(level,
1727 'poll %.3f ms took %.3f ms: %s events',
1728 timeout * 1e3, dt * 1e3, nevent)
1729 elif dt >= 1.0:
1730 logger.log(level,
1731 'poll %.3f ms took %.3f ms: timeout',
1732 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001733 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001734 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001735 self._process_events(event_list)
1736
1737 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001738 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001739 while self._scheduled:
1740 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001741 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001742 break
1743 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001744 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001745 self._ready.append(handle)
1746
1747 # This is the only place where callbacks are actually *called*.
1748 # All other places just add them to ready.
1749 # Note: We run all currently scheduled callbacks, but not any
1750 # callbacks scheduled by callbacks run this time around --
1751 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001752 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001753 ntodo = len(self._ready)
1754 for i in range(ntodo):
1755 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001756 if handle._cancelled:
1757 continue
1758 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001759 try:
1760 self._current_handle = handle
1761 t0 = self.time()
1762 handle._run()
1763 dt = self.time() - t0
1764 if dt >= self.slow_callback_duration:
1765 logger.warning('Executing %s took %.3f seconds',
1766 _format_handle(handle), dt)
1767 finally:
1768 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001769 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001770 handle._run()
1771 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001772
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001773 def _set_coroutine_origin_tracking(self, enabled):
1774 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001775 return
1776
Yury Selivanove8944cb2015-05-12 11:43:04 -04001777 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001778 self._coroutine_origin_tracking_saved_depth = (
1779 sys.get_coroutine_origin_tracking_depth())
1780 sys.set_coroutine_origin_tracking_depth(
1781 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001782 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001783 sys.set_coroutine_origin_tracking_depth(
1784 self._coroutine_origin_tracking_saved_depth)
1785
1786 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001787
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001788 def get_debug(self):
1789 return self._debug
1790
1791 def set_debug(self, enabled):
1792 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001793
Yury Selivanove8944cb2015-05-12 11:43:04 -04001794 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001795 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)