blob: 6488f23d3c89595af99efdd2167b49011b260d82 [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
Yury Selivanov592ada92014-09-25 12:07:56 -040044# Minimum number of _scheduled timer handles before cleanup of
45# cancelled handles is performed.
46_MIN_SCHEDULED_TIMER_HANDLES = 100
47
48# Minimum fraction of _scheduled timer handles that are cancelled
49# before cleanup of cancelled handles is performed.
50_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051
Victor Stinnerc94a93a2016-04-01 21:43:39 +020052# Exceptions which must not call the exception handler in fatal error
53# methods (_fatal_error())
54_FATAL_ERROR_IGNORE = (BrokenPipeError,
55 ConnectionResetError, ConnectionAbortedError)
56
57
Victor Stinner0e6f52a2014-06-20 17:34:15 +020058def _format_handle(handle):
59 cb = handle._callback
60 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
61 # format the task
62 return repr(cb.__self__)
63 else:
64 return str(handle)
65
66
Victor Stinneracdb7822014-07-14 18:33:40 +020067def _format_pipe(fd):
68 if fd == subprocess.PIPE:
69 return '<pipe>'
70 elif fd == subprocess.STDOUT:
71 return '<stdout>'
72 else:
73 return repr(fd)
74
75
Yury Selivanov5587d7c2016-09-15 15:45:07 -040076def _set_reuseport(sock):
77 if not hasattr(socket, 'SO_REUSEPORT'):
78 raise ValueError('reuse_port not supported by socket module')
79 else:
80 try:
81 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
82 except OSError:
83 raise ValueError('reuse_port not supported by socket module, '
84 'SO_REUSEPORT defined but not implemented.')
85
86
Yury Selivanovd5c2a622015-12-16 19:31:17 -050087# Linux's sock.type is a bitmask that can include extra info about socket.
88_SOCKET_TYPE_MASK = 0
89if hasattr(socket, 'SOCK_NONBLOCK'):
90 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
91if hasattr(socket, 'SOCK_CLOEXEC'):
92 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
93
94
Yury Selivanovd5c2a622015-12-16 19:31:17 -050095def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040096 # Try to skip getaddrinfo if "host" is already an IP. Users might have
97 # handled name resolution in their own code and pass in resolved IPs.
98 if not hasattr(socket, 'inet_pton'):
99 return
100
101 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
102 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500103 return None
104
105 type &= ~_SOCKET_TYPE_MASK
106 if type == socket.SOCK_STREAM:
107 proto = socket.IPPROTO_TCP
108 elif type == socket.SOCK_DGRAM:
109 proto = socket.IPPROTO_UDP
110 else:
111 return None
112
Yury Selivanova7146162016-06-02 16:51:07 -0400113 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400114 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700115 elif isinstance(port, bytes) and port == b'':
116 port = 0
117 elif isinstance(port, str) and port == '':
118 port = 0
119 else:
120 # If port's a service name like "http", don't skip getaddrinfo.
121 try:
122 port = int(port)
123 except (TypeError, ValueError):
124 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400125
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 if family == socket.AF_UNSPEC:
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 Selivanovf6d991d2016-09-15 13:10:51 -0400245 if hasattr(sys, 'get_asyncgen_hooks'):
246 # Python >= 3.6
247 # A weak set of all asynchronous generators that are
248 # being iterated by the loop.
249 self._asyncgens = weakref.WeakSet()
250 else:
251 self._asyncgens = None
252
253 # Set to True when `loop.shutdown_asyncgens` is called.
254 self._asyncgens_shutdown_called = False
255
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200256 def __repr__(self):
257 return ('<%s running=%s closed=%s debug=%s>'
258 % (self.__class__.__name__, self.is_running(),
259 self.is_closed(), self.get_debug()))
260
Yury Selivanov7661db62016-05-16 15:38:39 -0400261 def create_future(self):
262 """Create a Future object attached to the loop."""
263 return futures.Future(loop=self)
264
Victor Stinner896a25a2014-07-08 11:29:25 +0200265 def create_task(self, coro):
266 """Schedule a coroutine object.
267
Victor Stinneracdb7822014-07-14 18:33:40 +0200268 Return a task object.
269 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100270 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400271 if self._task_factory is None:
272 task = tasks.Task(coro, loop=self)
273 if task._source_traceback:
274 del task._source_traceback[-1]
275 else:
276 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200277 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200278
Yury Selivanov740169c2015-05-11 14:23:38 -0400279 def set_task_factory(self, factory):
280 """Set a task factory that will be used by loop.create_task().
281
282 If factory is None the default task factory will be set.
283
284 If factory is a callable, it should have a signature matching
285 '(loop, coro)', where 'loop' will be a reference to the active
286 event loop, 'coro' will be a coroutine object. The callable
287 must return a Future.
288 """
289 if factory is not None and not callable(factory):
290 raise TypeError('task factory must be a callable or None')
291 self._task_factory = factory
292
293 def get_task_factory(self):
294 """Return a task factory, or None if the default one is in use."""
295 return self._task_factory
296
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 def _make_socket_transport(self, sock, protocol, waiter=None, *,
298 extra=None, server=None):
299 """Create socket transport."""
300 raise NotImplementedError
301
Victor Stinner15cc6782015-01-09 00:09:10 +0100302 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
303 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700304 extra=None, server=None):
305 """Create SSL transport."""
306 raise NotImplementedError
307
308 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200309 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700310 """Create datagram transport."""
311 raise NotImplementedError
312
313 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
314 extra=None):
315 """Create read pipe transport."""
316 raise NotImplementedError
317
318 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
319 extra=None):
320 """Create write pipe transport."""
321 raise NotImplementedError
322
Victor Stinnerf951d282014-06-29 00:46:45 +0200323 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700324 def _make_subprocess_transport(self, protocol, args, shell,
325 stdin, stdout, stderr, bufsize,
326 extra=None, **kwargs):
327 """Create subprocess transport."""
328 raise NotImplementedError
329
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700330 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200331 """Write a byte to self-pipe, to wake up the event loop.
332
333 This may be called from a different thread.
334
335 The subclass is responsible for implementing the self-pipe.
336 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700337 raise NotImplementedError
338
339 def _process_events(self, event_list):
340 """Process selector events."""
341 raise NotImplementedError
342
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200343 def _check_closed(self):
344 if self._closed:
345 raise RuntimeError('Event loop is closed')
346
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400347 def _asyncgen_finalizer_hook(self, agen):
348 self._asyncgens.discard(agen)
349 if not self.is_closed():
350 self.create_task(agen.aclose())
Yury Selivanovc5420492016-11-03 15:35:23 -0700351 # Wake up the loop if the finalizer was called from
352 # a different thread.
353 self._write_to_self()
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400354
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():
Yury Selivanov600a3492016-11-04 14:29:28 -0400396 raise RuntimeError('This event loop is already running')
397 if events._get_running_loop() is not None:
398 raise RuntimeError(
399 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400400 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100401 self._thread_id = threading.get_ident()
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400402 if self._asyncgens is not None:
403 old_agen_hooks = sys.get_asyncgen_hooks()
404 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
405 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700406 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400407 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800409 self._run_once()
410 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 break
412 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800413 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100414 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400415 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400416 self._set_coroutine_wrapper(False)
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400417 if self._asyncgens is not None:
418 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700419
420 def run_until_complete(self, future):
421 """Run until the Future is done.
422
423 If the argument is a coroutine, it is wrapped in a Task.
424
Victor Stinneracdb7822014-07-14 18:33:40 +0200425 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700426 with the same coroutine twice -- it would wrap it in two
427 different Tasks and that can't be good.
428
429 Return the Future's result, or raise its exception.
430 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200431 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200432
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700433 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400434 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200435 if new_task:
436 # An exception is raised if the future didn't complete, so there
437 # is no need to log the "destroy pending task" message
438 future._log_destroy_pending = False
439
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100440 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200441 try:
442 self.run_forever()
443 except:
444 if new_task and future.done() and not future.cancelled():
445 # The coroutine raised a BaseException. Consume the exception
446 # to not log a warning, the caller doesn't have access to the
447 # local task.
448 future.exception()
449 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100450 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700451 if not future.done():
452 raise RuntimeError('Event loop stopped before Future completed.')
453
454 return future.result()
455
456 def stop(self):
457 """Stop running the event loop.
458
Guido van Rossum41f69f42015-11-19 13:28:47 -0800459 Every callback already scheduled will still run. This simply informs
460 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700461 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800462 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700463
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200464 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700465 """Close the event loop.
466
467 This clears the queues and shuts down the executor,
468 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200469
470 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700471 """
Victor Stinner956de692014-12-26 21:07:52 +0100472 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200473 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200474 if self._closed:
475 return
Victor Stinnere912e652014-07-12 03:11:53 +0200476 if self._debug:
477 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400478 self._closed = True
479 self._ready.clear()
480 self._scheduled.clear()
481 executor = self._default_executor
482 if executor is not None:
483 self._default_executor = None
484 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200485
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200486 def is_closed(self):
487 """Returns True if the event loop was closed."""
488 return self._closed
489
Victor Stinner978a9af2015-01-29 17:50:58 +0100490 # On Python 3.3 and older, objects with a destructor part of a reference
491 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
492 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400493 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100494 def __del__(self):
495 if not self.is_closed():
496 warnings.warn("unclosed event loop %r" % self, ResourceWarning)
497 if not self.is_running():
498 self.close()
499
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200501 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100502 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700503
504 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200505 """Return the time according to the event loop's clock.
506
507 This is a float expressed in seconds since an epoch, but the
508 epoch, precision, accuracy and drift are unspecified and may
509 differ per event loop.
510 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700511 return time.monotonic()
512
513 def call_later(self, delay, callback, *args):
514 """Arrange for a callback to be called at a given time.
515
516 Return a Handle: an opaque object with a cancel() method that
517 can be used to cancel the call.
518
519 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200520 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700521
522 Each callback will be called exactly once. If two callbacks
523 are scheduled for exactly the same time, it undefined which
524 will be called first.
525
526 Any positional arguments after the callback will be passed to
527 the callback when it is called.
528 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200529 timer = self.call_at(self.time() + delay, callback, *args)
530 if timer._source_traceback:
531 del timer._source_traceback[-1]
532 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533
534 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200535 """Like call_later(), but uses an absolute time.
536
537 Absolute time corresponds to the event loop's time() method.
538 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100539 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100540 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100541 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700542 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500543 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200544 if timer._source_traceback:
545 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700546 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400547 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700548 return timer
549
550 def call_soon(self, callback, *args):
551 """Arrange for a callback to be called as soon as possible.
552
Victor Stinneracdb7822014-07-14 18:33:40 +0200553 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554 order in which they are registered. Each callback will be
555 called exactly once.
556
557 Any positional arguments after the callback will be passed to
558 the callback when it is called.
559 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700560 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100561 if self._debug:
562 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700563 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100564 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200565 if handle._source_traceback:
566 del handle._source_traceback[-1]
567 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100568
Yury Selivanov491a9122016-11-03 15:09:24 -0700569 def _check_callback(self, callback, method):
570 if (coroutines.iscoroutine(callback) or
571 coroutines.iscoroutinefunction(callback)):
572 raise TypeError(
573 "coroutines cannot be used with {}()".format(method))
574 if not callable(callback):
575 raise TypeError(
576 'a callable object was expected by {}(), got {!r}'.format(
577 method, callback))
578
579
Victor Stinner956de692014-12-26 21:07:52 +0100580 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500581 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200582 if handle._source_traceback:
583 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700584 self._ready.append(handle)
585 return handle
586
Victor Stinner956de692014-12-26 21:07:52 +0100587 def _check_thread(self):
588 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100589
Victor Stinneracdb7822014-07-14 18:33:40 +0200590 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100591 likely behave incorrectly when the assumption is violated.
592
Victor Stinneracdb7822014-07-14 18:33:40 +0200593 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100594 responsible for checking this condition for performance reasons.
595 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100596 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200597 return
Victor Stinner956de692014-12-26 21:07:52 +0100598 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100599 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100600 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200601 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100602 "than the current one")
603
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700604 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200605 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700606 self._check_closed()
607 if self._debug:
608 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100609 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200610 if handle._source_traceback:
611 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700612 self._write_to_self()
613 return handle
614
Yury Selivanov740169c2015-05-11 14:23:38 -0400615 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100616 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700617 if self._debug:
618 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700619 if executor is None:
620 executor = self._default_executor
621 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400622 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400624 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625
626 def set_default_executor(self, executor):
627 self._default_executor = executor
628
Victor Stinnere912e652014-07-12 03:11:53 +0200629 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
630 msg = ["%s:%r" % (host, port)]
631 if family:
632 msg.append('family=%r' % family)
633 if type:
634 msg.append('type=%r' % type)
635 if proto:
636 msg.append('proto=%r' % proto)
637 if flags:
638 msg.append('flags=%r' % flags)
639 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200640 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200641
642 t0 = self.time()
643 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
644 dt = self.time() - t0
645
Victor Stinneracdb7822014-07-14 18:33:40 +0200646 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200647 % (msg, dt * 1e3, addrinfo))
648 if dt >= self.slow_callback_duration:
649 logger.info(msg)
650 else:
651 logger.debug(msg)
652 return addrinfo
653
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700654 def getaddrinfo(self, host, port, *,
655 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400656 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200657 return self.run_in_executor(None, self._getaddrinfo_debug,
658 host, port, family, type, proto, flags)
659 else:
660 return self.run_in_executor(None, socket.getaddrinfo,
661 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700662
663 def getnameinfo(self, sockaddr, flags=0):
664 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
665
Victor Stinnerf951d282014-06-29 00:46:45 +0200666 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700667 def create_connection(self, protocol_factory, host=None, port=None, *,
668 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700669 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200670 """Connect to a TCP server.
671
672 Create a streaming transport connection to a given Internet host and
673 port: socket family AF_INET or socket.AF_INET6 depending on host (or
674 family if specified), socket type SOCK_STREAM. protocol_factory must be
675 a callable returning a protocol instance.
676
677 This method is a coroutine which will try to establish the connection
678 in the background. When successful, the coroutine returns a
679 (transport, protocol) pair.
680 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700681 if server_hostname is not None and not ssl:
682 raise ValueError('server_hostname is only meaningful with ssl')
683
684 if server_hostname is None and ssl:
685 # Use host as default for server_hostname. It is an error
686 # if host is empty or not set, e.g. when an
687 # already-connected socket was passed or when only a port
688 # is given. To avoid this error, you can pass
689 # server_hostname='' -- this will bypass the hostname
690 # check. (This also means that if host is a numeric
691 # IP/IPv6 address, we will attempt to verify that exact
692 # address; this will probably fail, but it is possible to
693 # create a certificate for a specific IP address, so we
694 # don't judge it here.)
695 if not host:
696 raise ValueError('You must set server_hostname '
697 'when using ssl without a host')
698 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700699
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700700 if host is not None or port is not None:
701 if sock is not None:
702 raise ValueError(
703 'host/port and sock can not be specified at the same time')
704
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400705 f1 = _ensure_resolved((host, port), family=family,
706 type=socket.SOCK_STREAM, proto=proto,
707 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700708 fs = [f1]
709 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400710 f2 = _ensure_resolved(local_addr, family=family,
711 type=socket.SOCK_STREAM, proto=proto,
712 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700713 fs.append(f2)
714 else:
715 f2 = None
716
717 yield from tasks.wait(fs, loop=self)
718
719 infos = f1.result()
720 if not infos:
721 raise OSError('getaddrinfo() returned empty list')
722 if f2 is not None:
723 laddr_infos = f2.result()
724 if not laddr_infos:
725 raise OSError('getaddrinfo() returned empty list')
726
727 exceptions = []
728 for family, type, proto, cname, address in infos:
729 try:
730 sock = socket.socket(family=family, type=type, proto=proto)
731 sock.setblocking(False)
732 if f2 is not None:
733 for _, _, _, _, laddr in laddr_infos:
734 try:
735 sock.bind(laddr)
736 break
737 except OSError as exc:
738 exc = OSError(
739 exc.errno, 'error while '
740 'attempting to bind on address '
741 '{!r}: {}'.format(
742 laddr, exc.strerror.lower()))
743 exceptions.append(exc)
744 else:
745 sock.close()
746 sock = None
747 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200748 if self._debug:
749 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700750 yield from self.sock_connect(sock, address)
751 except OSError as exc:
752 if sock is not None:
753 sock.close()
754 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200755 except:
756 if sock is not None:
757 sock.close()
758 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700759 else:
760 break
761 else:
762 if len(exceptions) == 1:
763 raise exceptions[0]
764 else:
765 # If they all have the same str(), raise one.
766 model = str(exceptions[0])
767 if all(str(exc) == model for exc in exceptions):
768 raise exceptions[0]
769 # Raise a combined exception so the user can see all
770 # the various error messages.
771 raise OSError('Multiple exceptions: {}'.format(
772 ', '.join(str(exc) for exc in exceptions)))
773
774 elif sock is None:
775 raise ValueError(
776 'host and port was not specified and no sock specified')
777
Yury Selivanovb057c522014-02-18 12:15:06 -0500778 transport, protocol = yield from self._create_connection_transport(
779 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200780 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200781 # Get the socket from the transport because SSL transport closes
782 # the old socket and creates a new SSL socket
783 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200784 logger.debug("%r connected to %s:%r: (%r, %r)",
785 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500786 return transport, protocol
787
Victor Stinnerf951d282014-06-29 00:46:45 +0200788 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500789 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400790 server_hostname, server_side=False):
791
792 sock.setblocking(False)
793
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700794 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400795 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700796 if ssl:
797 sslcontext = None if isinstance(ssl, bool) else ssl
798 transport = self._make_ssl_transport(
799 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400800 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700801 else:
802 transport = self._make_socket_transport(sock, protocol, waiter)
803
Victor Stinner29ad0112015-01-15 00:04:21 +0100804 try:
805 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100806 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100807 transport.close()
808 raise
809
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700810 return transport, protocol
811
Victor Stinnerf951d282014-06-29 00:46:45 +0200812 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700813 def create_datagram_endpoint(self, protocol_factory,
814 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700815 family=0, proto=0, flags=0,
816 reuse_address=None, reuse_port=None,
817 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700818 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700819 if sock is not None:
820 if (local_addr or remote_addr or
821 family or proto or flags or
822 reuse_address or reuse_port or allow_broadcast):
823 # show the problematic kwargs in exception msg
824 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
825 family=family, proto=proto, flags=flags,
826 reuse_address=reuse_address, reuse_port=reuse_port,
827 allow_broadcast=allow_broadcast)
828 problems = ', '.join(
829 '{}={}'.format(k, v) for k, v in opts.items() if v)
830 raise ValueError(
831 'socket modifier keyword arguments can not be used '
832 'when sock is specified. ({})'.format(problems))
833 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700834 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700835 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700836 if not (local_addr or remote_addr):
837 if family == 0:
838 raise ValueError('unexpected address family')
839 addr_pairs_info = (((family, proto), (None, None)),)
840 else:
841 # join address by (family, protocol)
842 addr_infos = collections.OrderedDict()
843 for idx, addr in ((0, local_addr), (1, remote_addr)):
844 if addr is not None:
845 assert isinstance(addr, tuple) and len(addr) == 2, (
846 '2-tuple is expected')
847
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400848 infos = yield from _ensure_resolved(
849 addr, family=family, type=socket.SOCK_DGRAM,
850 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700851 if not infos:
852 raise OSError('getaddrinfo() returned empty list')
853
854 for fam, _, pro, _, address in infos:
855 key = (fam, pro)
856 if key not in addr_infos:
857 addr_infos[key] = [None, None]
858 addr_infos[key][idx] = address
859
860 # each addr has to have info for each (family, proto) pair
861 addr_pairs_info = [
862 (key, addr_pair) for key, addr_pair in addr_infos.items()
863 if not ((local_addr and addr_pair[0] is None) or
864 (remote_addr and addr_pair[1] is None))]
865
866 if not addr_pairs_info:
867 raise ValueError('can not get address information')
868
869 exceptions = []
870
871 if reuse_address is None:
872 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
873
874 for ((family, proto),
875 (local_address, remote_address)) in addr_pairs_info:
876 sock = None
877 r_addr = None
878 try:
879 sock = socket.socket(
880 family=family, type=socket.SOCK_DGRAM, proto=proto)
881 if reuse_address:
882 sock.setsockopt(
883 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
884 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400885 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700886 if allow_broadcast:
887 sock.setsockopt(
888 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
889 sock.setblocking(False)
890
891 if local_addr:
892 sock.bind(local_address)
893 if remote_addr:
894 yield from self.sock_connect(sock, remote_address)
895 r_addr = remote_address
896 except OSError as exc:
897 if sock is not None:
898 sock.close()
899 exceptions.append(exc)
900 except:
901 if sock is not None:
902 sock.close()
903 raise
904 else:
905 break
906 else:
907 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700908
909 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400910 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700911 transport = self._make_datagram_transport(
912 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200913 if self._debug:
914 if local_addr:
915 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
916 "created: (%r, %r)",
917 local_addr, remote_addr, transport, protocol)
918 else:
919 logger.debug("Datagram endpoint remote_addr=%r created: "
920 "(%r, %r)",
921 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100922
923 try:
924 yield from waiter
925 except:
926 transport.close()
927 raise
928
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700929 return transport, protocol
930
Victor Stinnerf951d282014-06-29 00:46:45 +0200931 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200932 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400933 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200934 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400935 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200936 if not infos:
937 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
938 return infos
939
940 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700941 def create_server(self, protocol_factory, host=None, port=None,
942 *,
943 family=socket.AF_UNSPEC,
944 flags=socket.AI_PASSIVE,
945 sock=None,
946 backlog=100,
947 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700948 reuse_address=None,
949 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200950 """Create a TCP server.
951
952 The host parameter can be a string, in that case the TCP server is bound
953 to host and port.
954
955 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500956 the TCP server is bound to all hosts of the sequence. If a host
957 appears multiple times (possibly indirectly e.g. when hostnames
958 resolve to the same IP address), the server is only bound once to that
959 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200960
Victor Stinneracdb7822014-07-14 18:33:40 +0200961 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200962
963 This method is a coroutine.
964 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700965 if isinstance(ssl, bool):
966 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700967 if host is not None or port is not None:
968 if sock is not None:
969 raise ValueError(
970 'host/port and sock can not be specified at the same time')
971
972 AF_INET6 = getattr(socket, 'AF_INET6', 0)
973 if reuse_address is None:
974 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
975 sockets = []
976 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200977 hosts = [None]
978 elif (isinstance(host, str) or
979 not isinstance(host, collections.Iterable)):
980 hosts = [host]
981 else:
982 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700983
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200984 fs = [self._create_server_getaddrinfo(host, port, family=family,
985 flags=flags)
986 for host in hosts]
987 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500988 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700989
990 completed = False
991 try:
992 for res in infos:
993 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700994 try:
995 sock = socket.socket(af, socktype, proto)
996 except socket.error:
997 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200998 if self._debug:
999 logger.warning('create_server() failed to create '
1000 'socket.socket(%r, %r, %r)',
1001 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001002 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001003 sockets.append(sock)
1004 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001005 sock.setsockopt(
1006 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1007 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001008 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001009 # Disable IPv4/IPv6 dual stack support (enabled by
1010 # default on Linux) which makes a single socket
1011 # listen on both address families.
1012 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1013 sock.setsockopt(socket.IPPROTO_IPV6,
1014 socket.IPV6_V6ONLY,
1015 True)
1016 try:
1017 sock.bind(sa)
1018 except OSError as err:
1019 raise OSError(err.errno, 'error while attempting '
1020 'to bind on address %r: %s'
1021 % (sa, err.strerror.lower()))
1022 completed = True
1023 finally:
1024 if not completed:
1025 for sock in sockets:
1026 sock.close()
1027 else:
1028 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001029 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001030 sockets = [sock]
1031
1032 server = Server(self, sockets)
1033 for sock in sockets:
1034 sock.listen(backlog)
1035 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001036 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001037 if self._debug:
1038 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001039 return server
1040
Victor Stinnerf951d282014-06-29 00:46:45 +02001041 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001042 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1043 """Handle an accepted connection.
1044
1045 This is used by servers that accept connections outside of
1046 asyncio but that use asyncio to handle connections.
1047
1048 This method is a coroutine. When completed, the coroutine
1049 returns a (transport, protocol) pair.
1050 """
1051 transport, protocol = yield from self._create_connection_transport(
1052 sock, protocol_factory, ssl, '', server_side=True)
1053 if self._debug:
1054 # Get the socket from the transport because SSL transport closes
1055 # the old socket and creates a new SSL socket
1056 sock = transport.get_extra_info('socket')
1057 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1058 return transport, protocol
1059
1060 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001061 def connect_read_pipe(self, protocol_factory, pipe):
1062 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001063 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001064 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001065
1066 try:
1067 yield from waiter
1068 except:
1069 transport.close()
1070 raise
1071
Victor Stinneracdb7822014-07-14 18:33:40 +02001072 if self._debug:
1073 logger.debug('Read pipe %r connected: (%r, %r)',
1074 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001075 return transport, protocol
1076
Victor Stinnerf951d282014-06-29 00:46:45 +02001077 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078 def connect_write_pipe(self, protocol_factory, pipe):
1079 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001080 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001081 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001082
1083 try:
1084 yield from waiter
1085 except:
1086 transport.close()
1087 raise
1088
Victor Stinneracdb7822014-07-14 18:33:40 +02001089 if self._debug:
1090 logger.debug('Write pipe %r connected: (%r, %r)',
1091 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001092 return transport, protocol
1093
Victor Stinneracdb7822014-07-14 18:33:40 +02001094 def _log_subprocess(self, msg, stdin, stdout, stderr):
1095 info = [msg]
1096 if stdin is not None:
1097 info.append('stdin=%s' % _format_pipe(stdin))
1098 if stdout is not None and stderr == subprocess.STDOUT:
1099 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1100 else:
1101 if stdout is not None:
1102 info.append('stdout=%s' % _format_pipe(stdout))
1103 if stderr is not None:
1104 info.append('stderr=%s' % _format_pipe(stderr))
1105 logger.debug(' '.join(info))
1106
Victor Stinnerf951d282014-06-29 00:46:45 +02001107 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001108 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1109 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1110 universal_newlines=False, shell=True, bufsize=0,
1111 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001112 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001113 raise ValueError("cmd must be a string")
1114 if universal_newlines:
1115 raise ValueError("universal_newlines must be False")
1116 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001117 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001118 if bufsize != 0:
1119 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001120 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001121 if self._debug:
1122 # don't log parameters: they may contain sensitive information
1123 # (password) and may be too long
1124 debug_log = 'run shell command %r' % cmd
1125 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001126 transport = yield from self._make_subprocess_transport(
1127 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001128 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001129 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001130 return transport, protocol
1131
Victor Stinnerf951d282014-06-29 00:46:45 +02001132 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001133 def subprocess_exec(self, protocol_factory, program, *args,
1134 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1135 stderr=subprocess.PIPE, universal_newlines=False,
1136 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001137 if universal_newlines:
1138 raise ValueError("universal_newlines must be False")
1139 if shell:
1140 raise ValueError("shell must be False")
1141 if bufsize != 0:
1142 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001143 popen_args = (program,) + args
1144 for arg in popen_args:
1145 if not isinstance(arg, (str, bytes)):
1146 raise TypeError("program arguments must be "
1147 "a bytes or text string, not %s"
1148 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001149 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001150 if self._debug:
1151 # don't log parameters: they may contain sensitive information
1152 # (password) and may be too long
1153 debug_log = 'execute program %r' % program
1154 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001155 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001156 protocol, popen_args, False, stdin, stdout, stderr,
1157 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001158 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001159 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001160 return transport, protocol
1161
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001162 def get_exception_handler(self):
1163 """Return an exception handler, or None if the default one is in use.
1164 """
1165 return self._exception_handler
1166
Yury Selivanov569efa22014-02-18 18:02:19 -05001167 def set_exception_handler(self, handler):
1168 """Set handler as the new event loop exception handler.
1169
1170 If handler is None, the default exception handler will
1171 be set.
1172
1173 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001174 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001175 will be a reference to the active event loop, 'context'
1176 will be a dict object (see `call_exception_handler()`
1177 documentation for details about context).
1178 """
1179 if handler is not None and not callable(handler):
1180 raise TypeError('A callable object or None is expected, '
1181 'got {!r}'.format(handler))
1182 self._exception_handler = handler
1183
1184 def default_exception_handler(self, context):
1185 """Default exception handler.
1186
1187 This is called when an exception occurs and no exception
1188 handler is set, and can be called by a custom exception
1189 handler that wants to defer to the default behavior.
1190
Victor Stinneracdb7822014-07-14 18:33:40 +02001191 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001192 `call_exception_handler()`.
1193 """
1194 message = context.get('message')
1195 if not message:
1196 message = 'Unhandled exception in event loop'
1197
1198 exception = context.get('exception')
1199 if exception is not None:
1200 exc_info = (type(exception), exception, exception.__traceback__)
1201 else:
1202 exc_info = False
1203
Victor Stinnerff018e42015-01-28 00:30:40 +01001204 if ('source_traceback' not in context
1205 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001206 and self._current_handle._source_traceback):
1207 context['handle_traceback'] = self._current_handle._source_traceback
1208
Yury Selivanov569efa22014-02-18 18:02:19 -05001209 log_lines = [message]
1210 for key in sorted(context):
1211 if key in {'message', 'exception'}:
1212 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001213 value = context[key]
1214 if key == 'source_traceback':
1215 tb = ''.join(traceback.format_list(value))
1216 value = 'Object created at (most recent call last):\n'
1217 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001218 elif key == 'handle_traceback':
1219 tb = ''.join(traceback.format_list(value))
1220 value = 'Handle created at (most recent call last):\n'
1221 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001222 else:
1223 value = repr(value)
1224 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001225
1226 logger.error('\n'.join(log_lines), exc_info=exc_info)
1227
1228 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001229 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001230
Victor Stinneracdb7822014-07-14 18:33:40 +02001231 The context argument is a dict containing the following keys:
1232
Yury Selivanov569efa22014-02-18 18:02:19 -05001233 - 'message': Error message;
1234 - 'exception' (optional): Exception object;
1235 - 'future' (optional): Future instance;
1236 - 'handle' (optional): Handle instance;
1237 - 'protocol' (optional): Protocol instance;
1238 - 'transport' (optional): Transport instance;
Yury Selivanov4357cf62016-09-15 13:49:08 -04001239 - 'socket' (optional): Socket instance;
1240 - 'asyncgen' (optional): Asynchronous generator that caused
1241 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001242
Victor Stinneracdb7822014-07-14 18:33:40 +02001243 New keys maybe introduced in the future.
1244
1245 Note: do not overload this method in an event loop subclass.
1246 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001247 `set_exception_handler()` method.
1248 """
1249 if self._exception_handler is None:
1250 try:
1251 self.default_exception_handler(context)
1252 except Exception:
1253 # Second protection layer for unexpected errors
1254 # in the default implementation, as well as for subclassed
1255 # event loops with overloaded "default_exception_handler".
1256 logger.error('Exception in default exception handler',
1257 exc_info=True)
1258 else:
1259 try:
1260 self._exception_handler(self, context)
1261 except Exception as exc:
1262 # Exception in the user set custom exception handler.
1263 try:
1264 # Let's try default handler.
1265 self.default_exception_handler({
1266 'message': 'Unhandled error in exception handler',
1267 'exception': exc,
1268 'context': context,
1269 })
1270 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001271 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001272 # overloaded.
1273 logger.error('Exception in default exception handler '
1274 'while handling an unexpected error '
1275 'in custom exception handler',
1276 exc_info=True)
1277
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001278 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001279 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001280 assert isinstance(handle, events.Handle), 'A Handle is required here'
1281 if handle._cancelled:
1282 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001283 assert not isinstance(handle, events.TimerHandle)
1284 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001285
1286 def _add_callback_signalsafe(self, handle):
1287 """Like _add_callback() but called from a signal handler."""
1288 self._add_callback(handle)
1289 self._write_to_self()
1290
Yury Selivanov592ada92014-09-25 12:07:56 -04001291 def _timer_handle_cancelled(self, handle):
1292 """Notification that a TimerHandle has been cancelled."""
1293 if handle._scheduled:
1294 self._timer_cancelled_count += 1
1295
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001296 def _run_once(self):
1297 """Run one full iteration of the event loop.
1298
1299 This calls all currently ready callbacks, polls for I/O,
1300 schedules the resulting callbacks, and finally schedules
1301 'call_later' callbacks.
1302 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001303
Yury Selivanov592ada92014-09-25 12:07:56 -04001304 sched_count = len(self._scheduled)
1305 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1306 self._timer_cancelled_count / sched_count >
1307 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001308 # Remove delayed calls that were cancelled if their number
1309 # is too high
1310 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001311 for handle in self._scheduled:
1312 if handle._cancelled:
1313 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001314 else:
1315 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001316
Victor Stinner68da8fc2014-09-30 18:08:36 +02001317 heapq.heapify(new_scheduled)
1318 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001319 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001320 else:
1321 # Remove delayed calls that were cancelled from head of queue.
1322 while self._scheduled and self._scheduled[0]._cancelled:
1323 self._timer_cancelled_count -= 1
1324 handle = heapq.heappop(self._scheduled)
1325 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001326
1327 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001328 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001329 timeout = 0
1330 elif self._scheduled:
1331 # Compute the desired timeout.
1332 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001333 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001334
Victor Stinner770e48d2014-07-11 11:58:33 +02001335 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001336 t0 = self.time()
1337 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001338 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001339 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001340 level = logging.INFO
1341 else:
1342 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001343 nevent = len(event_list)
1344 if timeout is None:
1345 logger.log(level, 'poll took %.3f ms: %s events',
1346 dt * 1e3, nevent)
1347 elif nevent:
1348 logger.log(level,
1349 'poll %.3f ms took %.3f ms: %s events',
1350 timeout * 1e3, dt * 1e3, nevent)
1351 elif dt >= 1.0:
1352 logger.log(level,
1353 'poll %.3f ms took %.3f ms: timeout',
1354 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001355 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001356 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001357 self._process_events(event_list)
1358
1359 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001360 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001361 while self._scheduled:
1362 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001363 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001364 break
1365 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001366 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001367 self._ready.append(handle)
1368
1369 # This is the only place where callbacks are actually *called*.
1370 # All other places just add them to ready.
1371 # Note: We run all currently scheduled callbacks, but not any
1372 # callbacks scheduled by callbacks run this time around --
1373 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001374 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001375 ntodo = len(self._ready)
1376 for i in range(ntodo):
1377 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001378 if handle._cancelled:
1379 continue
1380 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001381 try:
1382 self._current_handle = handle
1383 t0 = self.time()
1384 handle._run()
1385 dt = self.time() - t0
1386 if dt >= self.slow_callback_duration:
1387 logger.warning('Executing %s took %.3f seconds',
1388 _format_handle(handle), dt)
1389 finally:
1390 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001391 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001392 handle._run()
1393 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001394
Yury Selivanove8944cb2015-05-12 11:43:04 -04001395 def _set_coroutine_wrapper(self, enabled):
1396 try:
1397 set_wrapper = sys.set_coroutine_wrapper
1398 get_wrapper = sys.get_coroutine_wrapper
1399 except AttributeError:
1400 return
1401
1402 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001403 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001404 return
1405
1406 wrapper = coroutines.debug_wrapper
1407 current_wrapper = get_wrapper()
1408
1409 if enabled:
1410 if current_wrapper not in (None, wrapper):
1411 warnings.warn(
1412 "loop.set_debug(True): cannot set debug coroutine "
1413 "wrapper; another wrapper is already set %r" %
1414 current_wrapper, RuntimeWarning)
1415 else:
1416 set_wrapper(wrapper)
1417 self._coroutine_wrapper_set = True
1418 else:
1419 if current_wrapper not in (None, wrapper):
1420 warnings.warn(
1421 "loop.set_debug(False): cannot unset debug coroutine "
1422 "wrapper; another wrapper was set %r" %
1423 current_wrapper, RuntimeWarning)
1424 else:
1425 set_wrapper(None)
1426 self._coroutine_wrapper_set = False
1427
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001428 def get_debug(self):
1429 return self._debug
1430
1431 def set_debug(self, enabled):
1432 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001433
Yury Selivanove8944cb2015-05-12 11:43:04 -04001434 if self.is_running():
1435 self._set_coroutine_wrapper(enabled)