blob: f5ab6e7b2d21d89be70c311d254a0a5dbd3af613 [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
Victor Stinnerb75380f2014-06-30 14:39:11 +020021import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070022import socket
23import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010024import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020026import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070027import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010028import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070029import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070030
Yury Selivanovf111b3d2017-12-30 00:35:36 -050031try:
32 import ssl
33except ImportError: # pragma: no cover
34 ssl = None
35
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080036from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020037from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070038from . import events
Andrew Svetlov0baa72f2018-09-11 10:13:04 -070039from . import exceptions
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040from . 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
Andrew Svetlov0dd71802018-09-12 14:03:54 -070064if ssl is not None:
65 _FATAL_ERROR_IGNORE = _FATAL_ERROR_IGNORE + (ssl.SSLCertVerificationError,)
66
Yury Selivanovd904c232018-06-28 21:59:32 -040067_HAS_IPv6 = hasattr(socket, 'AF_INET6')
68
MartinAltmayer944451c2018-07-31 15:06:12 +010069# Maximum timeout passed to select to avoid OS limitations
70MAXIMUM_SELECT_TIMEOUT = 24 * 3600
71
Victor Stinnerc94a93a2016-04-01 21:43:39 +020072
Victor Stinner0e6f52a2014-06-20 17:34:15 +020073def _format_handle(handle):
74 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040075 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020076 # format the task
77 return repr(cb.__self__)
78 else:
79 return str(handle)
80
81
Victor Stinneracdb7822014-07-14 18:33:40 +020082def _format_pipe(fd):
83 if fd == subprocess.PIPE:
84 return '<pipe>'
85 elif fd == subprocess.STDOUT:
86 return '<stdout>'
87 else:
88 return repr(fd)
89
90
Yury Selivanov5587d7c2016-09-15 15:45:07 -040091def _set_reuseport(sock):
92 if not hasattr(socket, 'SO_REUSEPORT'):
93 raise ValueError('reuse_port not supported by socket module')
94 else:
95 try:
96 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
97 except OSError:
98 raise ValueError('reuse_port not supported by socket module, '
99 'SO_REUSEPORT defined but not implemented.')
100
101
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500102def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400103 # Try to skip getaddrinfo if "host" is already an IP. Users might have
104 # handled name resolution in their own code and pass in resolved IPs.
105 if not hasattr(socket, 'inet_pton'):
106 return
107
108 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
109 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500110 return None
111
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500112 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500113 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500114 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500115 proto = socket.IPPROTO_UDP
116 else:
117 return None
118
Yury Selivanova7146162016-06-02 16:51:07 -0400119 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400120 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700121 elif isinstance(port, bytes) and port == b'':
122 port = 0
123 elif isinstance(port, str) and port == '':
124 port = 0
125 else:
126 # If port's a service name like "http", don't skip getaddrinfo.
127 try:
128 port = int(port)
129 except (TypeError, ValueError):
130 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400131
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400132 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500133 afs = [socket.AF_INET]
Yury Selivanovd904c232018-06-28 21:59:32 -0400134 if _HAS_IPv6:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500135 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 else:
137 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500138
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400139 if isinstance(host, bytes):
140 host = host.decode('idna')
141 if '%' in host:
142 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
143 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500144 return None
145
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400146 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500147 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400148 socket.inet_pton(af, host)
149 # The host has already been resolved.
Yury Selivanovd904c232018-06-28 21:59:32 -0400150 if _HAS_IPv6 and af == socket.AF_INET6:
151 return af, type, proto, '', (host, port, 0, 0)
152 else:
153 return af, type, proto, '', (host, port)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400154 except OSError:
155 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500156
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400157 # "host" is not an IP address.
158 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500159
160
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100161def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500162 if not fut.cancelled():
163 exc = fut.exception()
164 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
165 # Issue #22429: run_forever() already finished, no need to
166 # stop it.
167 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500168 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100169
170
Andrew Svetlov7c684072018-01-27 21:22:47 +0200171class _SendfileFallbackProtocol(protocols.Protocol):
172 def __init__(self, transp):
173 if not isinstance(transp, transports._FlowControlMixin):
174 raise TypeError("transport should be _FlowControlMixin instance")
175 self._transport = transp
176 self._proto = transp.get_protocol()
177 self._should_resume_reading = transp.is_reading()
178 self._should_resume_writing = transp._protocol_paused
179 transp.pause_reading()
180 transp.set_protocol(self)
181 if self._should_resume_writing:
182 self._write_ready_fut = self._transport._loop.create_future()
183 else:
184 self._write_ready_fut = None
185
186 async def drain(self):
187 if self._transport.is_closing():
188 raise ConnectionError("Connection closed by peer")
189 fut = self._write_ready_fut
190 if fut is None:
191 return
192 await fut
193
194 def connection_made(self, transport):
195 raise RuntimeError("Invalid state: "
196 "connection should have been established already.")
197
198 def connection_lost(self, exc):
199 if self._write_ready_fut is not None:
200 # Never happens if peer disconnects after sending the whole content
201 # Thus disconnection is always an exception from user perspective
202 if exc is None:
203 self._write_ready_fut.set_exception(
204 ConnectionError("Connection is closed by peer"))
205 else:
206 self._write_ready_fut.set_exception(exc)
207 self._proto.connection_lost(exc)
208
209 def pause_writing(self):
210 if self._write_ready_fut is not None:
211 return
212 self._write_ready_fut = self._transport._loop.create_future()
213
214 def resume_writing(self):
215 if self._write_ready_fut is None:
216 return
217 self._write_ready_fut.set_result(False)
218 self._write_ready_fut = None
219
220 def data_received(self, data):
221 raise RuntimeError("Invalid state: reading should be paused")
222
223 def eof_received(self):
224 raise RuntimeError("Invalid state: reading should be paused")
225
226 async def restore(self):
227 self._transport.set_protocol(self._proto)
228 if self._should_resume_reading:
229 self._transport.resume_reading()
230 if self._write_ready_fut is not None:
231 # Cancel the future.
232 # Basically it has no effect because protocol is switched back,
233 # no code should wait for it anymore.
234 self._write_ready_fut.cancel()
235 if self._should_resume_writing:
236 self._proto.resume_writing()
237
238
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700239class Server(events.AbstractServer):
240
Yury Selivanovc9070d02018-01-25 18:08:09 -0500241 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
242 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200243 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500244 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200245 self._active_count = 0
246 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500247 self._protocol_factory = protocol_factory
248 self._backlog = backlog
249 self._ssl_context = ssl_context
250 self._ssl_handshake_timeout = ssl_handshake_timeout
251 self._serving = False
252 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700253
Victor Stinnere912e652014-07-12 03:11:53 +0200254 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500255 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200256
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200257 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500258 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200259 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700260
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200261 def _detach(self):
262 assert self._active_count > 0
263 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500264 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700265 self._wakeup()
266
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700267 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200268 waiters = self._waiters
269 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700270 for waiter in waiters:
271 if not waiter.done():
272 waiter.set_result(waiter)
273
Yury Selivanovc9070d02018-01-25 18:08:09 -0500274 def _start_serving(self):
275 if self._serving:
276 return
277 self._serving = True
278 for sock in self._sockets:
279 sock.listen(self._backlog)
280 self._loop._start_serving(
281 self._protocol_factory, sock, self._ssl_context,
282 self, self._backlog, self._ssl_handshake_timeout)
283
284 def get_loop(self):
285 return self._loop
286
287 def is_serving(self):
288 return self._serving
289
290 @property
291 def sockets(self):
292 if self._sockets is None:
293 return []
294 return list(self._sockets)
295
296 def close(self):
297 sockets = self._sockets
298 if sockets is None:
299 return
300 self._sockets = None
301
302 for sock in sockets:
303 self._loop._stop_serving(sock)
304
305 self._serving = False
306
307 if (self._serving_forever_fut is not None and
308 not self._serving_forever_fut.done()):
309 self._serving_forever_fut.cancel()
310 self._serving_forever_fut = None
311
312 if self._active_count == 0:
313 self._wakeup()
314
315 async def start_serving(self):
316 self._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -0400317 # Skip one loop iteration so that all 'loop.add_reader'
318 # go through.
319 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500320
321 async def serve_forever(self):
322 if self._serving_forever_fut is not None:
323 raise RuntimeError(
324 f'server {self!r} is already being awaited on serve_forever()')
325 if self._sockets is None:
326 raise RuntimeError(f'server {self!r} is closed')
327
328 self._start_serving()
329 self._serving_forever_fut = self._loop.create_future()
330
331 try:
332 await self._serving_forever_fut
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700333 except exceptions.CancelledError:
Yury Selivanovc9070d02018-01-25 18:08:09 -0500334 try:
335 self.close()
336 await self.wait_closed()
337 finally:
338 raise
339 finally:
340 self._serving_forever_fut = None
341
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200342 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500343 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400345 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200346 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200347 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700348
349
350class BaseEventLoop(events.AbstractEventLoop):
351
352 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400353 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200354 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800355 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700356 self._ready = collections.deque()
357 self._scheduled = []
358 self._default_executor = None
359 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100360 # Identifier of the thread running the event loop, or None if the
361 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100362 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100363 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500364 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800365 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200366 # In debug mode, if the execution of a callback or a step of a task
367 # exceed this duration in seconds, the slow callback/task is logged.
368 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100369 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400370 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800371 self._coroutine_origin_tracking_enabled = False
372 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700373
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500374 # A weak set of all asynchronous generators that are
375 # being iterated by the loop.
376 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700377 # Set to True when `loop.shutdown_asyncgens` is called.
378 self._asyncgens_shutdown_called = False
379
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200380 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500381 return (
382 f'<{self.__class__.__name__} running={self.is_running()} '
383 f'closed={self.is_closed()} debug={self.get_debug()}>'
384 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200385
Yury Selivanov7661db62016-05-16 15:38:39 -0400386 def create_future(self):
387 """Create a Future object attached to the loop."""
388 return futures.Future(loop=self)
389
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300390 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200391 """Schedule a coroutine object.
392
Victor Stinneracdb7822014-07-14 18:33:40 +0200393 Return a task object.
394 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100395 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400396 if self._task_factory is None:
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300397 task = tasks.Task(coro, loop=self, name=name)
Yury Selivanov740169c2015-05-11 14:23:38 -0400398 if task._source_traceback:
399 del task._source_traceback[-1]
400 else:
401 task = self._task_factory(self, coro)
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300402 tasks._set_task_name(task, name)
403
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200404 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200405
Yury Selivanov740169c2015-05-11 14:23:38 -0400406 def set_task_factory(self, factory):
407 """Set a task factory that will be used by loop.create_task().
408
409 If factory is None the default task factory will be set.
410
411 If factory is a callable, it should have a signature matching
412 '(loop, coro)', where 'loop' will be a reference to the active
413 event loop, 'coro' will be a coroutine object. The callable
414 must return a Future.
415 """
416 if factory is not None and not callable(factory):
417 raise TypeError('task factory must be a callable or None')
418 self._task_factory = factory
419
420 def get_task_factory(self):
421 """Return a task factory, or None if the default one is in use."""
422 return self._task_factory
423
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700424 def _make_socket_transport(self, sock, protocol, waiter=None, *,
425 extra=None, server=None):
426 """Create socket transport."""
427 raise NotImplementedError
428
Neil Aspinallf7686c12017-12-19 19:45:42 +0000429 def _make_ssl_transport(
430 self, rawsock, protocol, sslcontext, waiter=None,
431 *, server_side=False, server_hostname=None,
432 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500433 ssl_handshake_timeout=None,
434 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700435 """Create SSL transport."""
436 raise NotImplementedError
437
438 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200439 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700440 """Create datagram transport."""
441 raise NotImplementedError
442
443 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
444 extra=None):
445 """Create read pipe transport."""
446 raise NotImplementedError
447
448 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
449 extra=None):
450 """Create write pipe transport."""
451 raise NotImplementedError
452
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200453 async def _make_subprocess_transport(self, protocol, args, shell,
454 stdin, stdout, stderr, bufsize,
455 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700456 """Create subprocess transport."""
457 raise NotImplementedError
458
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200460 """Write a byte to self-pipe, to wake up the event loop.
461
462 This may be called from a different thread.
463
464 The subclass is responsible for implementing the self-pipe.
465 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 raise NotImplementedError
467
468 def _process_events(self, event_list):
469 """Process selector events."""
470 raise NotImplementedError
471
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200472 def _check_closed(self):
473 if self._closed:
474 raise RuntimeError('Event loop is closed')
475
Yury Selivanoveb636452016-09-08 22:01:51 -0700476 def _asyncgen_finalizer_hook(self, agen):
477 self._asyncgens.discard(agen)
478 if not self.is_closed():
twisteroid ambassadorc880ffe2018-10-09 23:30:21 +0800479 self.call_soon_threadsafe(self.create_task, agen.aclose())
Yury Selivanoveb636452016-09-08 22:01:51 -0700480
481 def _asyncgen_firstiter_hook(self, agen):
482 if self._asyncgens_shutdown_called:
483 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500484 f"asynchronous generator {agen!r} was scheduled after "
485 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700486 ResourceWarning, source=self)
487
488 self._asyncgens.add(agen)
489
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200490 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700491 """Shutdown all active asynchronous generators."""
492 self._asyncgens_shutdown_called = True
493
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500494 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400495 # If Python version is <3.6 or we don't have any asynchronous
496 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700497 return
498
499 closing_agens = list(self._asyncgens)
500 self._asyncgens.clear()
501
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200502 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700503 *[ag.aclose() for ag in closing_agens],
504 return_exceptions=True,
505 loop=self)
506
Yury Selivanoveb636452016-09-08 22:01:51 -0700507 for result, agen in zip(results, closing_agens):
508 if isinstance(result, Exception):
509 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500510 'message': f'an error occurred during closing of '
511 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700512 'exception': result,
513 'asyncgen': agen
514 })
515
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516 def run_forever(self):
517 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200518 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100519 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400520 raise RuntimeError('This event loop is already running')
521 if events._get_running_loop() is not None:
522 raise RuntimeError(
523 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800524 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100525 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500526
527 old_agen_hooks = sys.get_asyncgen_hooks()
528 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
529 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400531 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700532 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800533 self._run_once()
534 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535 break
536 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800537 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100538 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400539 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800540 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500541 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700542
543 def run_until_complete(self, future):
544 """Run until the Future is done.
545
546 If the argument is a coroutine, it is wrapped in a Task.
547
Victor Stinneracdb7822014-07-14 18:33:40 +0200548 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 with the same coroutine twice -- it would wrap it in two
550 different Tasks and that can't be good.
551
552 Return the Future's result, or raise its exception.
553 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200554 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200555
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700556 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400557 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200558 if new_task:
559 # An exception is raised if the future didn't complete, so there
560 # is no need to log the "destroy pending task" message
561 future._log_destroy_pending = False
562
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100563 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200564 try:
565 self.run_forever()
566 except:
567 if new_task and future.done() and not future.cancelled():
568 # The coroutine raised a BaseException. Consume the exception
569 # to not log a warning, the caller doesn't have access to the
570 # local task.
571 future.exception()
572 raise
jimmylai21b3e042017-05-22 22:32:46 -0700573 finally:
574 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700575 if not future.done():
576 raise RuntimeError('Event loop stopped before Future completed.')
577
578 return future.result()
579
580 def stop(self):
581 """Stop running the event loop.
582
Guido van Rossum41f69f42015-11-19 13:28:47 -0800583 Every callback already scheduled will still run. This simply informs
584 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800586 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200588 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700589 """Close the event loop.
590
591 This clears the queues and shuts down the executor,
592 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200593
594 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700595 """
Victor Stinner956de692014-12-26 21:07:52 +0100596 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200597 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200598 if self._closed:
599 return
Victor Stinnere912e652014-07-12 03:11:53 +0200600 if self._debug:
601 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400602 self._closed = True
603 self._ready.clear()
604 self._scheduled.clear()
605 executor = self._default_executor
606 if executor is not None:
607 self._default_executor = None
608 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200609
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200610 def is_closed(self):
611 """Returns True if the event loop was closed."""
612 return self._closed
613
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900614 def __del__(self):
615 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500616 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900617 source=self)
618 if not self.is_running():
619 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100620
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200622 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100623 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700624
625 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200626 """Return the time according to the event loop's clock.
627
628 This is a float expressed in seconds since an epoch, but the
629 epoch, precision, accuracy and drift are unspecified and may
630 differ per event loop.
631 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700632 return time.monotonic()
633
Yury Selivanovf23746a2018-01-22 19:11:18 -0500634 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700635 """Arrange for a callback to be called at a given time.
636
637 Return a Handle: an opaque object with a cancel() method that
638 can be used to cancel the call.
639
640 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200641 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700642
643 Each callback will be called exactly once. If two callbacks
644 are scheduled for exactly the same time, it undefined which
645 will be called first.
646
647 Any positional arguments after the callback will be passed to
648 the callback when it is called.
649 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500650 timer = self.call_at(self.time() + delay, callback, *args,
651 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200652 if timer._source_traceback:
653 del timer._source_traceback[-1]
654 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700655
Yury Selivanovf23746a2018-01-22 19:11:18 -0500656 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200657 """Like call_later(), but uses an absolute time.
658
659 Absolute time corresponds to the event loop's time() method.
660 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100661 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100662 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100663 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700664 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500665 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200666 if timer._source_traceback:
667 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700668 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400669 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700670 return timer
671
Yury Selivanovf23746a2018-01-22 19:11:18 -0500672 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700673 """Arrange for a callback to be called as soon as possible.
674
Victor Stinneracdb7822014-07-14 18:33:40 +0200675 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700676 order in which they are registered. Each callback will be
677 called exactly once.
678
679 Any positional arguments after the callback will be passed to
680 the callback when it is called.
681 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700682 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100683 if self._debug:
684 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700685 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500686 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200687 if handle._source_traceback:
688 del handle._source_traceback[-1]
689 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100690
Yury Selivanov491a9122016-11-03 15:09:24 -0700691 def _check_callback(self, callback, method):
692 if (coroutines.iscoroutine(callback) or
693 coroutines.iscoroutinefunction(callback)):
694 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500695 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700696 if not callable(callback):
697 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500698 f'a callable object was expected by {method}(), '
699 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700700
Yury Selivanovf23746a2018-01-22 19:11:18 -0500701 def _call_soon(self, callback, args, context):
702 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200703 if handle._source_traceback:
704 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705 self._ready.append(handle)
706 return handle
707
Victor Stinner956de692014-12-26 21:07:52 +0100708 def _check_thread(self):
709 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100710
Victor Stinneracdb7822014-07-14 18:33:40 +0200711 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100712 likely behave incorrectly when the assumption is violated.
713
Victor Stinneracdb7822014-07-14 18:33:40 +0200714 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100715 responsible for checking this condition for performance reasons.
716 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100717 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200718 return
Victor Stinner956de692014-12-26 21:07:52 +0100719 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100720 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100721 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200722 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100723 "than the current one")
724
Yury Selivanovf23746a2018-01-22 19:11:18 -0500725 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200726 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700727 self._check_closed()
728 if self._debug:
729 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500730 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200731 if handle._source_traceback:
732 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700733 self._write_to_self()
734 return handle
735
Yury Selivanovbec23722018-01-28 14:09:40 -0500736 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100737 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700738 if self._debug:
739 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700740 if executor is None:
741 executor = self._default_executor
742 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400743 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700744 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500745 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500746 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700747
748 def set_default_executor(self, executor):
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100749 if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
750 warnings.warn(
751 'Using the default executor that is not an instance of '
752 'ThreadPoolExecutor is deprecated and will be prohibited '
753 'in Python 3.9',
754 DeprecationWarning, 2)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700755 self._default_executor = executor
756
Victor Stinnere912e652014-07-12 03:11:53 +0200757 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500758 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200759 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500760 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200761 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500762 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200763 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500764 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200765 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500766 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200767 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200768 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200769
770 t0 = self.time()
771 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
772 dt = self.time() - t0
773
Yury Selivanov6370f342017-12-10 18:36:12 -0500774 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200775 if dt >= self.slow_callback_duration:
776 logger.info(msg)
777 else:
778 logger.debug(msg)
779 return addrinfo
780
Yury Selivanov19a44f62017-12-14 20:53:26 -0500781 async def getaddrinfo(self, host, port, *,
782 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400783 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500784 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200785 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500786 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700787
Yury Selivanov19a44f62017-12-14 20:53:26 -0500788 return await self.run_in_executor(
789 None, getaddr_func, host, port, family, type, proto, flags)
790
791 async def getnameinfo(self, sockaddr, flags=0):
792 return await self.run_in_executor(
793 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700794
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200795 async def sock_sendfile(self, sock, file, offset=0, count=None,
796 *, fallback=True):
797 if self._debug and sock.gettimeout() != 0:
798 raise ValueError("the socket must be non-blocking")
799 self._check_sendfile_params(sock, file, offset, count)
800 try:
801 return await self._sock_sendfile_native(sock, file,
802 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700803 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7464e872018-01-19 20:04:29 +0200804 if not fallback:
805 raise
806 return await self._sock_sendfile_fallback(sock, file,
807 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200808
809 async def _sock_sendfile_native(self, sock, file, offset, count):
810 # NB: sendfile syscall is not supported for SSL sockets and
811 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700812 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200813 f"syscall sendfile is not available for socket {sock!r} "
814 "and file {file!r} combination")
815
816 async def _sock_sendfile_fallback(self, sock, file, offset, count):
817 if offset:
818 file.seek(offset)
Yury Selivanov71657542018-05-28 18:31:55 -0400819 blocksize = (
820 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
821 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
822 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200823 buf = bytearray(blocksize)
824 total_sent = 0
825 try:
826 while True:
827 if count:
828 blocksize = min(count - total_sent, blocksize)
829 if blocksize <= 0:
830 break
831 view = memoryview(buf)[:blocksize]
Yury Selivanov71657542018-05-28 18:31:55 -0400832 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200833 if not read:
834 break # EOF
835 await self.sock_sendall(sock, view)
836 total_sent += read
837 return total_sent
838 finally:
839 if total_sent > 0 and hasattr(file, 'seek'):
840 file.seek(offset + total_sent)
841
842 def _check_sendfile_params(self, sock, file, offset, count):
843 if 'b' not in getattr(file, 'mode', 'b'):
844 raise ValueError("file should be opened in binary mode")
845 if not sock.type == socket.SOCK_STREAM:
846 raise ValueError("only SOCK_STREAM type sockets are supported")
847 if count is not None:
848 if not isinstance(count, int):
849 raise TypeError(
850 "count must be a positive integer (got {!r})".format(count))
851 if count <= 0:
852 raise ValueError(
853 "count must be a positive integer (got {!r})".format(count))
854 if not isinstance(offset, int):
855 raise TypeError(
856 "offset must be a non-negative integer (got {!r})".format(
857 offset))
858 if offset < 0:
859 raise ValueError(
860 "offset must be a non-negative integer (got {!r})".format(
861 offset))
862
Neil Aspinallf7686c12017-12-19 19:45:42 +0000863 async def create_connection(
864 self, protocol_factory, host=None, port=None,
865 *, ssl=None, family=0,
866 proto=0, flags=0, sock=None,
867 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200868 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200869 """Connect to a TCP server.
870
871 Create a streaming transport connection to a given Internet host and
872 port: socket family AF_INET or socket.AF_INET6 depending on host (or
873 family if specified), socket type SOCK_STREAM. protocol_factory must be
874 a callable returning a protocol instance.
875
876 This method is a coroutine which will try to establish the connection
877 in the background. When successful, the coroutine returns a
878 (transport, protocol) pair.
879 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700880 if server_hostname is not None and not ssl:
881 raise ValueError('server_hostname is only meaningful with ssl')
882
883 if server_hostname is None and ssl:
884 # Use host as default for server_hostname. It is an error
885 # if host is empty or not set, e.g. when an
886 # already-connected socket was passed or when only a port
887 # is given. To avoid this error, you can pass
888 # server_hostname='' -- this will bypass the hostname
889 # check. (This also means that if host is a numeric
890 # IP/IPv6 address, we will attempt to verify that exact
891 # address; this will probably fail, but it is possible to
892 # create a certificate for a specific IP address, so we
893 # don't judge it here.)
894 if not host:
895 raise ValueError('You must set server_hostname '
896 'when using ssl without a host')
897 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700898
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200899 if ssl_handshake_timeout is not None and not ssl:
900 raise ValueError(
901 'ssl_handshake_timeout is only meaningful with ssl')
902
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700903 if host is not None or port is not None:
904 if sock is not None:
905 raise ValueError(
906 'host/port and sock can not be specified at the same time')
907
Yury Selivanov19a44f62017-12-14 20:53:26 -0500908 infos = await self._ensure_resolved(
909 (host, port), family=family,
910 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700911 if not infos:
912 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500913
914 if local_addr is not None:
915 laddr_infos = await self._ensure_resolved(
916 local_addr, family=family,
917 type=socket.SOCK_STREAM, proto=proto,
918 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700919 if not laddr_infos:
920 raise OSError('getaddrinfo() returned empty list')
921
922 exceptions = []
923 for family, type, proto, cname, address in infos:
924 try:
925 sock = socket.socket(family=family, type=type, proto=proto)
926 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500927 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700928 for _, _, _, _, laddr in laddr_infos:
929 try:
930 sock.bind(laddr)
931 break
932 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500933 msg = (
934 f'error while attempting to bind on '
935 f'address {laddr!r}: '
936 f'{exc.strerror.lower()}'
937 )
938 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700939 exceptions.append(exc)
940 else:
941 sock.close()
942 sock = None
943 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200944 if self._debug:
945 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200946 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700947 except OSError as exc:
948 if sock is not None:
949 sock.close()
950 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200951 except:
952 if sock is not None:
953 sock.close()
954 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700955 else:
956 break
957 else:
958 if len(exceptions) == 1:
959 raise exceptions[0]
960 else:
961 # If they all have the same str(), raise one.
962 model = str(exceptions[0])
963 if all(str(exc) == model for exc in exceptions):
964 raise exceptions[0]
965 # Raise a combined exception so the user can see all
966 # the various error messages.
967 raise OSError('Multiple exceptions: {}'.format(
968 ', '.join(str(exc) for exc in exceptions)))
969
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500970 else:
971 if sock is None:
972 raise ValueError(
973 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500974 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500975 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
976 # are SOCK_STREAM.
977 # We support passing AF_UNIX sockets even though we have
978 # a dedicated API for that: create_unix_connection.
979 # Disallowing AF_UNIX in this method, breaks backwards
980 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500981 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500982 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700983
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200984 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000985 sock, protocol_factory, ssl, server_hostname,
986 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200987 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200988 # Get the socket from the transport because SSL transport closes
989 # the old socket and creates a new SSL socket
990 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200991 logger.debug("%r connected to %s:%r: (%r, %r)",
992 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500993 return transport, protocol
994
Neil Aspinallf7686c12017-12-19 19:45:42 +0000995 async def _create_connection_transport(
996 self, sock, protocol_factory, ssl,
997 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200998 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400999
1000 sock.setblocking(False)
1001
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001002 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001003 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001004 if ssl:
1005 sslcontext = None if isinstance(ssl, bool) else ssl
1006 transport = self._make_ssl_transport(
1007 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +00001008 server_side=server_side, server_hostname=server_hostname,
1009 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001010 else:
1011 transport = self._make_socket_transport(sock, protocol, waiter)
1012
Victor Stinner29ad0112015-01-15 00:04:21 +01001013 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001014 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +01001015 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001016 transport.close()
1017 raise
1018
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001019 return transport, protocol
1020
Andrew Svetlov7c684072018-01-27 21:22:47 +02001021 async def sendfile(self, transport, file, offset=0, count=None,
1022 *, fallback=True):
1023 """Send a file to transport.
1024
1025 Return the total number of bytes which were sent.
1026
1027 The method uses high-performance os.sendfile if available.
1028
1029 file must be a regular file object opened in binary mode.
1030
1031 offset tells from where to start reading the file. If specified,
1032 count is the total number of bytes to transmit as opposed to
1033 sending the file until EOF is reached. File position is updated on
1034 return or also in case of error in which case file.tell()
1035 can be used to figure out the number of bytes
1036 which were sent.
1037
1038 fallback set to True makes asyncio to manually read and send
1039 the file when the platform does not support the sendfile syscall
1040 (e.g. Windows or SSL socket on Unix).
1041
1042 Raise SendfileNotAvailableError if the system does not support
1043 sendfile syscall and fallback is False.
1044 """
1045 if transport.is_closing():
1046 raise RuntimeError("Transport is closing")
1047 mode = getattr(transport, '_sendfile_compatible',
1048 constants._SendfileMode.UNSUPPORTED)
1049 if mode is constants._SendfileMode.UNSUPPORTED:
1050 raise RuntimeError(
1051 f"sendfile is not supported for transport {transport!r}")
1052 if mode is constants._SendfileMode.TRY_NATIVE:
1053 try:
1054 return await self._sendfile_native(transport, file,
1055 offset, count)
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001056 except exceptions.SendfileNotAvailableError as exc:
Andrew Svetlov7c684072018-01-27 21:22:47 +02001057 if not fallback:
1058 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001059
1060 if not fallback:
1061 raise RuntimeError(
1062 f"fallback is disabled and native sendfile is not "
1063 f"supported for transport {transport!r}")
1064
Andrew Svetlov7c684072018-01-27 21:22:47 +02001065 return await self._sendfile_fallback(transport, file,
1066 offset, count)
1067
1068 async def _sendfile_native(self, transp, file, offset, count):
Andrew Svetlov0baa72f2018-09-11 10:13:04 -07001069 raise exceptions.SendfileNotAvailableError(
Andrew Svetlov7c684072018-01-27 21:22:47 +02001070 "sendfile syscall is not supported")
1071
1072 async def _sendfile_fallback(self, transp, file, offset, count):
1073 if offset:
1074 file.seek(offset)
1075 blocksize = min(count, 16384) if count else 16384
1076 buf = bytearray(blocksize)
1077 total_sent = 0
1078 proto = _SendfileFallbackProtocol(transp)
1079 try:
1080 while True:
1081 if count:
1082 blocksize = min(count - total_sent, blocksize)
1083 if blocksize <= 0:
1084 return total_sent
1085 view = memoryview(buf)[:blocksize]
1086 read = file.readinto(view)
1087 if not read:
1088 return total_sent # EOF
1089 await proto.drain()
1090 transp.write(view)
1091 total_sent += read
1092 finally:
1093 if total_sent > 0 and hasattr(file, 'seek'):
1094 file.seek(offset + total_sent)
1095 await proto.restore()
1096
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001097 async def start_tls(self, transport, protocol, sslcontext, *,
1098 server_side=False,
1099 server_hostname=None,
1100 ssl_handshake_timeout=None):
1101 """Upgrade transport to TLS.
1102
1103 Return a new transport that *protocol* should start using
1104 immediately.
1105 """
1106 if ssl is None:
1107 raise RuntimeError('Python ssl module is not available')
1108
1109 if not isinstance(sslcontext, ssl.SSLContext):
1110 raise TypeError(
1111 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1112 f'got {sslcontext!r}')
1113
1114 if not getattr(transport, '_start_tls_compatible', False):
1115 raise TypeError(
Yury Selivanov415bc462018-06-05 08:59:58 -04001116 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001117
1118 waiter = self.create_future()
1119 ssl_protocol = sslproto.SSLProtocol(
1120 self, protocol, sslcontext, waiter,
1121 server_side, server_hostname,
1122 ssl_handshake_timeout=ssl_handshake_timeout,
1123 call_connection_made=False)
1124
Yury Selivanovf2955872018-05-29 01:00:12 -04001125 # Pause early so that "ssl_protocol.data_received()" doesn't
1126 # have a chance to get called before "ssl_protocol.connection_made()".
1127 transport.pause_reading()
1128
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001129 transport.set_protocol(ssl_protocol)
Yury Selivanov415bc462018-06-05 08:59:58 -04001130 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1131 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001132
Yury Selivanov96026432018-06-04 11:32:35 -04001133 try:
1134 await waiter
1135 except Exception:
1136 transport.close()
Yury Selivanov415bc462018-06-05 08:59:58 -04001137 conmade_cb.cancel()
1138 resume_cb.cancel()
Yury Selivanov96026432018-06-04 11:32:35 -04001139 raise
1140
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001141 return ssl_protocol._app_transport
1142
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001143 async def create_datagram_endpoint(self, protocol_factory,
1144 local_addr=None, remote_addr=None, *,
1145 family=0, proto=0, flags=0,
1146 reuse_address=None, reuse_port=None,
1147 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001148 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001149 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001150 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001151 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001152 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001153 if (local_addr or remote_addr or
1154 family or proto or flags or
1155 reuse_address or reuse_port or allow_broadcast):
1156 # show the problematic kwargs in exception msg
1157 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1158 family=family, proto=proto, flags=flags,
1159 reuse_address=reuse_address, reuse_port=reuse_port,
1160 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001161 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001162 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001163 f'socket modifier keyword arguments can not be used '
1164 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001165 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001166 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001167 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001168 if not (local_addr or remote_addr):
1169 if family == 0:
1170 raise ValueError('unexpected address family')
1171 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001172 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1173 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001174 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001175 raise TypeError('string is expected')
1176 addr_pairs_info = (((family, proto),
1177 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001178 else:
1179 # join address by (family, protocol)
1180 addr_infos = collections.OrderedDict()
1181 for idx, addr in ((0, local_addr), (1, remote_addr)):
1182 if addr is not None:
1183 assert isinstance(addr, tuple) and len(addr) == 2, (
1184 '2-tuple is expected')
1185
Yury Selivanov19a44f62017-12-14 20:53:26 -05001186 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001187 addr, family=family, type=socket.SOCK_DGRAM,
1188 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001189 if not infos:
1190 raise OSError('getaddrinfo() returned empty list')
1191
1192 for fam, _, pro, _, address in infos:
1193 key = (fam, pro)
1194 if key not in addr_infos:
1195 addr_infos[key] = [None, None]
1196 addr_infos[key][idx] = address
1197
1198 # each addr has to have info for each (family, proto) pair
1199 addr_pairs_info = [
1200 (key, addr_pair) for key, addr_pair in addr_infos.items()
1201 if not ((local_addr and addr_pair[0] is None) or
1202 (remote_addr and addr_pair[1] is None))]
1203
1204 if not addr_pairs_info:
1205 raise ValueError('can not get address information')
1206
1207 exceptions = []
1208
1209 if reuse_address is None:
1210 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1211
1212 for ((family, proto),
1213 (local_address, remote_address)) in addr_pairs_info:
1214 sock = None
1215 r_addr = None
1216 try:
1217 sock = socket.socket(
1218 family=family, type=socket.SOCK_DGRAM, proto=proto)
1219 if reuse_address:
1220 sock.setsockopt(
1221 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1222 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001223 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001224 if allow_broadcast:
1225 sock.setsockopt(
1226 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1227 sock.setblocking(False)
1228
1229 if local_addr:
1230 sock.bind(local_address)
1231 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001232 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001233 r_addr = remote_address
1234 except OSError as exc:
1235 if sock is not None:
1236 sock.close()
1237 exceptions.append(exc)
1238 except:
1239 if sock is not None:
1240 sock.close()
1241 raise
1242 else:
1243 break
1244 else:
1245 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001246
1247 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001248 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001249 transport = self._make_datagram_transport(
1250 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001251 if self._debug:
1252 if local_addr:
1253 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1254 "created: (%r, %r)",
1255 local_addr, remote_addr, transport, protocol)
1256 else:
1257 logger.debug("Datagram endpoint remote_addr=%r created: "
1258 "(%r, %r)",
1259 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001260
1261 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001262 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001263 except:
1264 transport.close()
1265 raise
1266
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001267 return transport, protocol
1268
Yury Selivanov19a44f62017-12-14 20:53:26 -05001269 async def _ensure_resolved(self, address, *,
1270 family=0, type=socket.SOCK_STREAM,
1271 proto=0, flags=0, loop):
1272 host, port = address[:2]
1273 info = _ipaddr_info(host, port, family, type, proto)
1274 if info is not None:
1275 # "host" is already a resolved IP.
1276 return [info]
1277 else:
1278 return await loop.getaddrinfo(host, port, family=family, type=type,
1279 proto=proto, flags=flags)
1280
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001281 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001282 infos = await self._ensure_resolved((host, port), family=family,
1283 type=socket.SOCK_STREAM,
1284 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001285 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001286 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001287 return infos
1288
Neil Aspinallf7686c12017-12-19 19:45:42 +00001289 async def create_server(
1290 self, protocol_factory, host=None, port=None,
1291 *,
1292 family=socket.AF_UNSPEC,
1293 flags=socket.AI_PASSIVE,
1294 sock=None,
1295 backlog=100,
1296 ssl=None,
1297 reuse_address=None,
1298 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001299 ssl_handshake_timeout=None,
1300 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001301 """Create a TCP server.
1302
Yury Selivanov6370f342017-12-10 18:36:12 -05001303 The host parameter can be a string, in that case the TCP server is
1304 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001305
1306 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001307 the TCP server is bound to all hosts of the sequence. If a host
1308 appears multiple times (possibly indirectly e.g. when hostnames
1309 resolve to the same IP address), the server is only bound once to that
1310 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001311
Victor Stinneracdb7822014-07-14 18:33:40 +02001312 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001313
1314 This method is a coroutine.
1315 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001316 if isinstance(ssl, bool):
1317 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001318
1319 if ssl_handshake_timeout is not None and ssl is None:
1320 raise ValueError(
1321 'ssl_handshake_timeout is only meaningful with ssl')
1322
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323 if host is not None or port is not None:
1324 if sock is not None:
1325 raise ValueError(
1326 'host/port and sock can not be specified at the same time')
1327
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001328 if reuse_address is None:
1329 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1330 sockets = []
1331 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001332 hosts = [None]
1333 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001334 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001335 hosts = [host]
1336 else:
1337 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001338
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001339 fs = [self._create_server_getaddrinfo(host, port, family=family,
1340 flags=flags)
1341 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001342 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001343 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001344
1345 completed = False
1346 try:
1347 for res in infos:
1348 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001349 try:
1350 sock = socket.socket(af, socktype, proto)
1351 except socket.error:
1352 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001353 if self._debug:
1354 logger.warning('create_server() failed to create '
1355 'socket.socket(%r, %r, %r)',
1356 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001357 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001358 sockets.append(sock)
1359 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001360 sock.setsockopt(
1361 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1362 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001363 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001364 # Disable IPv4/IPv6 dual stack support (enabled by
1365 # default on Linux) which makes a single socket
1366 # listen on both address families.
Yury Selivanovd904c232018-06-28 21:59:32 -04001367 if (_HAS_IPv6 and
1368 af == socket.AF_INET6 and
1369 hasattr(socket, 'IPPROTO_IPV6')):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001370 sock.setsockopt(socket.IPPROTO_IPV6,
1371 socket.IPV6_V6ONLY,
1372 True)
1373 try:
1374 sock.bind(sa)
1375 except OSError as err:
1376 raise OSError(err.errno, 'error while attempting '
1377 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001378 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001379 completed = True
1380 finally:
1381 if not completed:
1382 for sock in sockets:
1383 sock.close()
1384 else:
1385 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001386 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001387 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001388 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001389 sockets = [sock]
1390
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001391 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001392 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001393
1394 server = Server(self, sockets, protocol_factory,
1395 ssl, backlog, ssl_handshake_timeout)
1396 if start_serving:
1397 server._start_serving()
Yury Selivanovdbf10222018-05-28 14:31:28 -04001398 # Skip one loop iteration so that all 'loop.add_reader'
1399 # go through.
1400 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001401
Victor Stinnere912e652014-07-12 03:11:53 +02001402 if self._debug:
1403 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001404 return server
1405
Neil Aspinallf7686c12017-12-19 19:45:42 +00001406 async def connect_accepted_socket(
1407 self, protocol_factory, sock,
1408 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001409 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001410 """Handle an accepted connection.
1411
1412 This is used by servers that accept connections outside of
1413 asyncio but that use asyncio to handle connections.
1414
1415 This method is a coroutine. When completed, the coroutine
1416 returns a (transport, protocol) pair.
1417 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001418 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001419 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001420
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001421 if ssl_handshake_timeout is not None and not ssl:
1422 raise ValueError(
1423 'ssl_handshake_timeout is only meaningful with ssl')
1424
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001425 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001426 sock, protocol_factory, ssl, '', server_side=True,
1427 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001428 if self._debug:
1429 # Get the socket from the transport because SSL transport closes
1430 # the old socket and creates a new SSL socket
1431 sock = transport.get_extra_info('socket')
1432 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1433 return transport, protocol
1434
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001435 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001436 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001437 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001438 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001439
1440 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001441 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001442 except:
1443 transport.close()
1444 raise
1445
Victor Stinneracdb7822014-07-14 18:33:40 +02001446 if self._debug:
1447 logger.debug('Read pipe %r connected: (%r, %r)',
1448 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001449 return transport, protocol
1450
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001451 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001452 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001453 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001454 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001455
1456 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001457 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001458 except:
1459 transport.close()
1460 raise
1461
Victor Stinneracdb7822014-07-14 18:33:40 +02001462 if self._debug:
1463 logger.debug('Write pipe %r connected: (%r, %r)',
1464 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001465 return transport, protocol
1466
Victor Stinneracdb7822014-07-14 18:33:40 +02001467 def _log_subprocess(self, msg, stdin, stdout, stderr):
1468 info = [msg]
1469 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001470 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001471 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001472 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001473 else:
1474 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001475 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001476 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001477 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001478 logger.debug(' '.join(info))
1479
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001480 async def subprocess_shell(self, protocol_factory, cmd, *,
1481 stdin=subprocess.PIPE,
1482 stdout=subprocess.PIPE,
1483 stderr=subprocess.PIPE,
1484 universal_newlines=False,
1485 shell=True, bufsize=0,
1486 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001487 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001488 raise ValueError("cmd must be a string")
1489 if universal_newlines:
1490 raise ValueError("universal_newlines must be False")
1491 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001492 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001493 if bufsize != 0:
1494 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001495 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001496 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001497 if self._debug:
1498 # don't log parameters: they may contain sensitive information
1499 # (password) and may be too long
1500 debug_log = 'run shell command %r' % cmd
1501 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001502 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001503 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001504 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001505 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001506 return transport, protocol
1507
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001508 async def subprocess_exec(self, protocol_factory, program, *args,
1509 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1510 stderr=subprocess.PIPE, universal_newlines=False,
1511 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001512 if universal_newlines:
1513 raise ValueError("universal_newlines must be False")
1514 if shell:
1515 raise ValueError("shell must be False")
1516 if bufsize != 0:
1517 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001518 popen_args = (program,) + args
1519 for arg in popen_args:
1520 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001521 raise TypeError(
1522 f"program arguments must be a bytes or text string, "
1523 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001524 protocol = protocol_factory()
Yury Selivanov12f482e2018-06-08 18:24:37 -04001525 debug_log = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001526 if self._debug:
1527 # don't log parameters: they may contain sensitive information
1528 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001529 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001530 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001531 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001532 protocol, popen_args, False, stdin, stdout, stderr,
1533 bufsize, **kwargs)
Yury Selivanov12f482e2018-06-08 18:24:37 -04001534 if self._debug and debug_log is not None:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001535 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001536 return transport, protocol
1537
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001538 def get_exception_handler(self):
1539 """Return an exception handler, or None if the default one is in use.
1540 """
1541 return self._exception_handler
1542
Yury Selivanov569efa22014-02-18 18:02:19 -05001543 def set_exception_handler(self, handler):
1544 """Set handler as the new event loop exception handler.
1545
1546 If handler is None, the default exception handler will
1547 be set.
1548
1549 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001550 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001551 will be a reference to the active event loop, 'context'
1552 will be a dict object (see `call_exception_handler()`
1553 documentation for details about context).
1554 """
1555 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001556 raise TypeError(f'A callable object or None is expected, '
1557 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001558 self._exception_handler = handler
1559
1560 def default_exception_handler(self, context):
1561 """Default exception handler.
1562
1563 This is called when an exception occurs and no exception
1564 handler is set, and can be called by a custom exception
1565 handler that wants to defer to the default behavior.
1566
Antoine Pitrou921e9432017-11-07 17:23:29 +01001567 This default handler logs the error message and other
1568 context-dependent information. In debug mode, a truncated
1569 stack trace is also appended showing where the given object
1570 (e.g. a handle or future or task) was created, if any.
1571
Victor Stinneracdb7822014-07-14 18:33:40 +02001572 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001573 `call_exception_handler()`.
1574 """
1575 message = context.get('message')
1576 if not message:
1577 message = 'Unhandled exception in event loop'
1578
1579 exception = context.get('exception')
1580 if exception is not None:
1581 exc_info = (type(exception), exception, exception.__traceback__)
1582 else:
1583 exc_info = False
1584
Yury Selivanov6370f342017-12-10 18:36:12 -05001585 if ('source_traceback' not in context and
1586 self._current_handle is not None and
1587 self._current_handle._source_traceback):
1588 context['handle_traceback'] = \
1589 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001590
Yury Selivanov569efa22014-02-18 18:02:19 -05001591 log_lines = [message]
1592 for key in sorted(context):
1593 if key in {'message', 'exception'}:
1594 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001595 value = context[key]
1596 if key == 'source_traceback':
1597 tb = ''.join(traceback.format_list(value))
1598 value = 'Object created at (most recent call last):\n'
1599 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001600 elif key == 'handle_traceback':
1601 tb = ''.join(traceback.format_list(value))
1602 value = 'Handle created at (most recent call last):\n'
1603 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001604 else:
1605 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001606 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001607
1608 logger.error('\n'.join(log_lines), exc_info=exc_info)
1609
1610 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001611 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001612
Victor Stinneracdb7822014-07-14 18:33:40 +02001613 The context argument is a dict containing the following keys:
1614
Yury Selivanov569efa22014-02-18 18:02:19 -05001615 - 'message': Error message;
1616 - 'exception' (optional): Exception object;
1617 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001618 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001619 - 'handle' (optional): Handle instance;
1620 - 'protocol' (optional): Protocol instance;
1621 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001622 - 'socket' (optional): Socket instance;
1623 - 'asyncgen' (optional): Asynchronous generator that caused
1624 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001625
Victor Stinneracdb7822014-07-14 18:33:40 +02001626 New keys maybe introduced in the future.
1627
1628 Note: do not overload this method in an event loop subclass.
1629 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001630 `set_exception_handler()` method.
1631 """
1632 if self._exception_handler is None:
1633 try:
1634 self.default_exception_handler(context)
1635 except Exception:
1636 # Second protection layer for unexpected errors
1637 # in the default implementation, as well as for subclassed
1638 # event loops with overloaded "default_exception_handler".
1639 logger.error('Exception in default exception handler',
1640 exc_info=True)
1641 else:
1642 try:
1643 self._exception_handler(self, context)
1644 except Exception as exc:
1645 # Exception in the user set custom exception handler.
1646 try:
1647 # Let's try default handler.
1648 self.default_exception_handler({
1649 'message': 'Unhandled error in exception handler',
1650 'exception': exc,
1651 'context': context,
1652 })
1653 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001654 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001655 # overloaded.
1656 logger.error('Exception in default exception handler '
1657 'while handling an unexpected error '
1658 'in custom exception handler',
1659 exc_info=True)
1660
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001661 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001662 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001663 assert isinstance(handle, events.Handle), 'A Handle is required here'
1664 if handle._cancelled:
1665 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001666 assert not isinstance(handle, events.TimerHandle)
1667 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001668
1669 def _add_callback_signalsafe(self, handle):
1670 """Like _add_callback() but called from a signal handler."""
1671 self._add_callback(handle)
1672 self._write_to_self()
1673
Yury Selivanov592ada92014-09-25 12:07:56 -04001674 def _timer_handle_cancelled(self, handle):
1675 """Notification that a TimerHandle has been cancelled."""
1676 if handle._scheduled:
1677 self._timer_cancelled_count += 1
1678
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001679 def _run_once(self):
1680 """Run one full iteration of the event loop.
1681
1682 This calls all currently ready callbacks, polls for I/O,
1683 schedules the resulting callbacks, and finally schedules
1684 'call_later' callbacks.
1685 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001686
Yury Selivanov592ada92014-09-25 12:07:56 -04001687 sched_count = len(self._scheduled)
1688 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1689 self._timer_cancelled_count / sched_count >
1690 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001691 # Remove delayed calls that were cancelled if their number
1692 # is too high
1693 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001694 for handle in self._scheduled:
1695 if handle._cancelled:
1696 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001697 else:
1698 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001699
Victor Stinner68da8fc2014-09-30 18:08:36 +02001700 heapq.heapify(new_scheduled)
1701 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001702 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001703 else:
1704 # Remove delayed calls that were cancelled from head of queue.
1705 while self._scheduled and self._scheduled[0]._cancelled:
1706 self._timer_cancelled_count -= 1
1707 handle = heapq.heappop(self._scheduled)
1708 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001709
1710 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001711 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001712 timeout = 0
1713 elif self._scheduled:
1714 # Compute the desired timeout.
1715 when = self._scheduled[0]._when
MartinAltmayer944451c2018-07-31 15:06:12 +01001716 timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001717
Andrew Svetlovd5bd0362018-09-30 08:28:40 +03001718 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001719 self._process_events(event_list)
1720
1721 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001722 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001723 while self._scheduled:
1724 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001725 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001726 break
1727 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001728 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001729 self._ready.append(handle)
1730
1731 # This is the only place where callbacks are actually *called*.
1732 # All other places just add them to ready.
1733 # Note: We run all currently scheduled callbacks, but not any
1734 # callbacks scheduled by callbacks run this time around --
1735 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001736 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001737 ntodo = len(self._ready)
1738 for i in range(ntodo):
1739 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001740 if handle._cancelled:
1741 continue
1742 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001743 try:
1744 self._current_handle = handle
1745 t0 = self.time()
1746 handle._run()
1747 dt = self.time() - t0
1748 if dt >= self.slow_callback_duration:
1749 logger.warning('Executing %s took %.3f seconds',
1750 _format_handle(handle), dt)
1751 finally:
1752 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001753 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001754 handle._run()
1755 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001756
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001757 def _set_coroutine_origin_tracking(self, enabled):
1758 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001759 return
1760
Yury Selivanove8944cb2015-05-12 11:43:04 -04001761 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001762 self._coroutine_origin_tracking_saved_depth = (
1763 sys.get_coroutine_origin_tracking_depth())
1764 sys.set_coroutine_origin_tracking_depth(
1765 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001766 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001767 sys.set_coroutine_origin_tracking_depth(
1768 self._coroutine_origin_tracking_saved_depth)
1769
1770 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001771
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001772 def get_debug(self):
1773 return self._debug
1774
1775 def set_debug(self, enabled):
1776 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001777
Yury Selivanove8944cb2015-05-12 11:43:04 -04001778 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001779 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)