blob: ac6e8f2753c9ffd2291c141ce7ddc20cc25c4788 [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 Selivanov5587d7c2016-09-15 15:45:07 -040079def _set_reuseport(sock):
80 if not hasattr(socket, 'SO_REUSEPORT'):
81 raise ValueError('reuse_port not supported by socket module')
82 else:
83 try:
84 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
85 except OSError:
86 raise ValueError('reuse_port not supported by socket module, '
87 'SO_REUSEPORT defined but not implemented.')
88
89
Yury Selivanovd5c2a622015-12-16 19:31:17 -050090# Linux's sock.type is a bitmask that can include extra info about socket.
91_SOCKET_TYPE_MASK = 0
92if hasattr(socket, 'SOCK_NONBLOCK'):
93 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
94if hasattr(socket, 'SOCK_CLOEXEC'):
95 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
96
97
Yury Selivanovd5c2a622015-12-16 19:31:17 -050098def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040099 # Try to skip getaddrinfo if "host" is already an IP. Users might have
100 # handled name resolution in their own code and pass in resolved IPs.
101 if not hasattr(socket, 'inet_pton'):
102 return
103
104 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
105 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500106 return None
107
108 type &= ~_SOCKET_TYPE_MASK
109 if type == socket.SOCK_STREAM:
110 proto = socket.IPPROTO_TCP
111 elif type == socket.SOCK_DGRAM:
112 proto = socket.IPPROTO_UDP
113 else:
114 return None
115
Yury Selivanova7146162016-06-02 16:51:07 -0400116 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400117 port = 0
Yury Selivanova7146162016-06-02 16:51:07 -0400118 elif isinstance(port, bytes):
119 if port == b'':
120 port = 0
121 else:
122 try:
123 port = int(port)
124 except ValueError:
125 # Might be a service name like b"http".
126 port = socket.getservbyname(port.decode('ascii'))
127 elif isinstance(port, str):
128 if port == '':
129 port = 0
130 else:
131 try:
132 port = int(port)
133 except ValueError:
134 # Might be a service name like "http".
135 port = socket.getservbyname(port)
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400136
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400137 if family == socket.AF_UNSPEC:
138 afs = [socket.AF_INET, socket.AF_INET6]
139 else:
140 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500141
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400142 if isinstance(host, bytes):
143 host = host.decode('idna')
144 if '%' in host:
145 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
146 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500147 return None
148
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400149 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500150 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 socket.inet_pton(af, host)
152 # The host has already been resolved.
153 return af, type, proto, '', (host, port)
154 except OSError:
155 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500156
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400157 # "host" is not an IP address.
158 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500159
160
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400161def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
162 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500163 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400164 info = _ipaddr_info(host, port, family, type, proto)
165 if info is not None:
166 # "host" is already a resolved IP.
167 fut = loop.create_future()
168 fut.set_result([info])
169 return fut
170 else:
171 return loop.getaddrinfo(host, port, family=family, type=type,
172 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100173
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100175def _run_until_complete_cb(fut):
176 exc = fut._exception
177 if (isinstance(exc, BaseException)
178 and not isinstance(exc, Exception)):
179 # Issue #22429: run_forever() already finished, no need to
180 # stop it.
181 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800182 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100183
184
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700185class Server(events.AbstractServer):
186
187 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200188 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700189 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200190 self._active_count = 0
191 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700192
Victor Stinnere912e652014-07-12 03:11:53 +0200193 def __repr__(self):
194 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
195
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200196 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700197 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200198 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700199
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200200 def _detach(self):
201 assert self._active_count > 0
202 self._active_count -= 1
203 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204 self._wakeup()
205
206 def close(self):
207 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200208 if sockets is None:
209 return
210 self.sockets = None
211 for sock in sockets:
212 self._loop._stop_serving(sock)
213 if self._active_count == 0:
214 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700215
216 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 waiters = self._waiters
218 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700219 for waiter in waiters:
220 if not waiter.done():
221 waiter.set_result(waiter)
222
Victor Stinnerf951d282014-06-29 00:46:45 +0200223 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700224 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200225 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700226 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400227 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200228 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700229 yield from waiter
230
231
232class BaseEventLoop(events.AbstractEventLoop):
233
234 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400235 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200236 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800237 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700238 self._ready = collections.deque()
239 self._scheduled = []
240 self._default_executor = None
241 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100242 # Identifier of the thread running the event loop, or None if the
243 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100244 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100245 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500246 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400247 self.set_debug((not sys.flags.ignore_environment
248 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200249 # In debug mode, if the execution of a callback or a step of a task
250 # exceed this duration in seconds, the slow callback/task is logged.
251 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100252 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400253 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400254 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700255
Yury Selivanov0a91d482016-09-15 13:24:03 -0400256 if hasattr(sys, 'get_asyncgen_hooks'):
257 # Python >= 3.6
258 # A weak set of all asynchronous generators that are
259 # being iterated by the loop.
260 self._asyncgens = weakref.WeakSet()
261 else:
262 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700263
264 # Set to True when `loop.shutdown_asyncgens` is called.
265 self._asyncgens_shutdown_called = False
266
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200267 def __repr__(self):
268 return ('<%s running=%s closed=%s debug=%s>'
269 % (self.__class__.__name__, self.is_running(),
270 self.is_closed(), self.get_debug()))
271
Yury Selivanov7661db62016-05-16 15:38:39 -0400272 def create_future(self):
273 """Create a Future object attached to the loop."""
274 return futures.Future(loop=self)
275
Victor Stinner896a25a2014-07-08 11:29:25 +0200276 def create_task(self, coro):
277 """Schedule a coroutine object.
278
Victor Stinneracdb7822014-07-14 18:33:40 +0200279 Return a task object.
280 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100281 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400282 if self._task_factory is None:
283 task = tasks.Task(coro, loop=self)
284 if task._source_traceback:
285 del task._source_traceback[-1]
286 else:
287 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200288 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200289
Yury Selivanov740169c2015-05-11 14:23:38 -0400290 def set_task_factory(self, factory):
291 """Set a task factory that will be used by loop.create_task().
292
293 If factory is None the default task factory will be set.
294
295 If factory is a callable, it should have a signature matching
296 '(loop, coro)', where 'loop' will be a reference to the active
297 event loop, 'coro' will be a coroutine object. The callable
298 must return a Future.
299 """
300 if factory is not None and not callable(factory):
301 raise TypeError('task factory must be a callable or None')
302 self._task_factory = factory
303
304 def get_task_factory(self):
305 """Return a task factory, or None if the default one is in use."""
306 return self._task_factory
307
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700308 def _make_socket_transport(self, sock, protocol, waiter=None, *,
309 extra=None, server=None):
310 """Create socket transport."""
311 raise NotImplementedError
312
Victor Stinner15cc6782015-01-09 00:09:10 +0100313 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
314 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700315 extra=None, server=None):
316 """Create SSL transport."""
317 raise NotImplementedError
318
319 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200320 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700321 """Create datagram transport."""
322 raise NotImplementedError
323
324 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
325 extra=None):
326 """Create read pipe transport."""
327 raise NotImplementedError
328
329 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
330 extra=None):
331 """Create write pipe transport."""
332 raise NotImplementedError
333
Victor Stinnerf951d282014-06-29 00:46:45 +0200334 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700335 def _make_subprocess_transport(self, protocol, args, shell,
336 stdin, stdout, stderr, bufsize,
337 extra=None, **kwargs):
338 """Create subprocess transport."""
339 raise NotImplementedError
340
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700341 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200342 """Write a byte to self-pipe, to wake up the event loop.
343
344 This may be called from a different thread.
345
346 The subclass is responsible for implementing the self-pipe.
347 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700348 raise NotImplementedError
349
350 def _process_events(self, event_list):
351 """Process selector events."""
352 raise NotImplementedError
353
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200354 def _check_closed(self):
355 if self._closed:
356 raise RuntimeError('Event loop is closed')
357
Yury Selivanoveb636452016-09-08 22:01:51 -0700358 def _asyncgen_finalizer_hook(self, agen):
359 self._asyncgens.discard(agen)
360 if not self.is_closed():
361 self.create_task(agen.aclose())
362
363 def _asyncgen_firstiter_hook(self, agen):
364 if self._asyncgens_shutdown_called:
365 warnings.warn(
366 "asynchronous generator {!r} was scheduled after "
367 "loop.shutdown_asyncgens() call".format(agen),
368 ResourceWarning, source=self)
369
370 self._asyncgens.add(agen)
371
372 @coroutine
373 def shutdown_asyncgens(self):
374 """Shutdown all active asynchronous generators."""
375 self._asyncgens_shutdown_called = True
376
Yury Selivanov0a91d482016-09-15 13:24:03 -0400377 if self._asyncgens is None or not len(self._asyncgens):
378 # If Python version is <3.6 or we don't have any asynchronous
379 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700380 return
381
382 closing_agens = list(self._asyncgens)
383 self._asyncgens.clear()
384
385 shutdown_coro = tasks.gather(
386 *[ag.aclose() for ag in closing_agens],
387 return_exceptions=True,
388 loop=self)
389
390 results = yield from shutdown_coro
391 for result, agen in zip(results, closing_agens):
392 if isinstance(result, Exception):
393 self.call_exception_handler({
394 'message': 'an error occurred during closing of '
395 'asynchronous generator {!r}'.format(agen),
396 'exception': result,
397 'asyncgen': agen
398 })
399
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700400 def run_forever(self):
401 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200402 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100403 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700404 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400405 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100406 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400407 if self._asyncgens is not None:
408 old_agen_hooks = sys.get_asyncgen_hooks()
409 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
410 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 try:
412 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800413 self._run_once()
414 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700415 break
416 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800417 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100418 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400419 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400420 if self._asyncgens is not None:
421 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700422
423 def run_until_complete(self, future):
424 """Run until the Future is done.
425
426 If the argument is a coroutine, it is wrapped in a Task.
427
Victor Stinneracdb7822014-07-14 18:33:40 +0200428 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700429 with the same coroutine twice -- it would wrap it in two
430 different Tasks and that can't be good.
431
432 Return the Future's result, or raise its exception.
433 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200434 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200435
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700436 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400437 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200438 if new_task:
439 # An exception is raised if the future didn't complete, so there
440 # is no need to log the "destroy pending task" message
441 future._log_destroy_pending = False
442
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100443 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200444 try:
445 self.run_forever()
446 except:
447 if new_task and future.done() and not future.cancelled():
448 # The coroutine raised a BaseException. Consume the exception
449 # to not log a warning, the caller doesn't have access to the
450 # local task.
451 future.exception()
452 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100453 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700454 if not future.done():
455 raise RuntimeError('Event loop stopped before Future completed.')
456
457 return future.result()
458
459 def stop(self):
460 """Stop running the event loop.
461
Guido van Rossum41f69f42015-11-19 13:28:47 -0800462 Every callback already scheduled will still run. This simply informs
463 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700464 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800465 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200467 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700468 """Close the event loop.
469
470 This clears the queues and shuts down the executor,
471 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200472
473 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700474 """
Victor Stinner956de692014-12-26 21:07:52 +0100475 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200476 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200477 if self._closed:
478 return
Victor Stinnere912e652014-07-12 03:11:53 +0200479 if self._debug:
480 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400481 self._closed = True
482 self._ready.clear()
483 self._scheduled.clear()
484 executor = self._default_executor
485 if executor is not None:
486 self._default_executor = None
487 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200488
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200489 def is_closed(self):
490 """Returns True if the event loop was closed."""
491 return self._closed
492
Victor Stinner978a9af2015-01-29 17:50:58 +0100493 # On Python 3.3 and older, objects with a destructor part of a reference
494 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
495 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400496 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100497 def __del__(self):
498 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100499 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
500 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100501 if not self.is_running():
502 self.close()
503
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200505 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100506 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700507
508 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200509 """Return the time according to the event loop's clock.
510
511 This is a float expressed in seconds since an epoch, but the
512 epoch, precision, accuracy and drift are unspecified and may
513 differ per event loop.
514 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700515 return time.monotonic()
516
517 def call_later(self, delay, callback, *args):
518 """Arrange for a callback to be called at a given time.
519
520 Return a Handle: an opaque object with a cancel() method that
521 can be used to cancel the call.
522
523 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200524 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525
526 Each callback will be called exactly once. If two callbacks
527 are scheduled for exactly the same time, it undefined which
528 will be called first.
529
530 Any positional arguments after the callback will be passed to
531 the callback when it is called.
532 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200533 timer = self.call_at(self.time() + delay, callback, *args)
534 if timer._source_traceback:
535 del timer._source_traceback[-1]
536 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537
538 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200539 """Like call_later(), but uses an absolute time.
540
541 Absolute time corresponds to the event loop's time() method.
542 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100543 if (coroutines.iscoroutine(callback)
544 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100545 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100546 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100547 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100548 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500549 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200550 if timer._source_traceback:
551 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400553 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554 return timer
555
556 def call_soon(self, callback, *args):
557 """Arrange for a callback to be called as soon as possible.
558
Victor Stinneracdb7822014-07-14 18:33:40 +0200559 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560 order in which they are registered. Each callback will be
561 called exactly once.
562
563 Any positional arguments after the callback will be passed to
564 the callback when it is called.
565 """
Victor Stinner956de692014-12-26 21:07:52 +0100566 if self._debug:
567 self._check_thread()
568 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200569 if handle._source_traceback:
570 del handle._source_traceback[-1]
571 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100572
Victor Stinner956de692014-12-26 21:07:52 +0100573 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100574 if (coroutines.iscoroutine(callback)
575 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100576 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100577 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500578 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200579 if handle._source_traceback:
580 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700581 self._ready.append(handle)
582 return handle
583
Victor Stinner956de692014-12-26 21:07:52 +0100584 def _check_thread(self):
585 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100586
Victor Stinneracdb7822014-07-14 18:33:40 +0200587 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100588 likely behave incorrectly when the assumption is violated.
589
Victor Stinneracdb7822014-07-14 18:33:40 +0200590 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100591 responsible for checking this condition for performance reasons.
592 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100593 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200594 return
Victor Stinner956de692014-12-26 21:07:52 +0100595 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100596 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100597 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200598 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100599 "than the current one")
600
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200602 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100603 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200604 if handle._source_traceback:
605 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700606 self._write_to_self()
607 return handle
608
Yury Selivanov740169c2015-05-11 14:23:38 -0400609 def run_in_executor(self, executor, func, *args):
610 if (coroutines.iscoroutine(func)
611 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100612 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100613 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400614 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700615 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400616 assert not isinstance(func, events.TimerHandle)
617 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400618 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700619 f.set_result(None)
620 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400621 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622 if executor is None:
623 executor = self._default_executor
624 if executor is None:
625 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
626 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400627 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700628
629 def set_default_executor(self, executor):
630 self._default_executor = executor
631
Victor Stinnere912e652014-07-12 03:11:53 +0200632 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
633 msg = ["%s:%r" % (host, port)]
634 if family:
635 msg.append('family=%r' % family)
636 if type:
637 msg.append('type=%r' % type)
638 if proto:
639 msg.append('proto=%r' % proto)
640 if flags:
641 msg.append('flags=%r' % flags)
642 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200643 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200644
645 t0 = self.time()
646 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
647 dt = self.time() - t0
648
Victor Stinneracdb7822014-07-14 18:33:40 +0200649 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200650 % (msg, dt * 1e3, addrinfo))
651 if dt >= self.slow_callback_duration:
652 logger.info(msg)
653 else:
654 logger.debug(msg)
655 return addrinfo
656
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657 def getaddrinfo(self, host, port, *,
658 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400659 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200660 return self.run_in_executor(None, self._getaddrinfo_debug,
661 host, port, family, type, proto, flags)
662 else:
663 return self.run_in_executor(None, socket.getaddrinfo,
664 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665
666 def getnameinfo(self, sockaddr, flags=0):
667 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
668
Victor Stinnerf951d282014-06-29 00:46:45 +0200669 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700670 def create_connection(self, protocol_factory, host=None, port=None, *,
671 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700672 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200673 """Connect to a TCP server.
674
675 Create a streaming transport connection to a given Internet host and
676 port: socket family AF_INET or socket.AF_INET6 depending on host (or
677 family if specified), socket type SOCK_STREAM. protocol_factory must be
678 a callable returning a protocol instance.
679
680 This method is a coroutine which will try to establish the connection
681 in the background. When successful, the coroutine returns a
682 (transport, protocol) pair.
683 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700684 if server_hostname is not None and not ssl:
685 raise ValueError('server_hostname is only meaningful with ssl')
686
687 if server_hostname is None and ssl:
688 # Use host as default for server_hostname. It is an error
689 # if host is empty or not set, e.g. when an
690 # already-connected socket was passed or when only a port
691 # is given. To avoid this error, you can pass
692 # server_hostname='' -- this will bypass the hostname
693 # check. (This also means that if host is a numeric
694 # IP/IPv6 address, we will attempt to verify that exact
695 # address; this will probably fail, but it is possible to
696 # create a certificate for a specific IP address, so we
697 # don't judge it here.)
698 if not host:
699 raise ValueError('You must set server_hostname '
700 'when using ssl without a host')
701 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700702
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700703 if host is not None or port is not None:
704 if sock is not None:
705 raise ValueError(
706 'host/port and sock can not be specified at the same time')
707
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400708 f1 = _ensure_resolved((host, port), family=family,
709 type=socket.SOCK_STREAM, proto=proto,
710 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700711 fs = [f1]
712 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400713 f2 = _ensure_resolved(local_addr, family=family,
714 type=socket.SOCK_STREAM, proto=proto,
715 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700716 fs.append(f2)
717 else:
718 f2 = None
719
720 yield from tasks.wait(fs, loop=self)
721
722 infos = f1.result()
723 if not infos:
724 raise OSError('getaddrinfo() returned empty list')
725 if f2 is not None:
726 laddr_infos = f2.result()
727 if not laddr_infos:
728 raise OSError('getaddrinfo() returned empty list')
729
730 exceptions = []
731 for family, type, proto, cname, address in infos:
732 try:
733 sock = socket.socket(family=family, type=type, proto=proto)
734 sock.setblocking(False)
735 if f2 is not None:
736 for _, _, _, _, laddr in laddr_infos:
737 try:
738 sock.bind(laddr)
739 break
740 except OSError as exc:
741 exc = OSError(
742 exc.errno, 'error while '
743 'attempting to bind on address '
744 '{!r}: {}'.format(
745 laddr, exc.strerror.lower()))
746 exceptions.append(exc)
747 else:
748 sock.close()
749 sock = None
750 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200751 if self._debug:
752 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700753 yield from self.sock_connect(sock, address)
754 except OSError as exc:
755 if sock is not None:
756 sock.close()
757 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200758 except:
759 if sock is not None:
760 sock.close()
761 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700762 else:
763 break
764 else:
765 if len(exceptions) == 1:
766 raise exceptions[0]
767 else:
768 # If they all have the same str(), raise one.
769 model = str(exceptions[0])
770 if all(str(exc) == model for exc in exceptions):
771 raise exceptions[0]
772 # Raise a combined exception so the user can see all
773 # the various error messages.
774 raise OSError('Multiple exceptions: {}'.format(
775 ', '.join(str(exc) for exc in exceptions)))
776
777 elif sock is None:
778 raise ValueError(
779 'host and port was not specified and no sock specified')
780
Yury Selivanovb057c522014-02-18 12:15:06 -0500781 transport, protocol = yield from self._create_connection_transport(
782 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200783 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200784 # Get the socket from the transport because SSL transport closes
785 # the old socket and creates a new SSL socket
786 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200787 logger.debug("%r connected to %s:%r: (%r, %r)",
788 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500789 return transport, protocol
790
Victor Stinnerf951d282014-06-29 00:46:45 +0200791 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500792 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400793 server_hostname, server_side=False):
794
795 sock.setblocking(False)
796
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700797 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400798 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700799 if ssl:
800 sslcontext = None if isinstance(ssl, bool) else ssl
801 transport = self._make_ssl_transport(
802 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400803 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700804 else:
805 transport = self._make_socket_transport(sock, protocol, waiter)
806
Victor Stinner29ad0112015-01-15 00:04:21 +0100807 try:
808 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100809 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100810 transport.close()
811 raise
812
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700813 return transport, protocol
814
Victor Stinnerf951d282014-06-29 00:46:45 +0200815 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700816 def create_datagram_endpoint(self, protocol_factory,
817 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700818 family=0, proto=0, flags=0,
819 reuse_address=None, reuse_port=None,
820 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700821 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700822 if sock is not None:
823 if (local_addr or remote_addr or
824 family or proto or flags or
825 reuse_address or reuse_port or allow_broadcast):
826 # show the problematic kwargs in exception msg
827 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
828 family=family, proto=proto, flags=flags,
829 reuse_address=reuse_address, reuse_port=reuse_port,
830 allow_broadcast=allow_broadcast)
831 problems = ', '.join(
832 '{}={}'.format(k, v) for k, v in opts.items() if v)
833 raise ValueError(
834 'socket modifier keyword arguments can not be used '
835 'when sock is specified. ({})'.format(problems))
836 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700837 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700838 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700839 if not (local_addr or remote_addr):
840 if family == 0:
841 raise ValueError('unexpected address family')
842 addr_pairs_info = (((family, proto), (None, None)),)
843 else:
844 # join address by (family, protocol)
845 addr_infos = collections.OrderedDict()
846 for idx, addr in ((0, local_addr), (1, remote_addr)):
847 if addr is not None:
848 assert isinstance(addr, tuple) and len(addr) == 2, (
849 '2-tuple is expected')
850
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400851 infos = yield from _ensure_resolved(
852 addr, family=family, type=socket.SOCK_DGRAM,
853 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700854 if not infos:
855 raise OSError('getaddrinfo() returned empty list')
856
857 for fam, _, pro, _, address in infos:
858 key = (fam, pro)
859 if key not in addr_infos:
860 addr_infos[key] = [None, None]
861 addr_infos[key][idx] = address
862
863 # each addr has to have info for each (family, proto) pair
864 addr_pairs_info = [
865 (key, addr_pair) for key, addr_pair in addr_infos.items()
866 if not ((local_addr and addr_pair[0] is None) or
867 (remote_addr and addr_pair[1] is None))]
868
869 if not addr_pairs_info:
870 raise ValueError('can not get address information')
871
872 exceptions = []
873
874 if reuse_address is None:
875 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
876
877 for ((family, proto),
878 (local_address, remote_address)) in addr_pairs_info:
879 sock = None
880 r_addr = None
881 try:
882 sock = socket.socket(
883 family=family, type=socket.SOCK_DGRAM, proto=proto)
884 if reuse_address:
885 sock.setsockopt(
886 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
887 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400888 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700889 if allow_broadcast:
890 sock.setsockopt(
891 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
892 sock.setblocking(False)
893
894 if local_addr:
895 sock.bind(local_address)
896 if remote_addr:
897 yield from self.sock_connect(sock, remote_address)
898 r_addr = remote_address
899 except OSError as exc:
900 if sock is not None:
901 sock.close()
902 exceptions.append(exc)
903 except:
904 if sock is not None:
905 sock.close()
906 raise
907 else:
908 break
909 else:
910 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700911
912 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400913 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700914 transport = self._make_datagram_transport(
915 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200916 if self._debug:
917 if local_addr:
918 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
919 "created: (%r, %r)",
920 local_addr, remote_addr, transport, protocol)
921 else:
922 logger.debug("Datagram endpoint remote_addr=%r created: "
923 "(%r, %r)",
924 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100925
926 try:
927 yield from waiter
928 except:
929 transport.close()
930 raise
931
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700932 return transport, protocol
933
Victor Stinnerf951d282014-06-29 00:46:45 +0200934 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200935 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400936 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200937 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400938 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200939 if not infos:
940 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
941 return infos
942
943 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700944 def create_server(self, protocol_factory, host=None, port=None,
945 *,
946 family=socket.AF_UNSPEC,
947 flags=socket.AI_PASSIVE,
948 sock=None,
949 backlog=100,
950 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700951 reuse_address=None,
952 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200953 """Create a TCP server.
954
955 The host parameter can be a string, in that case the TCP server is bound
956 to host and port.
957
958 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500959 the TCP server is bound to all hosts of the sequence. If a host
960 appears multiple times (possibly indirectly e.g. when hostnames
961 resolve to the same IP address), the server is only bound once to that
962 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200963
Victor Stinneracdb7822014-07-14 18:33:40 +0200964 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200965
966 This method is a coroutine.
967 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700968 if isinstance(ssl, bool):
969 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700970 if host is not None or port is not None:
971 if sock is not None:
972 raise ValueError(
973 'host/port and sock can not be specified at the same time')
974
975 AF_INET6 = getattr(socket, 'AF_INET6', 0)
976 if reuse_address is None:
977 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
978 sockets = []
979 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200980 hosts = [None]
981 elif (isinstance(host, str) or
982 not isinstance(host, collections.Iterable)):
983 hosts = [host]
984 else:
985 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700986
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200987 fs = [self._create_server_getaddrinfo(host, port, family=family,
988 flags=flags)
989 for host in hosts]
990 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500991 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700992
993 completed = False
994 try:
995 for res in infos:
996 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700997 try:
998 sock = socket.socket(af, socktype, proto)
999 except socket.error:
1000 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001001 if self._debug:
1002 logger.warning('create_server() failed to create '
1003 'socket.socket(%r, %r, %r)',
1004 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001005 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001006 sockets.append(sock)
1007 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001008 sock.setsockopt(
1009 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1010 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001011 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001012 # Disable IPv4/IPv6 dual stack support (enabled by
1013 # default on Linux) which makes a single socket
1014 # listen on both address families.
1015 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1016 sock.setsockopt(socket.IPPROTO_IPV6,
1017 socket.IPV6_V6ONLY,
1018 True)
1019 try:
1020 sock.bind(sa)
1021 except OSError as err:
1022 raise OSError(err.errno, 'error while attempting '
1023 'to bind on address %r: %s'
1024 % (sa, err.strerror.lower()))
1025 completed = True
1026 finally:
1027 if not completed:
1028 for sock in sockets:
1029 sock.close()
1030 else:
1031 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001032 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001033 sockets = [sock]
1034
1035 server = Server(self, sockets)
1036 for sock in sockets:
1037 sock.listen(backlog)
1038 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001039 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001040 if self._debug:
1041 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001042 return server
1043
Victor Stinnerf951d282014-06-29 00:46:45 +02001044 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001045 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1046 """Handle an accepted connection.
1047
1048 This is used by servers that accept connections outside of
1049 asyncio but that use asyncio to handle connections.
1050
1051 This method is a coroutine. When completed, the coroutine
1052 returns a (transport, protocol) pair.
1053 """
1054 transport, protocol = yield from self._create_connection_transport(
1055 sock, protocol_factory, ssl, '', server_side=True)
1056 if self._debug:
1057 # Get the socket from the transport because SSL transport closes
1058 # the old socket and creates a new SSL socket
1059 sock = transport.get_extra_info('socket')
1060 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1061 return transport, protocol
1062
1063 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001064 def connect_read_pipe(self, protocol_factory, pipe):
1065 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001066 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001067 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001068
1069 try:
1070 yield from waiter
1071 except:
1072 transport.close()
1073 raise
1074
Victor Stinneracdb7822014-07-14 18:33:40 +02001075 if self._debug:
1076 logger.debug('Read pipe %r connected: (%r, %r)',
1077 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078 return transport, protocol
1079
Victor Stinnerf951d282014-06-29 00:46:45 +02001080 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001081 def connect_write_pipe(self, protocol_factory, pipe):
1082 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001083 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001084 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001085
1086 try:
1087 yield from waiter
1088 except:
1089 transport.close()
1090 raise
1091
Victor Stinneracdb7822014-07-14 18:33:40 +02001092 if self._debug:
1093 logger.debug('Write pipe %r connected: (%r, %r)',
1094 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001095 return transport, protocol
1096
Victor Stinneracdb7822014-07-14 18:33:40 +02001097 def _log_subprocess(self, msg, stdin, stdout, stderr):
1098 info = [msg]
1099 if stdin is not None:
1100 info.append('stdin=%s' % _format_pipe(stdin))
1101 if stdout is not None and stderr == subprocess.STDOUT:
1102 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1103 else:
1104 if stdout is not None:
1105 info.append('stdout=%s' % _format_pipe(stdout))
1106 if stderr is not None:
1107 info.append('stderr=%s' % _format_pipe(stderr))
1108 logger.debug(' '.join(info))
1109
Victor Stinnerf951d282014-06-29 00:46:45 +02001110 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001111 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1112 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1113 universal_newlines=False, shell=True, bufsize=0,
1114 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001115 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001116 raise ValueError("cmd must be a string")
1117 if universal_newlines:
1118 raise ValueError("universal_newlines must be False")
1119 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001120 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001121 if bufsize != 0:
1122 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001123 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001124 if self._debug:
1125 # don't log parameters: they may contain sensitive information
1126 # (password) and may be too long
1127 debug_log = 'run shell command %r' % cmd
1128 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001129 transport = yield from self._make_subprocess_transport(
1130 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001131 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001132 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001133 return transport, protocol
1134
Victor Stinnerf951d282014-06-29 00:46:45 +02001135 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001136 def subprocess_exec(self, protocol_factory, program, *args,
1137 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1138 stderr=subprocess.PIPE, universal_newlines=False,
1139 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001140 if universal_newlines:
1141 raise ValueError("universal_newlines must be False")
1142 if shell:
1143 raise ValueError("shell must be False")
1144 if bufsize != 0:
1145 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001146 popen_args = (program,) + args
1147 for arg in popen_args:
1148 if not isinstance(arg, (str, bytes)):
1149 raise TypeError("program arguments must be "
1150 "a bytes or text string, not %s"
1151 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001152 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001153 if self._debug:
1154 # don't log parameters: they may contain sensitive information
1155 # (password) and may be too long
1156 debug_log = 'execute program %r' % program
1157 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001158 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001159 protocol, popen_args, False, stdin, stdout, stderr,
1160 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001161 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001162 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001163 return transport, protocol
1164
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001165 def get_exception_handler(self):
1166 """Return an exception handler, or None if the default one is in use.
1167 """
1168 return self._exception_handler
1169
Yury Selivanov569efa22014-02-18 18:02:19 -05001170 def set_exception_handler(self, handler):
1171 """Set handler as the new event loop exception handler.
1172
1173 If handler is None, the default exception handler will
1174 be set.
1175
1176 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001177 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001178 will be a reference to the active event loop, 'context'
1179 will be a dict object (see `call_exception_handler()`
1180 documentation for details about context).
1181 """
1182 if handler is not None and not callable(handler):
1183 raise TypeError('A callable object or None is expected, '
1184 'got {!r}'.format(handler))
1185 self._exception_handler = handler
1186
1187 def default_exception_handler(self, context):
1188 """Default exception handler.
1189
1190 This is called when an exception occurs and no exception
1191 handler is set, and can be called by a custom exception
1192 handler that wants to defer to the default behavior.
1193
Victor Stinneracdb7822014-07-14 18:33:40 +02001194 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001195 `call_exception_handler()`.
1196 """
1197 message = context.get('message')
1198 if not message:
1199 message = 'Unhandled exception in event loop'
1200
1201 exception = context.get('exception')
1202 if exception is not None:
1203 exc_info = (type(exception), exception, exception.__traceback__)
1204 else:
1205 exc_info = False
1206
Victor Stinnerff018e42015-01-28 00:30:40 +01001207 if ('source_traceback' not in context
1208 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001209 and self._current_handle._source_traceback):
1210 context['handle_traceback'] = self._current_handle._source_traceback
1211
Yury Selivanov569efa22014-02-18 18:02:19 -05001212 log_lines = [message]
1213 for key in sorted(context):
1214 if key in {'message', 'exception'}:
1215 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001216 value = context[key]
1217 if key == 'source_traceback':
1218 tb = ''.join(traceback.format_list(value))
1219 value = 'Object created at (most recent call last):\n'
1220 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001221 elif key == 'handle_traceback':
1222 tb = ''.join(traceback.format_list(value))
1223 value = 'Handle created at (most recent call last):\n'
1224 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001225 else:
1226 value = repr(value)
1227 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001228
1229 logger.error('\n'.join(log_lines), exc_info=exc_info)
1230
1231 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001232 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001233
Victor Stinneracdb7822014-07-14 18:33:40 +02001234 The context argument is a dict containing the following keys:
1235
Yury Selivanov569efa22014-02-18 18:02:19 -05001236 - 'message': Error message;
1237 - 'exception' (optional): Exception object;
1238 - 'future' (optional): Future instance;
1239 - 'handle' (optional): Handle instance;
1240 - 'protocol' (optional): Protocol instance;
1241 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001242 - 'socket' (optional): Socket instance;
1243 - 'asyncgen' (optional): Asynchronous generator that caused
1244 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001245
Victor Stinneracdb7822014-07-14 18:33:40 +02001246 New keys maybe introduced in the future.
1247
1248 Note: do not overload this method in an event loop subclass.
1249 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001250 `set_exception_handler()` method.
1251 """
1252 if self._exception_handler is None:
1253 try:
1254 self.default_exception_handler(context)
1255 except Exception:
1256 # Second protection layer for unexpected errors
1257 # in the default implementation, as well as for subclassed
1258 # event loops with overloaded "default_exception_handler".
1259 logger.error('Exception in default exception handler',
1260 exc_info=True)
1261 else:
1262 try:
1263 self._exception_handler(self, context)
1264 except Exception as exc:
1265 # Exception in the user set custom exception handler.
1266 try:
1267 # Let's try default handler.
1268 self.default_exception_handler({
1269 'message': 'Unhandled error in exception handler',
1270 'exception': exc,
1271 'context': context,
1272 })
1273 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001274 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001275 # overloaded.
1276 logger.error('Exception in default exception handler '
1277 'while handling an unexpected error '
1278 'in custom exception handler',
1279 exc_info=True)
1280
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001281 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001282 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001283 assert isinstance(handle, events.Handle), 'A Handle is required here'
1284 if handle._cancelled:
1285 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001286 assert not isinstance(handle, events.TimerHandle)
1287 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001288
1289 def _add_callback_signalsafe(self, handle):
1290 """Like _add_callback() but called from a signal handler."""
1291 self._add_callback(handle)
1292 self._write_to_self()
1293
Yury Selivanov592ada92014-09-25 12:07:56 -04001294 def _timer_handle_cancelled(self, handle):
1295 """Notification that a TimerHandle has been cancelled."""
1296 if handle._scheduled:
1297 self._timer_cancelled_count += 1
1298
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001299 def _run_once(self):
1300 """Run one full iteration of the event loop.
1301
1302 This calls all currently ready callbacks, polls for I/O,
1303 schedules the resulting callbacks, and finally schedules
1304 'call_later' callbacks.
1305 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001306
Yury Selivanov592ada92014-09-25 12:07:56 -04001307 sched_count = len(self._scheduled)
1308 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1309 self._timer_cancelled_count / sched_count >
1310 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001311 # Remove delayed calls that were cancelled if their number
1312 # is too high
1313 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001314 for handle in self._scheduled:
1315 if handle._cancelled:
1316 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001317 else:
1318 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001319
Victor Stinner68da8fc2014-09-30 18:08:36 +02001320 heapq.heapify(new_scheduled)
1321 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001322 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001323 else:
1324 # Remove delayed calls that were cancelled from head of queue.
1325 while self._scheduled and self._scheduled[0]._cancelled:
1326 self._timer_cancelled_count -= 1
1327 handle = heapq.heappop(self._scheduled)
1328 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001329
1330 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001331 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001332 timeout = 0
1333 elif self._scheduled:
1334 # Compute the desired timeout.
1335 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001336 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001337
Victor Stinner770e48d2014-07-11 11:58:33 +02001338 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001339 t0 = self.time()
1340 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001341 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001342 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001343 level = logging.INFO
1344 else:
1345 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001346 nevent = len(event_list)
1347 if timeout is None:
1348 logger.log(level, 'poll took %.3f ms: %s events',
1349 dt * 1e3, nevent)
1350 elif nevent:
1351 logger.log(level,
1352 'poll %.3f ms took %.3f ms: %s events',
1353 timeout * 1e3, dt * 1e3, nevent)
1354 elif dt >= 1.0:
1355 logger.log(level,
1356 'poll %.3f ms took %.3f ms: timeout',
1357 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001358 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001359 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001360 self._process_events(event_list)
1361
1362 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001363 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001364 while self._scheduled:
1365 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001366 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001367 break
1368 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001369 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001370 self._ready.append(handle)
1371
1372 # This is the only place where callbacks are actually *called*.
1373 # All other places just add them to ready.
1374 # Note: We run all currently scheduled callbacks, but not any
1375 # callbacks scheduled by callbacks run this time around --
1376 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001377 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001378 ntodo = len(self._ready)
1379 for i in range(ntodo):
1380 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001381 if handle._cancelled:
1382 continue
1383 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001384 try:
1385 self._current_handle = handle
1386 t0 = self.time()
1387 handle._run()
1388 dt = self.time() - t0
1389 if dt >= self.slow_callback_duration:
1390 logger.warning('Executing %s took %.3f seconds',
1391 _format_handle(handle), dt)
1392 finally:
1393 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001394 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001395 handle._run()
1396 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001397
Yury Selivanove8944cb2015-05-12 11:43:04 -04001398 def _set_coroutine_wrapper(self, enabled):
1399 try:
1400 set_wrapper = sys.set_coroutine_wrapper
1401 get_wrapper = sys.get_coroutine_wrapper
1402 except AttributeError:
1403 return
1404
1405 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001406 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001407 return
1408
1409 wrapper = coroutines.debug_wrapper
1410 current_wrapper = get_wrapper()
1411
1412 if enabled:
1413 if current_wrapper not in (None, wrapper):
1414 warnings.warn(
1415 "loop.set_debug(True): cannot set debug coroutine "
1416 "wrapper; another wrapper is already set %r" %
1417 current_wrapper, RuntimeWarning)
1418 else:
1419 set_wrapper(wrapper)
1420 self._coroutine_wrapper_set = True
1421 else:
1422 if current_wrapper not in (None, wrapper):
1423 warnings.warn(
1424 "loop.set_debug(False): cannot unset debug coroutine "
1425 "wrapper; another wrapper was set %r" %
1426 current_wrapper, RuntimeWarning)
1427 else:
1428 set_wrapper(None)
1429 self._coroutine_wrapper_set = False
1430
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001431 def get_debug(self):
1432 return self._debug
1433
1434 def set_debug(self, enabled):
1435 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001436
Yury Selivanove8944cb2015-05-12 11:43:04 -04001437 if self.is_running():
1438 self._set_coroutine_wrapper(enabled)