blob: b420586a13928bf351aa79d51d2ac5529d733953 [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 Selivanoveb636452016-09-08 22:01:51 -070030import 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 Selivanovd5c2a622015-12-16 19:31:17 -050079# Linux's sock.type is a bitmask that can include extra info about socket.
80_SOCKET_TYPE_MASK = 0
81if hasattr(socket, 'SOCK_NONBLOCK'):
82 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
83if hasattr(socket, 'SOCK_CLOEXEC'):
84 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
85
86
Yury Selivanovd5c2a622015-12-16 19:31:17 -050087def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040088 # Try to skip getaddrinfo if "host" is already an IP. Users might have
89 # handled name resolution in their own code and pass in resolved IPs.
90 if not hasattr(socket, 'inet_pton'):
91 return
92
93 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
94 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -050095 return None
96
97 type &= ~_SOCKET_TYPE_MASK
98 if type == socket.SOCK_STREAM:
99 proto = socket.IPPROTO_TCP
100 elif type == socket.SOCK_DGRAM:
101 proto = socket.IPPROTO_UDP
102 else:
103 return None
104
Yury Selivanova7146162016-06-02 16:51:07 -0400105 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400106 port = 0
Yury Selivanova7146162016-06-02 16:51:07 -0400107 elif isinstance(port, bytes):
108 if port == b'':
109 port = 0
110 else:
111 try:
112 port = int(port)
113 except ValueError:
114 # Might be a service name like b"http".
115 port = socket.getservbyname(port.decode('ascii'))
116 elif isinstance(port, str):
117 if port == '':
118 port = 0
119 else:
120 try:
121 port = int(port)
122 except ValueError:
123 # Might be a service name like "http".
124 port = socket.getservbyname(port)
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400125
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 if family == socket.AF_UNSPEC:
127 afs = [socket.AF_INET, socket.AF_INET6]
128 else:
129 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500130
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400131 if isinstance(host, bytes):
132 host = host.decode('idna')
133 if '%' in host:
134 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
135 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500136 return None
137
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500139 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 socket.inet_pton(af, host)
141 # The host has already been resolved.
142 return af, type, proto, '', (host, port)
143 except OSError:
144 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400146 # "host" is not an IP address.
147 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148
149
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
151 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500152 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400153 info = _ipaddr_info(host, port, family, type, proto)
154 if info is not None:
155 # "host" is already a resolved IP.
156 fut = loop.create_future()
157 fut.set_result([info])
158 return fut
159 else:
160 return loop.getaddrinfo(host, port, family=family, type=type,
161 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100162
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700163
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100164def _run_until_complete_cb(fut):
165 exc = fut._exception
166 if (isinstance(exc, BaseException)
167 and not isinstance(exc, Exception)):
168 # Issue #22429: run_forever() already finished, no need to
169 # stop it.
170 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800171 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100172
173
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174class Server(events.AbstractServer):
175
176 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200177 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700178 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200179 self._active_count = 0
180 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700181
Victor Stinnere912e652014-07-12 03:11:53 +0200182 def __repr__(self):
183 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
184
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200185 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 def _detach(self):
190 assert self._active_count > 0
191 self._active_count -= 1
192 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193 self._wakeup()
194
195 def close(self):
196 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 if sockets is None:
198 return
199 self.sockets = None
200 for sock in sockets:
201 self._loop._stop_serving(sock)
202 if self._active_count == 0:
203 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204
205 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 waiters = self._waiters
207 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208 for waiter in waiters:
209 if not waiter.done():
210 waiter.set_result(waiter)
211
Victor Stinnerf951d282014-06-29 00:46:45 +0200212 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200214 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700215 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400216 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 yield from waiter
219
220
221class BaseEventLoop(events.AbstractEventLoop):
222
223 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400224 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200225 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800226 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227 self._ready = collections.deque()
228 self._scheduled = []
229 self._default_executor = None
230 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100231 # Identifier of the thread running the event loop, or None if the
232 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100233 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100234 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500235 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400236 self.set_debug((not sys.flags.ignore_environment
237 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200238 # In debug mode, if the execution of a callback or a step of a task
239 # exceed this duration in seconds, the slow callback/task is logged.
240 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100241 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400242 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400243 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700244
Yury Selivanoveb636452016-09-08 22:01:51 -0700245 # A weak set of all asynchronous generators that are being iterated
246 # by the loop.
247 self._asyncgens = weakref.WeakSet()
248
249 # Set to True when `loop.shutdown_asyncgens` is called.
250 self._asyncgens_shutdown_called = False
251
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200252 def __repr__(self):
253 return ('<%s running=%s closed=%s debug=%s>'
254 % (self.__class__.__name__, self.is_running(),
255 self.is_closed(), self.get_debug()))
256
Yury Selivanov7661db62016-05-16 15:38:39 -0400257 def create_future(self):
258 """Create a Future object attached to the loop."""
259 return futures.Future(loop=self)
260
Victor Stinner896a25a2014-07-08 11:29:25 +0200261 def create_task(self, coro):
262 """Schedule a coroutine object.
263
Victor Stinneracdb7822014-07-14 18:33:40 +0200264 Return a task object.
265 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100266 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400267 if self._task_factory is None:
268 task = tasks.Task(coro, loop=self)
269 if task._source_traceback:
270 del task._source_traceback[-1]
271 else:
272 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200273 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200274
Yury Selivanov740169c2015-05-11 14:23:38 -0400275 def set_task_factory(self, factory):
276 """Set a task factory that will be used by loop.create_task().
277
278 If factory is None the default task factory will be set.
279
280 If factory is a callable, it should have a signature matching
281 '(loop, coro)', where 'loop' will be a reference to the active
282 event loop, 'coro' will be a coroutine object. The callable
283 must return a Future.
284 """
285 if factory is not None and not callable(factory):
286 raise TypeError('task factory must be a callable or None')
287 self._task_factory = factory
288
289 def get_task_factory(self):
290 """Return a task factory, or None if the default one is in use."""
291 return self._task_factory
292
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700293 def _make_socket_transport(self, sock, protocol, waiter=None, *,
294 extra=None, server=None):
295 """Create socket transport."""
296 raise NotImplementedError
297
Victor Stinner15cc6782015-01-09 00:09:10 +0100298 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
299 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700300 extra=None, server=None):
301 """Create SSL transport."""
302 raise NotImplementedError
303
304 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200305 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700306 """Create datagram transport."""
307 raise NotImplementedError
308
309 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
310 extra=None):
311 """Create read pipe transport."""
312 raise NotImplementedError
313
314 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
315 extra=None):
316 """Create write pipe transport."""
317 raise NotImplementedError
318
Victor Stinnerf951d282014-06-29 00:46:45 +0200319 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700320 def _make_subprocess_transport(self, protocol, args, shell,
321 stdin, stdout, stderr, bufsize,
322 extra=None, **kwargs):
323 """Create subprocess transport."""
324 raise NotImplementedError
325
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700326 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200327 """Write a byte to self-pipe, to wake up the event loop.
328
329 This may be called from a different thread.
330
331 The subclass is responsible for implementing the self-pipe.
332 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700333 raise NotImplementedError
334
335 def _process_events(self, event_list):
336 """Process selector events."""
337 raise NotImplementedError
338
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200339 def _check_closed(self):
340 if self._closed:
341 raise RuntimeError('Event loop is closed')
342
Yury Selivanoveb636452016-09-08 22:01:51 -0700343 def _asyncgen_finalizer_hook(self, agen):
344 self._asyncgens.discard(agen)
345 if not self.is_closed():
346 self.create_task(agen.aclose())
347
348 def _asyncgen_firstiter_hook(self, agen):
349 if self._asyncgens_shutdown_called:
350 warnings.warn(
351 "asynchronous generator {!r} was scheduled after "
352 "loop.shutdown_asyncgens() call".format(agen),
353 ResourceWarning, source=self)
354
355 self._asyncgens.add(agen)
356
357 @coroutine
358 def shutdown_asyncgens(self):
359 """Shutdown all active asynchronous generators."""
360 self._asyncgens_shutdown_called = True
361
362 if not len(self._asyncgens):
363 return
364
365 closing_agens = list(self._asyncgens)
366 self._asyncgens.clear()
367
368 shutdown_coro = tasks.gather(
369 *[ag.aclose() for ag in closing_agens],
370 return_exceptions=True,
371 loop=self)
372
373 results = yield from shutdown_coro
374 for result, agen in zip(results, closing_agens):
375 if isinstance(result, Exception):
376 self.call_exception_handler({
377 'message': 'an error occurred during closing of '
378 'asynchronous generator {!r}'.format(agen),
379 'exception': result,
380 'asyncgen': agen
381 })
382
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700383 def run_forever(self):
384 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200385 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100386 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700387 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400388 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100389 self._thread_id = threading.get_ident()
Yury Selivanoveb636452016-09-08 22:01:51 -0700390 old_agen_hooks = sys.get_asyncgen_hooks()
391 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
392 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700393 try:
394 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800395 self._run_once()
396 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700397 break
398 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800399 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100400 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400401 self._set_coroutine_wrapper(False)
Yury Selivanoveb636452016-09-08 22:01:51 -0700402 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700403
404 def run_until_complete(self, future):
405 """Run until the Future is done.
406
407 If the argument is a coroutine, it is wrapped in a Task.
408
Victor Stinneracdb7822014-07-14 18:33:40 +0200409 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700410 with the same coroutine twice -- it would wrap it in two
411 different Tasks and that can't be good.
412
413 Return the Future's result, or raise its exception.
414 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200415 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200416
417 new_task = not isinstance(future, futures.Future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400418 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200419 if new_task:
420 # An exception is raised if the future didn't complete, so there
421 # is no need to log the "destroy pending task" message
422 future._log_destroy_pending = False
423
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100424 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200425 try:
426 self.run_forever()
427 except:
428 if new_task and future.done() and not future.cancelled():
429 # The coroutine raised a BaseException. Consume the exception
430 # to not log a warning, the caller doesn't have access to the
431 # local task.
432 future.exception()
433 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100434 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700435 if not future.done():
436 raise RuntimeError('Event loop stopped before Future completed.')
437
438 return future.result()
439
440 def stop(self):
441 """Stop running the event loop.
442
Guido van Rossum41f69f42015-11-19 13:28:47 -0800443 Every callback already scheduled will still run. This simply informs
444 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700445 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800446 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200448 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700449 """Close the event loop.
450
451 This clears the queues and shuts down the executor,
452 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200453
454 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700455 """
Victor Stinner956de692014-12-26 21:07:52 +0100456 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200457 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200458 if self._closed:
459 return
Victor Stinnere912e652014-07-12 03:11:53 +0200460 if self._debug:
461 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400462 self._closed = True
463 self._ready.clear()
464 self._scheduled.clear()
465 executor = self._default_executor
466 if executor is not None:
467 self._default_executor = None
468 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200469
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200470 def is_closed(self):
471 """Returns True if the event loop was closed."""
472 return self._closed
473
Victor Stinner978a9af2015-01-29 17:50:58 +0100474 # On Python 3.3 and older, objects with a destructor part of a reference
475 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
476 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400477 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100478 def __del__(self):
479 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100480 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
481 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100482 if not self.is_running():
483 self.close()
484
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700485 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200486 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100487 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700488
489 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200490 """Return the time according to the event loop's clock.
491
492 This is a float expressed in seconds since an epoch, but the
493 epoch, precision, accuracy and drift are unspecified and may
494 differ per event loop.
495 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700496 return time.monotonic()
497
498 def call_later(self, delay, callback, *args):
499 """Arrange for a callback to be called at a given time.
500
501 Return a Handle: an opaque object with a cancel() method that
502 can be used to cancel the call.
503
504 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200505 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506
507 Each callback will be called exactly once. If two callbacks
508 are scheduled for exactly the same time, it undefined which
509 will be called first.
510
511 Any positional arguments after the callback will be passed to
512 the callback when it is called.
513 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200514 timer = self.call_at(self.time() + delay, callback, *args)
515 if timer._source_traceback:
516 del timer._source_traceback[-1]
517 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700518
519 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200520 """Like call_later(), but uses an absolute time.
521
522 Absolute time corresponds to the event loop's time() method.
523 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100524 if (coroutines.iscoroutine(callback)
525 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100526 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100527 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100528 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100529 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500530 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200531 if timer._source_traceback:
532 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400534 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535 return timer
536
537 def call_soon(self, callback, *args):
538 """Arrange for a callback to be called as soon as possible.
539
Victor Stinneracdb7822014-07-14 18:33:40 +0200540 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700541 order in which they are registered. Each callback will be
542 called exactly once.
543
544 Any positional arguments after the callback will be passed to
545 the callback when it is called.
546 """
Victor Stinner956de692014-12-26 21:07:52 +0100547 if self._debug:
548 self._check_thread()
549 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200550 if handle._source_traceback:
551 del handle._source_traceback[-1]
552 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100553
Victor Stinner956de692014-12-26 21:07:52 +0100554 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100555 if (coroutines.iscoroutine(callback)
556 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100557 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100558 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500559 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200560 if handle._source_traceback:
561 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562 self._ready.append(handle)
563 return handle
564
Victor Stinner956de692014-12-26 21:07:52 +0100565 def _check_thread(self):
566 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100567
Victor Stinneracdb7822014-07-14 18:33:40 +0200568 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100569 likely behave incorrectly when the assumption is violated.
570
Victor Stinneracdb7822014-07-14 18:33:40 +0200571 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100572 responsible for checking this condition for performance reasons.
573 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100574 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200575 return
Victor Stinner956de692014-12-26 21:07:52 +0100576 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100577 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100578 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200579 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100580 "than the current one")
581
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700582 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200583 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100584 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200585 if handle._source_traceback:
586 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587 self._write_to_self()
588 return handle
589
Yury Selivanov740169c2015-05-11 14:23:38 -0400590 def run_in_executor(self, executor, func, *args):
591 if (coroutines.iscoroutine(func)
592 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100593 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100594 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400595 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700596 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400597 assert not isinstance(func, events.TimerHandle)
598 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400599 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600 f.set_result(None)
601 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400602 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700603 if executor is None:
604 executor = self._default_executor
605 if executor is None:
606 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
607 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400608 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700609
610 def set_default_executor(self, executor):
611 self._default_executor = executor
612
Victor Stinnere912e652014-07-12 03:11:53 +0200613 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
614 msg = ["%s:%r" % (host, port)]
615 if family:
616 msg.append('family=%r' % family)
617 if type:
618 msg.append('type=%r' % type)
619 if proto:
620 msg.append('proto=%r' % proto)
621 if flags:
622 msg.append('flags=%r' % flags)
623 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200624 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200625
626 t0 = self.time()
627 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
628 dt = self.time() - t0
629
Victor Stinneracdb7822014-07-14 18:33:40 +0200630 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200631 % (msg, dt * 1e3, addrinfo))
632 if dt >= self.slow_callback_duration:
633 logger.info(msg)
634 else:
635 logger.debug(msg)
636 return addrinfo
637
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700638 def getaddrinfo(self, host, port, *,
639 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400640 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200641 return self.run_in_executor(None, self._getaddrinfo_debug,
642 host, port, family, type, proto, flags)
643 else:
644 return self.run_in_executor(None, socket.getaddrinfo,
645 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646
647 def getnameinfo(self, sockaddr, flags=0):
648 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
649
Victor Stinnerf951d282014-06-29 00:46:45 +0200650 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700651 def create_connection(self, protocol_factory, host=None, port=None, *,
652 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700653 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200654 """Connect to a TCP server.
655
656 Create a streaming transport connection to a given Internet host and
657 port: socket family AF_INET or socket.AF_INET6 depending on host (or
658 family if specified), socket type SOCK_STREAM. protocol_factory must be
659 a callable returning a protocol instance.
660
661 This method is a coroutine which will try to establish the connection
662 in the background. When successful, the coroutine returns a
663 (transport, protocol) pair.
664 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700665 if server_hostname is not None and not ssl:
666 raise ValueError('server_hostname is only meaningful with ssl')
667
668 if server_hostname is None and ssl:
669 # Use host as default for server_hostname. It is an error
670 # if host is empty or not set, e.g. when an
671 # already-connected socket was passed or when only a port
672 # is given. To avoid this error, you can pass
673 # server_hostname='' -- this will bypass the hostname
674 # check. (This also means that if host is a numeric
675 # IP/IPv6 address, we will attempt to verify that exact
676 # address; this will probably fail, but it is possible to
677 # create a certificate for a specific IP address, so we
678 # don't judge it here.)
679 if not host:
680 raise ValueError('You must set server_hostname '
681 'when using ssl without a host')
682 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700683
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700684 if host is not None or port is not None:
685 if sock is not None:
686 raise ValueError(
687 'host/port and sock can not be specified at the same time')
688
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400689 f1 = _ensure_resolved((host, port), family=family,
690 type=socket.SOCK_STREAM, proto=proto,
691 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700692 fs = [f1]
693 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400694 f2 = _ensure_resolved(local_addr, family=family,
695 type=socket.SOCK_STREAM, proto=proto,
696 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700697 fs.append(f2)
698 else:
699 f2 = None
700
701 yield from tasks.wait(fs, loop=self)
702
703 infos = f1.result()
704 if not infos:
705 raise OSError('getaddrinfo() returned empty list')
706 if f2 is not None:
707 laddr_infos = f2.result()
708 if not laddr_infos:
709 raise OSError('getaddrinfo() returned empty list')
710
711 exceptions = []
712 for family, type, proto, cname, address in infos:
713 try:
714 sock = socket.socket(family=family, type=type, proto=proto)
715 sock.setblocking(False)
716 if f2 is not None:
717 for _, _, _, _, laddr in laddr_infos:
718 try:
719 sock.bind(laddr)
720 break
721 except OSError as exc:
722 exc = OSError(
723 exc.errno, 'error while '
724 'attempting to bind on address '
725 '{!r}: {}'.format(
726 laddr, exc.strerror.lower()))
727 exceptions.append(exc)
728 else:
729 sock.close()
730 sock = None
731 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200732 if self._debug:
733 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 yield from self.sock_connect(sock, address)
735 except OSError as exc:
736 if sock is not None:
737 sock.close()
738 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200739 except:
740 if sock is not None:
741 sock.close()
742 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700743 else:
744 break
745 else:
746 if len(exceptions) == 1:
747 raise exceptions[0]
748 else:
749 # If they all have the same str(), raise one.
750 model = str(exceptions[0])
751 if all(str(exc) == model for exc in exceptions):
752 raise exceptions[0]
753 # Raise a combined exception so the user can see all
754 # the various error messages.
755 raise OSError('Multiple exceptions: {}'.format(
756 ', '.join(str(exc) for exc in exceptions)))
757
758 elif sock is None:
759 raise ValueError(
760 'host and port was not specified and no sock specified')
761
Yury Selivanovb057c522014-02-18 12:15:06 -0500762 transport, protocol = yield from self._create_connection_transport(
763 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200764 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200765 # Get the socket from the transport because SSL transport closes
766 # the old socket and creates a new SSL socket
767 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200768 logger.debug("%r connected to %s:%r: (%r, %r)",
769 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500770 return transport, protocol
771
Victor Stinnerf951d282014-06-29 00:46:45 +0200772 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500773 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400774 server_hostname, server_side=False):
775
776 sock.setblocking(False)
777
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700778 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400779 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700780 if ssl:
781 sslcontext = None if isinstance(ssl, bool) else ssl
782 transport = self._make_ssl_transport(
783 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400784 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700785 else:
786 transport = self._make_socket_transport(sock, protocol, waiter)
787
Victor Stinner29ad0112015-01-15 00:04:21 +0100788 try:
789 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100790 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100791 transport.close()
792 raise
793
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700794 return transport, protocol
795
Victor Stinnerf951d282014-06-29 00:46:45 +0200796 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700797 def create_datagram_endpoint(self, protocol_factory,
798 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700799 family=0, proto=0, flags=0,
800 reuse_address=None, reuse_port=None,
801 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700802 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700803 if sock is not None:
804 if (local_addr or remote_addr or
805 family or proto or flags or
806 reuse_address or reuse_port or allow_broadcast):
807 # show the problematic kwargs in exception msg
808 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
809 family=family, proto=proto, flags=flags,
810 reuse_address=reuse_address, reuse_port=reuse_port,
811 allow_broadcast=allow_broadcast)
812 problems = ', '.join(
813 '{}={}'.format(k, v) for k, v in opts.items() if v)
814 raise ValueError(
815 'socket modifier keyword arguments can not be used '
816 'when sock is specified. ({})'.format(problems))
817 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700818 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700819 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700820 if not (local_addr or remote_addr):
821 if family == 0:
822 raise ValueError('unexpected address family')
823 addr_pairs_info = (((family, proto), (None, None)),)
824 else:
825 # join address by (family, protocol)
826 addr_infos = collections.OrderedDict()
827 for idx, addr in ((0, local_addr), (1, remote_addr)):
828 if addr is not None:
829 assert isinstance(addr, tuple) and len(addr) == 2, (
830 '2-tuple is expected')
831
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400832 infos = yield from _ensure_resolved(
833 addr, family=family, type=socket.SOCK_DGRAM,
834 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700835 if not infos:
836 raise OSError('getaddrinfo() returned empty list')
837
838 for fam, _, pro, _, address in infos:
839 key = (fam, pro)
840 if key not in addr_infos:
841 addr_infos[key] = [None, None]
842 addr_infos[key][idx] = address
843
844 # each addr has to have info for each (family, proto) pair
845 addr_pairs_info = [
846 (key, addr_pair) for key, addr_pair in addr_infos.items()
847 if not ((local_addr and addr_pair[0] is None) or
848 (remote_addr and addr_pair[1] is None))]
849
850 if not addr_pairs_info:
851 raise ValueError('can not get address information')
852
853 exceptions = []
854
855 if reuse_address is None:
856 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
857
858 for ((family, proto),
859 (local_address, remote_address)) in addr_pairs_info:
860 sock = None
861 r_addr = None
862 try:
863 sock = socket.socket(
864 family=family, type=socket.SOCK_DGRAM, proto=proto)
865 if reuse_address:
866 sock.setsockopt(
867 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
868 if reuse_port:
869 if not hasattr(socket, 'SO_REUSEPORT'):
870 raise ValueError(
871 'reuse_port not supported by socket module')
872 else:
873 sock.setsockopt(
874 socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
875 if allow_broadcast:
876 sock.setsockopt(
877 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
878 sock.setblocking(False)
879
880 if local_addr:
881 sock.bind(local_address)
882 if remote_addr:
883 yield from self.sock_connect(sock, remote_address)
884 r_addr = remote_address
885 except OSError as exc:
886 if sock is not None:
887 sock.close()
888 exceptions.append(exc)
889 except:
890 if sock is not None:
891 sock.close()
892 raise
893 else:
894 break
895 else:
896 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700897
898 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400899 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700900 transport = self._make_datagram_transport(
901 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200902 if self._debug:
903 if local_addr:
904 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
905 "created: (%r, %r)",
906 local_addr, remote_addr, transport, protocol)
907 else:
908 logger.debug("Datagram endpoint remote_addr=%r created: "
909 "(%r, %r)",
910 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100911
912 try:
913 yield from waiter
914 except:
915 transport.close()
916 raise
917
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700918 return transport, protocol
919
Victor Stinnerf951d282014-06-29 00:46:45 +0200920 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200921 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400922 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200923 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400924 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200925 if not infos:
926 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
927 return infos
928
929 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700930 def create_server(self, protocol_factory, host=None, port=None,
931 *,
932 family=socket.AF_UNSPEC,
933 flags=socket.AI_PASSIVE,
934 sock=None,
935 backlog=100,
936 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700937 reuse_address=None,
938 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200939 """Create a TCP server.
940
941 The host parameter can be a string, in that case the TCP server is bound
942 to host and port.
943
944 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500945 the TCP server is bound to all hosts of the sequence. If a host
946 appears multiple times (possibly indirectly e.g. when hostnames
947 resolve to the same IP address), the server is only bound once to that
948 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200949
Victor Stinneracdb7822014-07-14 18:33:40 +0200950 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200951
952 This method is a coroutine.
953 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700954 if isinstance(ssl, bool):
955 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700956 if host is not None or port is not None:
957 if sock is not None:
958 raise ValueError(
959 'host/port and sock can not be specified at the same time')
960
961 AF_INET6 = getattr(socket, 'AF_INET6', 0)
962 if reuse_address is None:
963 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
964 sockets = []
965 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200966 hosts = [None]
967 elif (isinstance(host, str) or
968 not isinstance(host, collections.Iterable)):
969 hosts = [host]
970 else:
971 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700972
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200973 fs = [self._create_server_getaddrinfo(host, port, family=family,
974 flags=flags)
975 for host in hosts]
976 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500977 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700978
979 completed = False
980 try:
981 for res in infos:
982 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700983 try:
984 sock = socket.socket(af, socktype, proto)
985 except socket.error:
986 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200987 if self._debug:
988 logger.warning('create_server() failed to create '
989 'socket.socket(%r, %r, %r)',
990 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700991 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700992 sockets.append(sock)
993 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700994 sock.setsockopt(
995 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
996 if reuse_port:
997 if not hasattr(socket, 'SO_REUSEPORT'):
998 raise ValueError(
999 'reuse_port not supported by socket module')
1000 else:
1001 sock.setsockopt(
1002 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001003 # Disable IPv4/IPv6 dual stack support (enabled by
1004 # default on Linux) which makes a single socket
1005 # listen on both address families.
1006 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1007 sock.setsockopt(socket.IPPROTO_IPV6,
1008 socket.IPV6_V6ONLY,
1009 True)
1010 try:
1011 sock.bind(sa)
1012 except OSError as err:
1013 raise OSError(err.errno, 'error while attempting '
1014 'to bind on address %r: %s'
1015 % (sa, err.strerror.lower()))
1016 completed = True
1017 finally:
1018 if not completed:
1019 for sock in sockets:
1020 sock.close()
1021 else:
1022 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001023 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001024 sockets = [sock]
1025
1026 server = Server(self, sockets)
1027 for sock in sockets:
1028 sock.listen(backlog)
1029 sock.setblocking(False)
1030 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +02001031 if self._debug:
1032 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001033 return server
1034
Victor Stinnerf951d282014-06-29 00:46:45 +02001035 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001036 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1037 """Handle an accepted connection.
1038
1039 This is used by servers that accept connections outside of
1040 asyncio but that use asyncio to handle connections.
1041
1042 This method is a coroutine. When completed, the coroutine
1043 returns a (transport, protocol) pair.
1044 """
1045 transport, protocol = yield from self._create_connection_transport(
1046 sock, protocol_factory, ssl, '', server_side=True)
1047 if self._debug:
1048 # Get the socket from the transport because SSL transport closes
1049 # the old socket and creates a new SSL socket
1050 sock = transport.get_extra_info('socket')
1051 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1052 return transport, protocol
1053
1054 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001055 def connect_read_pipe(self, protocol_factory, pipe):
1056 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001057 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001058 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001059
1060 try:
1061 yield from waiter
1062 except:
1063 transport.close()
1064 raise
1065
Victor Stinneracdb7822014-07-14 18:33:40 +02001066 if self._debug:
1067 logger.debug('Read pipe %r connected: (%r, %r)',
1068 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001069 return transport, protocol
1070
Victor Stinnerf951d282014-06-29 00:46:45 +02001071 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001072 def connect_write_pipe(self, protocol_factory, pipe):
1073 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001074 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001075 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001076
1077 try:
1078 yield from waiter
1079 except:
1080 transport.close()
1081 raise
1082
Victor Stinneracdb7822014-07-14 18:33:40 +02001083 if self._debug:
1084 logger.debug('Write pipe %r connected: (%r, %r)',
1085 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001086 return transport, protocol
1087
Victor Stinneracdb7822014-07-14 18:33:40 +02001088 def _log_subprocess(self, msg, stdin, stdout, stderr):
1089 info = [msg]
1090 if stdin is not None:
1091 info.append('stdin=%s' % _format_pipe(stdin))
1092 if stdout is not None and stderr == subprocess.STDOUT:
1093 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1094 else:
1095 if stdout is not None:
1096 info.append('stdout=%s' % _format_pipe(stdout))
1097 if stderr is not None:
1098 info.append('stderr=%s' % _format_pipe(stderr))
1099 logger.debug(' '.join(info))
1100
Victor Stinnerf951d282014-06-29 00:46:45 +02001101 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001102 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1103 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1104 universal_newlines=False, shell=True, bufsize=0,
1105 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001106 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001107 raise ValueError("cmd must be a string")
1108 if universal_newlines:
1109 raise ValueError("universal_newlines must be False")
1110 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001111 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001112 if bufsize != 0:
1113 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001114 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001115 if self._debug:
1116 # don't log parameters: they may contain sensitive information
1117 # (password) and may be too long
1118 debug_log = 'run shell command %r' % cmd
1119 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001120 transport = yield from self._make_subprocess_transport(
1121 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001122 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001123 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001124 return transport, protocol
1125
Victor Stinnerf951d282014-06-29 00:46:45 +02001126 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001127 def subprocess_exec(self, protocol_factory, program, *args,
1128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1129 stderr=subprocess.PIPE, universal_newlines=False,
1130 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001131 if universal_newlines:
1132 raise ValueError("universal_newlines must be False")
1133 if shell:
1134 raise ValueError("shell must be False")
1135 if bufsize != 0:
1136 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001137 popen_args = (program,) + args
1138 for arg in popen_args:
1139 if not isinstance(arg, (str, bytes)):
1140 raise TypeError("program arguments must be "
1141 "a bytes or text string, not %s"
1142 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001143 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001144 if self._debug:
1145 # don't log parameters: they may contain sensitive information
1146 # (password) and may be too long
1147 debug_log = 'execute program %r' % program
1148 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001149 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001150 protocol, popen_args, False, stdin, stdout, stderr,
1151 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001152 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001153 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001154 return transport, protocol
1155
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001156 def get_exception_handler(self):
1157 """Return an exception handler, or None if the default one is in use.
1158 """
1159 return self._exception_handler
1160
Yury Selivanov569efa22014-02-18 18:02:19 -05001161 def set_exception_handler(self, handler):
1162 """Set handler as the new event loop exception handler.
1163
1164 If handler is None, the default exception handler will
1165 be set.
1166
1167 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001168 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001169 will be a reference to the active event loop, 'context'
1170 will be a dict object (see `call_exception_handler()`
1171 documentation for details about context).
1172 """
1173 if handler is not None and not callable(handler):
1174 raise TypeError('A callable object or None is expected, '
1175 'got {!r}'.format(handler))
1176 self._exception_handler = handler
1177
1178 def default_exception_handler(self, context):
1179 """Default exception handler.
1180
1181 This is called when an exception occurs and no exception
1182 handler is set, and can be called by a custom exception
1183 handler that wants to defer to the default behavior.
1184
Victor Stinneracdb7822014-07-14 18:33:40 +02001185 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001186 `call_exception_handler()`.
1187 """
1188 message = context.get('message')
1189 if not message:
1190 message = 'Unhandled exception in event loop'
1191
1192 exception = context.get('exception')
1193 if exception is not None:
1194 exc_info = (type(exception), exception, exception.__traceback__)
1195 else:
1196 exc_info = False
1197
Victor Stinnerff018e42015-01-28 00:30:40 +01001198 if ('source_traceback' not in context
1199 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001200 and self._current_handle._source_traceback):
1201 context['handle_traceback'] = self._current_handle._source_traceback
1202
Yury Selivanov569efa22014-02-18 18:02:19 -05001203 log_lines = [message]
1204 for key in sorted(context):
1205 if key in {'message', 'exception'}:
1206 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001207 value = context[key]
1208 if key == 'source_traceback':
1209 tb = ''.join(traceback.format_list(value))
1210 value = 'Object created at (most recent call last):\n'
1211 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001212 elif key == 'handle_traceback':
1213 tb = ''.join(traceback.format_list(value))
1214 value = 'Handle created at (most recent call last):\n'
1215 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001216 else:
1217 value = repr(value)
1218 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001219
1220 logger.error('\n'.join(log_lines), exc_info=exc_info)
1221
1222 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001223 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001224
Victor Stinneracdb7822014-07-14 18:33:40 +02001225 The context argument is a dict containing the following keys:
1226
Yury Selivanov569efa22014-02-18 18:02:19 -05001227 - 'message': Error message;
1228 - 'exception' (optional): Exception object;
1229 - 'future' (optional): Future instance;
1230 - 'handle' (optional): Handle instance;
1231 - 'protocol' (optional): Protocol instance;
1232 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001233 - 'socket' (optional): Socket instance;
1234 - 'asyncgen' (optional): Asynchronous generator that caused
1235 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001236
Victor Stinneracdb7822014-07-14 18:33:40 +02001237 New keys maybe introduced in the future.
1238
1239 Note: do not overload this method in an event loop subclass.
1240 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001241 `set_exception_handler()` method.
1242 """
1243 if self._exception_handler is None:
1244 try:
1245 self.default_exception_handler(context)
1246 except Exception:
1247 # Second protection layer for unexpected errors
1248 # in the default implementation, as well as for subclassed
1249 # event loops with overloaded "default_exception_handler".
1250 logger.error('Exception in default exception handler',
1251 exc_info=True)
1252 else:
1253 try:
1254 self._exception_handler(self, context)
1255 except Exception as exc:
1256 # Exception in the user set custom exception handler.
1257 try:
1258 # Let's try default handler.
1259 self.default_exception_handler({
1260 'message': 'Unhandled error in exception handler',
1261 'exception': exc,
1262 'context': context,
1263 })
1264 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001265 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001266 # overloaded.
1267 logger.error('Exception in default exception handler '
1268 'while handling an unexpected error '
1269 'in custom exception handler',
1270 exc_info=True)
1271
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001272 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001273 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001274 assert isinstance(handle, events.Handle), 'A Handle is required here'
1275 if handle._cancelled:
1276 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001277 assert not isinstance(handle, events.TimerHandle)
1278 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001279
1280 def _add_callback_signalsafe(self, handle):
1281 """Like _add_callback() but called from a signal handler."""
1282 self._add_callback(handle)
1283 self._write_to_self()
1284
Yury Selivanov592ada92014-09-25 12:07:56 -04001285 def _timer_handle_cancelled(self, handle):
1286 """Notification that a TimerHandle has been cancelled."""
1287 if handle._scheduled:
1288 self._timer_cancelled_count += 1
1289
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001290 def _run_once(self):
1291 """Run one full iteration of the event loop.
1292
1293 This calls all currently ready callbacks, polls for I/O,
1294 schedules the resulting callbacks, and finally schedules
1295 'call_later' callbacks.
1296 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001297
Yury Selivanov592ada92014-09-25 12:07:56 -04001298 sched_count = len(self._scheduled)
1299 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1300 self._timer_cancelled_count / sched_count >
1301 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001302 # Remove delayed calls that were cancelled if their number
1303 # is too high
1304 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001305 for handle in self._scheduled:
1306 if handle._cancelled:
1307 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001308 else:
1309 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001310
Victor Stinner68da8fc2014-09-30 18:08:36 +02001311 heapq.heapify(new_scheduled)
1312 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001313 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001314 else:
1315 # Remove delayed calls that were cancelled from head of queue.
1316 while self._scheduled and self._scheduled[0]._cancelled:
1317 self._timer_cancelled_count -= 1
1318 handle = heapq.heappop(self._scheduled)
1319 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001320
1321 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001322 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323 timeout = 0
1324 elif self._scheduled:
1325 # Compute the desired timeout.
1326 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001327 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001328
Victor Stinner770e48d2014-07-11 11:58:33 +02001329 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001330 t0 = self.time()
1331 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001332 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001333 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001334 level = logging.INFO
1335 else:
1336 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001337 nevent = len(event_list)
1338 if timeout is None:
1339 logger.log(level, 'poll took %.3f ms: %s events',
1340 dt * 1e3, nevent)
1341 elif nevent:
1342 logger.log(level,
1343 'poll %.3f ms took %.3f ms: %s events',
1344 timeout * 1e3, dt * 1e3, nevent)
1345 elif dt >= 1.0:
1346 logger.log(level,
1347 'poll %.3f ms took %.3f ms: timeout',
1348 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001349 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001350 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001351 self._process_events(event_list)
1352
1353 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001354 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001355 while self._scheduled:
1356 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001357 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001358 break
1359 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001360 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001361 self._ready.append(handle)
1362
1363 # This is the only place where callbacks are actually *called*.
1364 # All other places just add them to ready.
1365 # Note: We run all currently scheduled callbacks, but not any
1366 # callbacks scheduled by callbacks run this time around --
1367 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001368 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001369 ntodo = len(self._ready)
1370 for i in range(ntodo):
1371 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001372 if handle._cancelled:
1373 continue
1374 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001375 try:
1376 self._current_handle = handle
1377 t0 = self.time()
1378 handle._run()
1379 dt = self.time() - t0
1380 if dt >= self.slow_callback_duration:
1381 logger.warning('Executing %s took %.3f seconds',
1382 _format_handle(handle), dt)
1383 finally:
1384 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001385 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001386 handle._run()
1387 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001388
Yury Selivanove8944cb2015-05-12 11:43:04 -04001389 def _set_coroutine_wrapper(self, enabled):
1390 try:
1391 set_wrapper = sys.set_coroutine_wrapper
1392 get_wrapper = sys.get_coroutine_wrapper
1393 except AttributeError:
1394 return
1395
1396 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001397 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001398 return
1399
1400 wrapper = coroutines.debug_wrapper
1401 current_wrapper = get_wrapper()
1402
1403 if enabled:
1404 if current_wrapper not in (None, wrapper):
1405 warnings.warn(
1406 "loop.set_debug(True): cannot set debug coroutine "
1407 "wrapper; another wrapper is already set %r" %
1408 current_wrapper, RuntimeWarning)
1409 else:
1410 set_wrapper(wrapper)
1411 self._coroutine_wrapper_set = True
1412 else:
1413 if current_wrapper not in (None, wrapper):
1414 warnings.warn(
1415 "loop.set_debug(False): cannot unset debug coroutine "
1416 "wrapper; another wrapper was set %r" %
1417 current_wrapper, RuntimeWarning)
1418 else:
1419 set_wrapper(None)
1420 self._coroutine_wrapper_set = False
1421
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001422 def get_debug(self):
1423 return self._debug
1424
1425 def set_debug(self, enabled):
1426 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001427
Yury Selivanove8944cb2015-05-12 11:43:04 -04001428 if self.is_running():
1429 self._set_coroutine_wrapper(enabled)