blob: 648b9b9bbc2f5cd516ce4d93f71373f47e201043 [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
17import concurrent.futures
18import heapq
Victor Stinner0e6f52a2014-06-20 17:34:15 +020019import inspect
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 Selivanovf6d991d2016-09-15 13:10:51 -040030import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanov2a8911c2015-08-04 15:56:33 -040032from . import compat
Victor Stinnerf951d282014-06-29 00:46:45 +020033from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070034from . import events
35from . import futures
36from . import tasks
Victor Stinnerf951d282014-06-29 00:46:45 +020037from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070038from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039
40
Victor Stinner8c1a4a22015-01-06 01:03:58 +010041__all__ = ['BaseEventLoop']
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042
43
44# Argument for default thread pool executor creation.
45_MAX_WORKERS = 5
46
Yury Selivanov592ada92014-09-25 12:07:56 -040047# Minimum number of _scheduled timer handles before cleanup of
48# cancelled handles is performed.
49_MIN_SCHEDULED_TIMER_HANDLES = 100
50
51# Minimum fraction of _scheduled timer handles that are cancelled
52# before cleanup of cancelled handles is performed.
53_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070054
Victor Stinnerc94a93a2016-04-01 21:43:39 +020055# Exceptions which must not call the exception handler in fatal error
56# methods (_fatal_error())
57_FATAL_ERROR_IGNORE = (BrokenPipeError,
58 ConnectionResetError, ConnectionAbortedError)
59
60
Victor Stinner0e6f52a2014-06-20 17:34:15 +020061def _format_handle(handle):
62 cb = handle._callback
63 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
64 # format the task
65 return repr(cb.__self__)
66 else:
67 return str(handle)
68
69
Victor Stinneracdb7822014-07-14 18:33:40 +020070def _format_pipe(fd):
71 if fd == subprocess.PIPE:
72 return '<pipe>'
73 elif fd == subprocess.STDOUT:
74 return '<stdout>'
75 else:
76 return repr(fd)
77
78
Yury Selivanov5587d7c2016-09-15 15:45:07 -040079def _set_reuseport(sock):
80 if not hasattr(socket, 'SO_REUSEPORT'):
81 raise ValueError('reuse_port not supported by socket module')
82 else:
83 try:
84 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
85 except OSError:
86 raise ValueError('reuse_port not supported by socket module, '
87 'SO_REUSEPORT defined but not implemented.')
88
89
Yury Selivanovd5c2a622015-12-16 19:31:17 -050090# Linux's sock.type is a bitmask that can include extra info about socket.
91_SOCKET_TYPE_MASK = 0
92if hasattr(socket, 'SOCK_NONBLOCK'):
93 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
94if hasattr(socket, 'SOCK_CLOEXEC'):
95 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
96
97
Yury Selivanovd5c2a622015-12-16 19:31:17 -050098def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040099 # Try to skip getaddrinfo if "host" is already an IP. Users might have
100 # handled name resolution in their own code and pass in resolved IPs.
101 if not hasattr(socket, 'inet_pton'):
102 return
103
104 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
105 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500106 return None
107
108 type &= ~_SOCKET_TYPE_MASK
109 if type == socket.SOCK_STREAM:
110 proto = socket.IPPROTO_TCP
111 elif type == socket.SOCK_DGRAM:
112 proto = socket.IPPROTO_UDP
113 else:
114 return None
115
Yury Selivanova7146162016-06-02 16:51:07 -0400116 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400117 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700118 elif isinstance(port, bytes) and port == b'':
119 port = 0
120 elif isinstance(port, str) and port == '':
121 port = 0
122 else:
123 # If port's a service name like "http", don't skip getaddrinfo.
124 try:
125 port = int(port)
126 except (TypeError, ValueError):
127 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400128
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400129 if family == socket.AF_UNSPEC:
130 afs = [socket.AF_INET, socket.AF_INET6]
131 else:
132 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500133
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400134 if isinstance(host, bytes):
135 host = host.decode('idna')
136 if '%' in host:
137 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
138 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500139 return None
140
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400141 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500142 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400143 socket.inet_pton(af, host)
144 # The host has already been resolved.
145 return af, type, proto, '', (host, port)
146 except OSError:
147 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400149 # "host" is not an IP address.
150 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500151
152
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400153def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
154 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500155 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400156 info = _ipaddr_info(host, port, family, type, proto)
157 if info is not None:
158 # "host" is already a resolved IP.
159 fut = loop.create_future()
160 fut.set_result([info])
161 return fut
162 else:
163 return loop.getaddrinfo(host, port, family=family, type=type,
164 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100165
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700166
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100167def _run_until_complete_cb(fut):
168 exc = fut._exception
169 if (isinstance(exc, BaseException)
170 and not isinstance(exc, Exception)):
171 # Issue #22429: run_forever() already finished, no need to
172 # stop it.
173 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800174 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100175
176
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700177class Server(events.AbstractServer):
178
179 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200180 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700181 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200182 self._active_count = 0
183 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700184
Victor Stinnere912e652014-07-12 03:11:53 +0200185 def __repr__(self):
186 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
187
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200188 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700189 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200190 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200192 def _detach(self):
193 assert self._active_count > 0
194 self._active_count -= 1
195 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700196 self._wakeup()
197
198 def close(self):
199 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200200 if sockets is None:
201 return
202 self.sockets = None
203 for sock in sockets:
204 self._loop._stop_serving(sock)
205 if self._active_count == 0:
206 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700207
208 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200209 waiters = self._waiters
210 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700211 for waiter in waiters:
212 if not waiter.done():
213 waiter.set_result(waiter)
214
Victor Stinnerf951d282014-06-29 00:46:45 +0200215 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700216 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400219 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200220 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700221 yield from waiter
222
223
224class BaseEventLoop(events.AbstractEventLoop):
225
226 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400227 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200228 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800229 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700230 self._ready = collections.deque()
231 self._scheduled = []
232 self._default_executor = None
233 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100234 # Identifier of the thread running the event loop, or None if the
235 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100236 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100237 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500238 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400239 self.set_debug((not sys.flags.ignore_environment
240 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200241 # In debug mode, if the execution of a callback or a step of a task
242 # exceed this duration in seconds, the slow callback/task is logged.
243 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100244 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400245 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400246 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700247
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400248 if hasattr(sys, 'get_asyncgen_hooks'):
249 # Python >= 3.6
250 # A weak set of all asynchronous generators that are
251 # being iterated by the loop.
252 self._asyncgens = weakref.WeakSet()
253 else:
254 self._asyncgens = None
255
256 # Set to True when `loop.shutdown_asyncgens` is called.
257 self._asyncgens_shutdown_called = False
258
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200259 def __repr__(self):
260 return ('<%s running=%s closed=%s debug=%s>'
261 % (self.__class__.__name__, self.is_running(),
262 self.is_closed(), self.get_debug()))
263
Yury Selivanov7661db62016-05-16 15:38:39 -0400264 def create_future(self):
265 """Create a Future object attached to the loop."""
266 return futures.Future(loop=self)
267
Victor Stinner896a25a2014-07-08 11:29:25 +0200268 def create_task(self, coro):
269 """Schedule a coroutine object.
270
Victor Stinneracdb7822014-07-14 18:33:40 +0200271 Return a task object.
272 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100273 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400274 if self._task_factory is None:
275 task = tasks.Task(coro, loop=self)
276 if task._source_traceback:
277 del task._source_traceback[-1]
278 else:
279 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200280 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200281
Yury Selivanov740169c2015-05-11 14:23:38 -0400282 def set_task_factory(self, factory):
283 """Set a task factory that will be used by loop.create_task().
284
285 If factory is None the default task factory will be set.
286
287 If factory is a callable, it should have a signature matching
288 '(loop, coro)', where 'loop' will be a reference to the active
289 event loop, 'coro' will be a coroutine object. The callable
290 must return a Future.
291 """
292 if factory is not None and not callable(factory):
293 raise TypeError('task factory must be a callable or None')
294 self._task_factory = factory
295
296 def get_task_factory(self):
297 """Return a task factory, or None if the default one is in use."""
298 return self._task_factory
299
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700300 def _make_socket_transport(self, sock, protocol, waiter=None, *,
301 extra=None, server=None):
302 """Create socket transport."""
303 raise NotImplementedError
304
Victor Stinner15cc6782015-01-09 00:09:10 +0100305 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
306 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700307 extra=None, server=None):
308 """Create SSL transport."""
309 raise NotImplementedError
310
311 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200312 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700313 """Create datagram transport."""
314 raise NotImplementedError
315
316 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
317 extra=None):
318 """Create read pipe transport."""
319 raise NotImplementedError
320
321 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
322 extra=None):
323 """Create write pipe transport."""
324 raise NotImplementedError
325
Victor Stinnerf951d282014-06-29 00:46:45 +0200326 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700327 def _make_subprocess_transport(self, protocol, args, shell,
328 stdin, stdout, stderr, bufsize,
329 extra=None, **kwargs):
330 """Create subprocess transport."""
331 raise NotImplementedError
332
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700333 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200334 """Write a byte to self-pipe, to wake up the event loop.
335
336 This may be called from a different thread.
337
338 The subclass is responsible for implementing the self-pipe.
339 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700340 raise NotImplementedError
341
342 def _process_events(self, event_list):
343 """Process selector events."""
344 raise NotImplementedError
345
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200346 def _check_closed(self):
347 if self._closed:
348 raise RuntimeError('Event loop is closed')
349
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400350 def _asyncgen_finalizer_hook(self, agen):
351 self._asyncgens.discard(agen)
352 if not self.is_closed():
353 self.create_task(agen.aclose())
354
355 def _asyncgen_firstiter_hook(self, agen):
356 if self._asyncgens_shutdown_called:
357 warnings.warn(
358 "asynchronous generator {!r} was scheduled after "
359 "loop.shutdown_asyncgens() call".format(agen),
360 ResourceWarning, source=self)
361
362 self._asyncgens.add(agen)
363
364 @coroutine
365 def shutdown_asyncgens(self):
366 """Shutdown all active asynchronous generators."""
367 self._asyncgens_shutdown_called = True
368
369 if self._asyncgens is None or not len(self._asyncgens):
370 # If Python version is <3.6 or we don't have any asynchronous
371 # generators alive.
372 return
373
374 closing_agens = list(self._asyncgens)
375 self._asyncgens.clear()
376
377 shutdown_coro = tasks.gather(
378 *[ag.aclose() for ag in closing_agens],
379 return_exceptions=True,
380 loop=self)
381
382 results = yield from shutdown_coro
383 for result, agen in zip(results, closing_agens):
384 if isinstance(result, Exception):
385 self.call_exception_handler({
386 'message': 'an error occurred during closing of '
387 'asynchronous generator {!r}'.format(agen),
388 'exception': result,
389 'asyncgen': agen
390 })
391
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700392 def run_forever(self):
393 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200394 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100395 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700396 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400397 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100398 self._thread_id = threading.get_ident()
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400399 if self._asyncgens is not None:
400 old_agen_hooks = sys.get_asyncgen_hooks()
401 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
402 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700403 try:
404 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800405 self._run_once()
406 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700407 break
408 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800409 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100410 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400411 self._set_coroutine_wrapper(False)
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400412 if self._asyncgens is not None:
413 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700414
415 def run_until_complete(self, future):
416 """Run until the Future is done.
417
418 If the argument is a coroutine, it is wrapped in a Task.
419
Victor Stinneracdb7822014-07-14 18:33:40 +0200420 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700421 with the same coroutine twice -- it would wrap it in two
422 different Tasks and that can't be good.
423
424 Return the Future's result, or raise its exception.
425 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200426 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200427
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700428 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400429 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200430 if new_task:
431 # An exception is raised if the future didn't complete, so there
432 # is no need to log the "destroy pending task" message
433 future._log_destroy_pending = False
434
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100435 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200436 try:
437 self.run_forever()
438 except:
439 if new_task and future.done() and not future.cancelled():
440 # The coroutine raised a BaseException. Consume the exception
441 # to not log a warning, the caller doesn't have access to the
442 # local task.
443 future.exception()
444 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100445 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446 if not future.done():
447 raise RuntimeError('Event loop stopped before Future completed.')
448
449 return future.result()
450
451 def stop(self):
452 """Stop running the event loop.
453
Guido van Rossum41f69f42015-11-19 13:28:47 -0800454 Every callback already scheduled will still run. This simply informs
455 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700456 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800457 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700458
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200459 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700460 """Close the event loop.
461
462 This clears the queues and shuts down the executor,
463 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200464
465 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700466 """
Victor Stinner956de692014-12-26 21:07:52 +0100467 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200468 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200469 if self._closed:
470 return
Victor Stinnere912e652014-07-12 03:11:53 +0200471 if self._debug:
472 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400473 self._closed = True
474 self._ready.clear()
475 self._scheduled.clear()
476 executor = self._default_executor
477 if executor is not None:
478 self._default_executor = None
479 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200480
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200481 def is_closed(self):
482 """Returns True if the event loop was closed."""
483 return self._closed
484
Victor Stinner978a9af2015-01-29 17:50:58 +0100485 # On Python 3.3 and older, objects with a destructor part of a reference
486 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
487 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400488 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100489 def __del__(self):
490 if not self.is_closed():
491 warnings.warn("unclosed event loop %r" % self, ResourceWarning)
492 if not self.is_running():
493 self.close()
494
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700495 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200496 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100497 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700498
499 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200500 """Return the time according to the event loop's clock.
501
502 This is a float expressed in seconds since an epoch, but the
503 epoch, precision, accuracy and drift are unspecified and may
504 differ per event loop.
505 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506 return time.monotonic()
507
508 def call_later(self, delay, callback, *args):
509 """Arrange for a callback to be called at a given time.
510
511 Return a Handle: an opaque object with a cancel() method that
512 can be used to cancel the call.
513
514 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200515 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516
517 Each callback will be called exactly once. If two callbacks
518 are scheduled for exactly the same time, it undefined which
519 will be called first.
520
521 Any positional arguments after the callback will be passed to
522 the callback when it is called.
523 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200524 timer = self.call_at(self.time() + delay, callback, *args)
525 if timer._source_traceback:
526 del timer._source_traceback[-1]
527 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528
529 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200530 """Like call_later(), but uses an absolute time.
531
532 Absolute time corresponds to the event loop's time() method.
533 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100534 if (coroutines.iscoroutine(callback)
535 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100536 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100537 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100538 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100539 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500540 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200541 if timer._source_traceback:
542 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700543 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400544 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700545 return timer
546
547 def call_soon(self, callback, *args):
548 """Arrange for a callback to be called as soon as possible.
549
Victor Stinneracdb7822014-07-14 18:33:40 +0200550 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 order in which they are registered. Each callback will be
552 called exactly once.
553
554 Any positional arguments after the callback will be passed to
555 the callback when it is called.
556 """
Victor Stinner956de692014-12-26 21:07:52 +0100557 if self._debug:
558 self._check_thread()
559 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200560 if handle._source_traceback:
561 del handle._source_traceback[-1]
562 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100563
Victor Stinner956de692014-12-26 21:07:52 +0100564 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100565 if (coroutines.iscoroutine(callback)
566 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100567 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100568 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500569 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200570 if handle._source_traceback:
571 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700572 self._ready.append(handle)
573 return handle
574
Victor Stinner956de692014-12-26 21:07:52 +0100575 def _check_thread(self):
576 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100577
Victor Stinneracdb7822014-07-14 18:33:40 +0200578 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100579 likely behave incorrectly when the assumption is violated.
580
Victor Stinneracdb7822014-07-14 18:33:40 +0200581 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100582 responsible for checking this condition for performance reasons.
583 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100584 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200585 return
Victor Stinner956de692014-12-26 21:07:52 +0100586 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100587 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100588 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200589 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100590 "than the current one")
591
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200593 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100594 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200595 if handle._source_traceback:
596 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700597 self._write_to_self()
598 return handle
599
Yury Selivanov740169c2015-05-11 14:23:38 -0400600 def run_in_executor(self, executor, func, *args):
601 if (coroutines.iscoroutine(func)
602 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100603 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100604 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400605 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700606 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400607 assert not isinstance(func, events.TimerHandle)
Yury Selivanov0de3de62016-10-05 18:28:09 -0400608 warnings.warn(
609 "Passing Handle to loop.run_in_executor() is deprecated",
610 DeprecationWarning)
Yury Selivanov740169c2015-05-11 14:23:38 -0400611 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400612 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700613 f.set_result(None)
614 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400615 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700616 if executor is None:
617 executor = self._default_executor
618 if executor is None:
619 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
620 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400621 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622
623 def set_default_executor(self, executor):
624 self._default_executor = executor
625
Victor Stinnere912e652014-07-12 03:11:53 +0200626 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
627 msg = ["%s:%r" % (host, port)]
628 if family:
629 msg.append('family=%r' % family)
630 if type:
631 msg.append('type=%r' % type)
632 if proto:
633 msg.append('proto=%r' % proto)
634 if flags:
635 msg.append('flags=%r' % flags)
636 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200637 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200638
639 t0 = self.time()
640 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
641 dt = self.time() - t0
642
Victor Stinneracdb7822014-07-14 18:33:40 +0200643 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200644 % (msg, dt * 1e3, addrinfo))
645 if dt >= self.slow_callback_duration:
646 logger.info(msg)
647 else:
648 logger.debug(msg)
649 return addrinfo
650
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700651 def getaddrinfo(self, host, port, *,
652 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400653 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200654 return self.run_in_executor(None, self._getaddrinfo_debug,
655 host, port, family, type, proto, flags)
656 else:
657 return self.run_in_executor(None, socket.getaddrinfo,
658 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700659
660 def getnameinfo(self, sockaddr, flags=0):
661 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
662
Victor Stinnerf951d282014-06-29 00:46:45 +0200663 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664 def create_connection(self, protocol_factory, host=None, port=None, *,
665 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700666 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200667 """Connect to a TCP server.
668
669 Create a streaming transport connection to a given Internet host and
670 port: socket family AF_INET or socket.AF_INET6 depending on host (or
671 family if specified), socket type SOCK_STREAM. protocol_factory must be
672 a callable returning a protocol instance.
673
674 This method is a coroutine which will try to establish the connection
675 in the background. When successful, the coroutine returns a
676 (transport, protocol) pair.
677 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700678 if server_hostname is not None and not ssl:
679 raise ValueError('server_hostname is only meaningful with ssl')
680
681 if server_hostname is None and ssl:
682 # Use host as default for server_hostname. It is an error
683 # if host is empty or not set, e.g. when an
684 # already-connected socket was passed or when only a port
685 # is given. To avoid this error, you can pass
686 # server_hostname='' -- this will bypass the hostname
687 # check. (This also means that if host is a numeric
688 # IP/IPv6 address, we will attempt to verify that exact
689 # address; this will probably fail, but it is possible to
690 # create a certificate for a specific IP address, so we
691 # don't judge it here.)
692 if not host:
693 raise ValueError('You must set server_hostname '
694 'when using ssl without a host')
695 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700696
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700697 if host is not None or port is not None:
698 if sock is not None:
699 raise ValueError(
700 'host/port and sock can not be specified at the same time')
701
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400702 f1 = _ensure_resolved((host, port), family=family,
703 type=socket.SOCK_STREAM, proto=proto,
704 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700705 fs = [f1]
706 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400707 f2 = _ensure_resolved(local_addr, family=family,
708 type=socket.SOCK_STREAM, proto=proto,
709 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700710 fs.append(f2)
711 else:
712 f2 = None
713
714 yield from tasks.wait(fs, loop=self)
715
716 infos = f1.result()
717 if not infos:
718 raise OSError('getaddrinfo() returned empty list')
719 if f2 is not None:
720 laddr_infos = f2.result()
721 if not laddr_infos:
722 raise OSError('getaddrinfo() returned empty list')
723
724 exceptions = []
725 for family, type, proto, cname, address in infos:
726 try:
727 sock = socket.socket(family=family, type=type, proto=proto)
728 sock.setblocking(False)
729 if f2 is not None:
730 for _, _, _, _, laddr in laddr_infos:
731 try:
732 sock.bind(laddr)
733 break
734 except OSError as exc:
735 exc = OSError(
736 exc.errno, 'error while '
737 'attempting to bind on address '
738 '{!r}: {}'.format(
739 laddr, exc.strerror.lower()))
740 exceptions.append(exc)
741 else:
742 sock.close()
743 sock = None
744 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200745 if self._debug:
746 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700747 yield from self.sock_connect(sock, address)
748 except OSError as exc:
749 if sock is not None:
750 sock.close()
751 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200752 except:
753 if sock is not None:
754 sock.close()
755 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700756 else:
757 break
758 else:
759 if len(exceptions) == 1:
760 raise exceptions[0]
761 else:
762 # If they all have the same str(), raise one.
763 model = str(exceptions[0])
764 if all(str(exc) == model for exc in exceptions):
765 raise exceptions[0]
766 # Raise a combined exception so the user can see all
767 # the various error messages.
768 raise OSError('Multiple exceptions: {}'.format(
769 ', '.join(str(exc) for exc in exceptions)))
770
771 elif sock is None:
772 raise ValueError(
773 'host and port was not specified and no sock specified')
774
Yury Selivanovb057c522014-02-18 12:15:06 -0500775 transport, protocol = yield from self._create_connection_transport(
776 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200777 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200778 # Get the socket from the transport because SSL transport closes
779 # the old socket and creates a new SSL socket
780 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200781 logger.debug("%r connected to %s:%r: (%r, %r)",
782 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500783 return transport, protocol
784
Victor Stinnerf951d282014-06-29 00:46:45 +0200785 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500786 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400787 server_hostname, server_side=False):
788
789 sock.setblocking(False)
790
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700791 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400792 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700793 if ssl:
794 sslcontext = None if isinstance(ssl, bool) else ssl
795 transport = self._make_ssl_transport(
796 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400797 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700798 else:
799 transport = self._make_socket_transport(sock, protocol, waiter)
800
Victor Stinner29ad0112015-01-15 00:04:21 +0100801 try:
802 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100803 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100804 transport.close()
805 raise
806
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700807 return transport, protocol
808
Victor Stinnerf951d282014-06-29 00:46:45 +0200809 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700810 def create_datagram_endpoint(self, protocol_factory,
811 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700812 family=0, proto=0, flags=0,
813 reuse_address=None, reuse_port=None,
814 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700815 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700816 if sock is not None:
817 if (local_addr or remote_addr or
818 family or proto or flags or
819 reuse_address or reuse_port or allow_broadcast):
820 # show the problematic kwargs in exception msg
821 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
822 family=family, proto=proto, flags=flags,
823 reuse_address=reuse_address, reuse_port=reuse_port,
824 allow_broadcast=allow_broadcast)
825 problems = ', '.join(
826 '{}={}'.format(k, v) for k, v in opts.items() if v)
827 raise ValueError(
828 'socket modifier keyword arguments can not be used '
829 'when sock is specified. ({})'.format(problems))
830 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700831 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700832 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700833 if not (local_addr or remote_addr):
834 if family == 0:
835 raise ValueError('unexpected address family')
836 addr_pairs_info = (((family, proto), (None, None)),)
837 else:
838 # join address by (family, protocol)
839 addr_infos = collections.OrderedDict()
840 for idx, addr in ((0, local_addr), (1, remote_addr)):
841 if addr is not None:
842 assert isinstance(addr, tuple) and len(addr) == 2, (
843 '2-tuple is expected')
844
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400845 infos = yield from _ensure_resolved(
846 addr, family=family, type=socket.SOCK_DGRAM,
847 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700848 if not infos:
849 raise OSError('getaddrinfo() returned empty list')
850
851 for fam, _, pro, _, address in infos:
852 key = (fam, pro)
853 if key not in addr_infos:
854 addr_infos[key] = [None, None]
855 addr_infos[key][idx] = address
856
857 # each addr has to have info for each (family, proto) pair
858 addr_pairs_info = [
859 (key, addr_pair) for key, addr_pair in addr_infos.items()
860 if not ((local_addr and addr_pair[0] is None) or
861 (remote_addr and addr_pair[1] is None))]
862
863 if not addr_pairs_info:
864 raise ValueError('can not get address information')
865
866 exceptions = []
867
868 if reuse_address is None:
869 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
870
871 for ((family, proto),
872 (local_address, remote_address)) in addr_pairs_info:
873 sock = None
874 r_addr = None
875 try:
876 sock = socket.socket(
877 family=family, type=socket.SOCK_DGRAM, proto=proto)
878 if reuse_address:
879 sock.setsockopt(
880 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
881 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400882 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700883 if allow_broadcast:
884 sock.setsockopt(
885 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
886 sock.setblocking(False)
887
888 if local_addr:
889 sock.bind(local_address)
890 if remote_addr:
891 yield from self.sock_connect(sock, remote_address)
892 r_addr = remote_address
893 except OSError as exc:
894 if sock is not None:
895 sock.close()
896 exceptions.append(exc)
897 except:
898 if sock is not None:
899 sock.close()
900 raise
901 else:
902 break
903 else:
904 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700905
906 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400907 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700908 transport = self._make_datagram_transport(
909 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200910 if self._debug:
911 if local_addr:
912 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
913 "created: (%r, %r)",
914 local_addr, remote_addr, transport, protocol)
915 else:
916 logger.debug("Datagram endpoint remote_addr=%r created: "
917 "(%r, %r)",
918 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100919
920 try:
921 yield from waiter
922 except:
923 transport.close()
924 raise
925
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700926 return transport, protocol
927
Victor Stinnerf951d282014-06-29 00:46:45 +0200928 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200929 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400930 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200931 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400932 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200933 if not infos:
934 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
935 return infos
936
937 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700938 def create_server(self, protocol_factory, host=None, port=None,
939 *,
940 family=socket.AF_UNSPEC,
941 flags=socket.AI_PASSIVE,
942 sock=None,
943 backlog=100,
944 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700945 reuse_address=None,
946 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200947 """Create a TCP server.
948
949 The host parameter can be a string, in that case the TCP server is bound
950 to host and port.
951
952 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500953 the TCP server is bound to all hosts of the sequence. If a host
954 appears multiple times (possibly indirectly e.g. when hostnames
955 resolve to the same IP address), the server is only bound once to that
956 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200957
Victor Stinneracdb7822014-07-14 18:33:40 +0200958 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200959
960 This method is a coroutine.
961 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700962 if isinstance(ssl, bool):
963 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700964 if host is not None or port is not None:
965 if sock is not None:
966 raise ValueError(
967 'host/port and sock can not be specified at the same time')
968
969 AF_INET6 = getattr(socket, 'AF_INET6', 0)
970 if reuse_address is None:
971 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
972 sockets = []
973 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200974 hosts = [None]
975 elif (isinstance(host, str) or
976 not isinstance(host, collections.Iterable)):
977 hosts = [host]
978 else:
979 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700980
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200981 fs = [self._create_server_getaddrinfo(host, port, family=family,
982 flags=flags)
983 for host in hosts]
984 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500985 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700986
987 completed = False
988 try:
989 for res in infos:
990 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700991 try:
992 sock = socket.socket(af, socktype, proto)
993 except socket.error:
994 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200995 if self._debug:
996 logger.warning('create_server() failed to create '
997 'socket.socket(%r, %r, %r)',
998 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700999 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001000 sockets.append(sock)
1001 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001002 sock.setsockopt(
1003 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1004 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001005 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001006 # Disable IPv4/IPv6 dual stack support (enabled by
1007 # default on Linux) which makes a single socket
1008 # listen on both address families.
1009 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1010 sock.setsockopt(socket.IPPROTO_IPV6,
1011 socket.IPV6_V6ONLY,
1012 True)
1013 try:
1014 sock.bind(sa)
1015 except OSError as err:
1016 raise OSError(err.errno, 'error while attempting '
1017 'to bind on address %r: %s'
1018 % (sa, err.strerror.lower()))
1019 completed = True
1020 finally:
1021 if not completed:
1022 for sock in sockets:
1023 sock.close()
1024 else:
1025 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001026 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001027 sockets = [sock]
1028
1029 server = Server(self, sockets)
1030 for sock in sockets:
1031 sock.listen(backlog)
1032 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001033 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001034 if self._debug:
1035 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001036 return server
1037
Victor Stinnerf951d282014-06-29 00:46:45 +02001038 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001039 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1040 """Handle an accepted connection.
1041
1042 This is used by servers that accept connections outside of
1043 asyncio but that use asyncio to handle connections.
1044
1045 This method is a coroutine. When completed, the coroutine
1046 returns a (transport, protocol) pair.
1047 """
1048 transport, protocol = yield from self._create_connection_transport(
1049 sock, protocol_factory, ssl, '', server_side=True)
1050 if self._debug:
1051 # Get the socket from the transport because SSL transport closes
1052 # the old socket and creates a new SSL socket
1053 sock = transport.get_extra_info('socket')
1054 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1055 return transport, protocol
1056
1057 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001058 def connect_read_pipe(self, protocol_factory, pipe):
1059 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001060 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001061 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001062
1063 try:
1064 yield from waiter
1065 except:
1066 transport.close()
1067 raise
1068
Victor Stinneracdb7822014-07-14 18:33:40 +02001069 if self._debug:
1070 logger.debug('Read pipe %r connected: (%r, %r)',
1071 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001072 return transport, protocol
1073
Victor Stinnerf951d282014-06-29 00:46:45 +02001074 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001075 def connect_write_pipe(self, protocol_factory, pipe):
1076 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001077 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001079
1080 try:
1081 yield from waiter
1082 except:
1083 transport.close()
1084 raise
1085
Victor Stinneracdb7822014-07-14 18:33:40 +02001086 if self._debug:
1087 logger.debug('Write pipe %r connected: (%r, %r)',
1088 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001089 return transport, protocol
1090
Victor Stinneracdb7822014-07-14 18:33:40 +02001091 def _log_subprocess(self, msg, stdin, stdout, stderr):
1092 info = [msg]
1093 if stdin is not None:
1094 info.append('stdin=%s' % _format_pipe(stdin))
1095 if stdout is not None and stderr == subprocess.STDOUT:
1096 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1097 else:
1098 if stdout is not None:
1099 info.append('stdout=%s' % _format_pipe(stdout))
1100 if stderr is not None:
1101 info.append('stderr=%s' % _format_pipe(stderr))
1102 logger.debug(' '.join(info))
1103
Victor Stinnerf951d282014-06-29 00:46:45 +02001104 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001105 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1106 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1107 universal_newlines=False, shell=True, bufsize=0,
1108 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001109 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001110 raise ValueError("cmd must be a string")
1111 if universal_newlines:
1112 raise ValueError("universal_newlines must be False")
1113 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001114 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001115 if bufsize != 0:
1116 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001117 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001118 if self._debug:
1119 # don't log parameters: they may contain sensitive information
1120 # (password) and may be too long
1121 debug_log = 'run shell command %r' % cmd
1122 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001123 transport = yield from self._make_subprocess_transport(
1124 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001125 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001126 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001127 return transport, protocol
1128
Victor Stinnerf951d282014-06-29 00:46:45 +02001129 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001130 def subprocess_exec(self, protocol_factory, program, *args,
1131 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1132 stderr=subprocess.PIPE, universal_newlines=False,
1133 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001134 if universal_newlines:
1135 raise ValueError("universal_newlines must be False")
1136 if shell:
1137 raise ValueError("shell must be False")
1138 if bufsize != 0:
1139 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001140 popen_args = (program,) + args
1141 for arg in popen_args:
1142 if not isinstance(arg, (str, bytes)):
1143 raise TypeError("program arguments must be "
1144 "a bytes or text string, not %s"
1145 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001146 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001147 if self._debug:
1148 # don't log parameters: they may contain sensitive information
1149 # (password) and may be too long
1150 debug_log = 'execute program %r' % program
1151 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001152 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001153 protocol, popen_args, False, stdin, stdout, stderr,
1154 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001155 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001156 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001157 return transport, protocol
1158
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001159 def get_exception_handler(self):
1160 """Return an exception handler, or None if the default one is in use.
1161 """
1162 return self._exception_handler
1163
Yury Selivanov569efa22014-02-18 18:02:19 -05001164 def set_exception_handler(self, handler):
1165 """Set handler as the new event loop exception handler.
1166
1167 If handler is None, the default exception handler will
1168 be set.
1169
1170 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001171 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001172 will be a reference to the active event loop, 'context'
1173 will be a dict object (see `call_exception_handler()`
1174 documentation for details about context).
1175 """
1176 if handler is not None and not callable(handler):
1177 raise TypeError('A callable object or None is expected, '
1178 'got {!r}'.format(handler))
1179 self._exception_handler = handler
1180
1181 def default_exception_handler(self, context):
1182 """Default exception handler.
1183
1184 This is called when an exception occurs and no exception
1185 handler is set, and can be called by a custom exception
1186 handler that wants to defer to the default behavior.
1187
Victor Stinneracdb7822014-07-14 18:33:40 +02001188 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001189 `call_exception_handler()`.
1190 """
1191 message = context.get('message')
1192 if not message:
1193 message = 'Unhandled exception in event loop'
1194
1195 exception = context.get('exception')
1196 if exception is not None:
1197 exc_info = (type(exception), exception, exception.__traceback__)
1198 else:
1199 exc_info = False
1200
Victor Stinnerff018e42015-01-28 00:30:40 +01001201 if ('source_traceback' not in context
1202 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001203 and self._current_handle._source_traceback):
1204 context['handle_traceback'] = self._current_handle._source_traceback
1205
Yury Selivanov569efa22014-02-18 18:02:19 -05001206 log_lines = [message]
1207 for key in sorted(context):
1208 if key in {'message', 'exception'}:
1209 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001210 value = context[key]
1211 if key == 'source_traceback':
1212 tb = ''.join(traceback.format_list(value))
1213 value = 'Object created at (most recent call last):\n'
1214 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001215 elif key == 'handle_traceback':
1216 tb = ''.join(traceback.format_list(value))
1217 value = 'Handle created at (most recent call last):\n'
1218 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001219 else:
1220 value = repr(value)
1221 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001222
1223 logger.error('\n'.join(log_lines), exc_info=exc_info)
1224
1225 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001226 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001227
Victor Stinneracdb7822014-07-14 18:33:40 +02001228 The context argument is a dict containing the following keys:
1229
Yury Selivanov569efa22014-02-18 18:02:19 -05001230 - 'message': Error message;
1231 - 'exception' (optional): Exception object;
1232 - 'future' (optional): Future instance;
1233 - 'handle' (optional): Handle instance;
1234 - 'protocol' (optional): Protocol instance;
1235 - 'transport' (optional): Transport instance;
Yury Selivanov4357cf62016-09-15 13:49:08 -04001236 - 'socket' (optional): Socket instance;
1237 - 'asyncgen' (optional): Asynchronous generator that caused
1238 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001239
Victor Stinneracdb7822014-07-14 18:33:40 +02001240 New keys maybe introduced in the future.
1241
1242 Note: do not overload this method in an event loop subclass.
1243 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001244 `set_exception_handler()` method.
1245 """
1246 if self._exception_handler is None:
1247 try:
1248 self.default_exception_handler(context)
1249 except Exception:
1250 # Second protection layer for unexpected errors
1251 # in the default implementation, as well as for subclassed
1252 # event loops with overloaded "default_exception_handler".
1253 logger.error('Exception in default exception handler',
1254 exc_info=True)
1255 else:
1256 try:
1257 self._exception_handler(self, context)
1258 except Exception as exc:
1259 # Exception in the user set custom exception handler.
1260 try:
1261 # Let's try default handler.
1262 self.default_exception_handler({
1263 'message': 'Unhandled error in exception handler',
1264 'exception': exc,
1265 'context': context,
1266 })
1267 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001268 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001269 # overloaded.
1270 logger.error('Exception in default exception handler '
1271 'while handling an unexpected error '
1272 'in custom exception handler',
1273 exc_info=True)
1274
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001275 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001276 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001277 assert isinstance(handle, events.Handle), 'A Handle is required here'
1278 if handle._cancelled:
1279 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001280 assert not isinstance(handle, events.TimerHandle)
1281 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001282
1283 def _add_callback_signalsafe(self, handle):
1284 """Like _add_callback() but called from a signal handler."""
1285 self._add_callback(handle)
1286 self._write_to_self()
1287
Yury Selivanov592ada92014-09-25 12:07:56 -04001288 def _timer_handle_cancelled(self, handle):
1289 """Notification that a TimerHandle has been cancelled."""
1290 if handle._scheduled:
1291 self._timer_cancelled_count += 1
1292
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001293 def _run_once(self):
1294 """Run one full iteration of the event loop.
1295
1296 This calls all currently ready callbacks, polls for I/O,
1297 schedules the resulting callbacks, and finally schedules
1298 'call_later' callbacks.
1299 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001300
Yury Selivanov592ada92014-09-25 12:07:56 -04001301 sched_count = len(self._scheduled)
1302 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1303 self._timer_cancelled_count / sched_count >
1304 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001305 # Remove delayed calls that were cancelled if their number
1306 # is too high
1307 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001308 for handle in self._scheduled:
1309 if handle._cancelled:
1310 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001311 else:
1312 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001313
Victor Stinner68da8fc2014-09-30 18:08:36 +02001314 heapq.heapify(new_scheduled)
1315 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001316 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001317 else:
1318 # Remove delayed calls that were cancelled from head of queue.
1319 while self._scheduled and self._scheduled[0]._cancelled:
1320 self._timer_cancelled_count -= 1
1321 handle = heapq.heappop(self._scheduled)
1322 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323
1324 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001325 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001326 timeout = 0
1327 elif self._scheduled:
1328 # Compute the desired timeout.
1329 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001330 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001331
Victor Stinner770e48d2014-07-11 11:58:33 +02001332 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001333 t0 = self.time()
1334 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001335 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001336 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001337 level = logging.INFO
1338 else:
1339 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001340 nevent = len(event_list)
1341 if timeout is None:
1342 logger.log(level, 'poll took %.3f ms: %s events',
1343 dt * 1e3, nevent)
1344 elif nevent:
1345 logger.log(level,
1346 'poll %.3f ms took %.3f ms: %s events',
1347 timeout * 1e3, dt * 1e3, nevent)
1348 elif dt >= 1.0:
1349 logger.log(level,
1350 'poll %.3f ms took %.3f ms: timeout',
1351 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001352 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001353 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001354 self._process_events(event_list)
1355
1356 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001357 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001358 while self._scheduled:
1359 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001360 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001361 break
1362 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001363 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001364 self._ready.append(handle)
1365
1366 # This is the only place where callbacks are actually *called*.
1367 # All other places just add them to ready.
1368 # Note: We run all currently scheduled callbacks, but not any
1369 # callbacks scheduled by callbacks run this time around --
1370 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001371 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001372 ntodo = len(self._ready)
1373 for i in range(ntodo):
1374 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001375 if handle._cancelled:
1376 continue
1377 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001378 try:
1379 self._current_handle = handle
1380 t0 = self.time()
1381 handle._run()
1382 dt = self.time() - t0
1383 if dt >= self.slow_callback_duration:
1384 logger.warning('Executing %s took %.3f seconds',
1385 _format_handle(handle), dt)
1386 finally:
1387 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001388 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001389 handle._run()
1390 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001391
Yury Selivanove8944cb2015-05-12 11:43:04 -04001392 def _set_coroutine_wrapper(self, enabled):
1393 try:
1394 set_wrapper = sys.set_coroutine_wrapper
1395 get_wrapper = sys.get_coroutine_wrapper
1396 except AttributeError:
1397 return
1398
1399 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001400 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001401 return
1402
1403 wrapper = coroutines.debug_wrapper
1404 current_wrapper = get_wrapper()
1405
1406 if enabled:
1407 if current_wrapper not in (None, wrapper):
1408 warnings.warn(
1409 "loop.set_debug(True): cannot set debug coroutine "
1410 "wrapper; another wrapper is already set %r" %
1411 current_wrapper, RuntimeWarning)
1412 else:
1413 set_wrapper(wrapper)
1414 self._coroutine_wrapper_set = True
1415 else:
1416 if current_wrapper not in (None, wrapper):
1417 warnings.warn(
1418 "loop.set_debug(False): cannot unset debug coroutine "
1419 "wrapper; another wrapper was set %r" %
1420 current_wrapper, RuntimeWarning)
1421 else:
1422 set_wrapper(None)
1423 self._coroutine_wrapper_set = False
1424
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001425 def get_debug(self):
1426 return self._debug
1427
1428 def set_debug(self, enabled):
1429 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001430
Yury Selivanove8944cb2015-05-12 11:43:04 -04001431 if self.is_running():
1432 self._set_coroutine_wrapper(enabled)