blob: 03935ea94ba53018ac7e624384d6fa1805c8ab85 [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Base implementation of event loop.
2
3The event loop can be broken up into a multiplexer (the part
Victor Stinneracdb7822014-07-14 18:33:40 +02004responsible for notifying us of I/O events) and the event loop proper,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07005which wraps a multiplexer with functionality for scheduling callbacks,
6immediately or at a given time in the future.
7
8Whenever a public API takes a callback, subsequent positional
9arguments will be passed to the callback if/when it is called. This
10avoids the proliferation of trivial lambdas implementing closures.
11Keyword arguments for the callback are not supported; this is a
12conscious design decision, leaving the door open for keyword arguments
13to modify the meaning of the API call itself.
14"""
15
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import collections
17import concurrent.futures
18import heapq
Victor Stinner0e6f52a2014-06-20 17:34:15 +020019import inspect
Victor Stinner5e4a7d82015-09-21 18:33:43 +020020import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
24import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010025import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020027import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070028import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010029import warnings
Yury Selivanovf6d991d2016-09-15 13:10:51 -040030import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanov2a8911c2015-08-04 15:56:33 -040032from . import compat
Victor Stinnerf951d282014-06-29 00:46:45 +020033from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070034from . import events
35from . import futures
36from . import tasks
Victor Stinnerf951d282014-06-29 00:46:45 +020037from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070038from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039
40
Victor Stinner8c1a4a22015-01-06 01:03:58 +010041__all__ = ['BaseEventLoop']
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042
43
44# Argument for default thread pool executor creation.
45_MAX_WORKERS = 5
46
Yury Selivanov592ada92014-09-25 12:07:56 -040047# Minimum number of _scheduled timer handles before cleanup of
48# cancelled handles is performed.
49_MIN_SCHEDULED_TIMER_HANDLES = 100
50
51# Minimum fraction of _scheduled timer handles that are cancelled
52# before cleanup of cancelled handles is performed.
53_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070054
Victor Stinnerc94a93a2016-04-01 21:43:39 +020055# Exceptions which must not call the exception handler in fatal error
56# methods (_fatal_error())
57_FATAL_ERROR_IGNORE = (BrokenPipeError,
58 ConnectionResetError, ConnectionAbortedError)
59
60
Victor Stinner0e6f52a2014-06-20 17:34:15 +020061def _format_handle(handle):
62 cb = handle._callback
63 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
64 # format the task
65 return repr(cb.__self__)
66 else:
67 return str(handle)
68
69
Victor Stinneracdb7822014-07-14 18:33:40 +020070def _format_pipe(fd):
71 if fd == subprocess.PIPE:
72 return '<pipe>'
73 elif fd == subprocess.STDOUT:
74 return '<stdout>'
75 else:
76 return repr(fd)
77
78
Yury Selivanov5587d7c2016-09-15 15:45:07 -040079def _set_reuseport(sock):
80 if not hasattr(socket, 'SO_REUSEPORT'):
81 raise ValueError('reuse_port not supported by socket module')
82 else:
83 try:
84 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
85 except OSError:
86 raise ValueError('reuse_port not supported by socket module, '
87 'SO_REUSEPORT defined but not implemented.')
88
89
Yury Selivanovd5c2a622015-12-16 19:31:17 -050090# Linux's sock.type is a bitmask that can include extra info about socket.
91_SOCKET_TYPE_MASK = 0
92if hasattr(socket, 'SOCK_NONBLOCK'):
93 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
94if hasattr(socket, 'SOCK_CLOEXEC'):
95 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
96
97
Yury Selivanovd5c2a622015-12-16 19:31:17 -050098def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040099 # Try to skip getaddrinfo if "host" is already an IP. Users might have
100 # handled name resolution in their own code and pass in resolved IPs.
101 if not hasattr(socket, 'inet_pton'):
102 return
103
104 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
105 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500106 return None
107
108 type &= ~_SOCKET_TYPE_MASK
109 if type == socket.SOCK_STREAM:
110 proto = socket.IPPROTO_TCP
111 elif type == socket.SOCK_DGRAM:
112 proto = socket.IPPROTO_UDP
113 else:
114 return None
115
Yury Selivanova7146162016-06-02 16:51:07 -0400116 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400117 port = 0
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 Selivanovf6d991d2016-09-15 13:10:51 -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
263
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 Selivanovf6d991d2016-09-15 13:10:51 -0400358 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
377 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.
380 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 Selivanovf6d991d2016-09-15 13:10:51 -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 Selivanovf6d991d2016-09-15 13:10:51 -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():
499 warnings.warn("unclosed event loop %r" % self, ResourceWarning)
500 if not self.is_running():
501 self.close()
502
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700503 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200504 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100505 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506
507 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200508 """Return the time according to the event loop's clock.
509
510 This is a float expressed in seconds since an epoch, but the
511 epoch, precision, accuracy and drift are unspecified and may
512 differ per event loop.
513 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 return time.monotonic()
515
516 def call_later(self, delay, callback, *args):
517 """Arrange for a callback to be called at a given time.
518
519 Return a Handle: an opaque object with a cancel() method that
520 can be used to cancel the call.
521
522 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200523 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 Each callback will be called exactly once. If two callbacks
526 are scheduled for exactly the same time, it undefined which
527 will be called first.
528
529 Any positional arguments after the callback will be passed to
530 the callback when it is called.
531 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200532 timer = self.call_at(self.time() + delay, callback, *args)
533 if timer._source_traceback:
534 del timer._source_traceback[-1]
535 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700536
537 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200538 """Like call_later(), but uses an absolute time.
539
540 Absolute time corresponds to the event loop's time() method.
541 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100542 if (coroutines.iscoroutine(callback)
543 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100544 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100545 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100546 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100547 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500548 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200549 if timer._source_traceback:
550 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400552 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700553 return timer
554
555 def call_soon(self, callback, *args):
556 """Arrange for a callback to be called as soon as possible.
557
Victor Stinneracdb7822014-07-14 18:33:40 +0200558 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700559 order in which they are registered. Each callback will be
560 called exactly once.
561
562 Any positional arguments after the callback will be passed to
563 the callback when it is called.
564 """
Victor Stinner956de692014-12-26 21:07:52 +0100565 if self._debug:
566 self._check_thread()
567 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200568 if handle._source_traceback:
569 del handle._source_traceback[-1]
570 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100571
Victor Stinner956de692014-12-26 21:07:52 +0100572 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100573 if (coroutines.iscoroutine(callback)
574 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100575 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100576 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500577 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200578 if handle._source_traceback:
579 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700580 self._ready.append(handle)
581 return handle
582
Victor Stinner956de692014-12-26 21:07:52 +0100583 def _check_thread(self):
584 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100585
Victor Stinneracdb7822014-07-14 18:33:40 +0200586 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100587 likely behave incorrectly when the assumption is violated.
588
Victor Stinneracdb7822014-07-14 18:33:40 +0200589 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100590 responsible for checking this condition for performance reasons.
591 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100592 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200593 return
Victor Stinner956de692014-12-26 21:07:52 +0100594 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100595 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100596 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200597 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100598 "than the current one")
599
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200601 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100602 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200603 if handle._source_traceback:
604 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605 self._write_to_self()
606 return handle
607
Yury Selivanov740169c2015-05-11 14:23:38 -0400608 def run_in_executor(self, executor, func, *args):
609 if (coroutines.iscoroutine(func)
610 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100611 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100612 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400613 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700614 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400615 assert not isinstance(func, events.TimerHandle)
616 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400617 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700618 f.set_result(None)
619 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400620 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 if executor is None:
622 executor = self._default_executor
623 if executor is None:
624 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
625 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400626 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700627
628 def set_default_executor(self, executor):
629 self._default_executor = executor
630
Victor Stinnere912e652014-07-12 03:11:53 +0200631 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
632 msg = ["%s:%r" % (host, port)]
633 if family:
634 msg.append('family=%r' % family)
635 if type:
636 msg.append('type=%r' % type)
637 if proto:
638 msg.append('proto=%r' % proto)
639 if flags:
640 msg.append('flags=%r' % flags)
641 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200642 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200643
644 t0 = self.time()
645 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
646 dt = self.time() - t0
647
Victor Stinneracdb7822014-07-14 18:33:40 +0200648 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200649 % (msg, dt * 1e3, addrinfo))
650 if dt >= self.slow_callback_duration:
651 logger.info(msg)
652 else:
653 logger.debug(msg)
654 return addrinfo
655
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700656 def getaddrinfo(self, host, port, *,
657 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400658 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200659 return self.run_in_executor(None, self._getaddrinfo_debug,
660 host, port, family, type, proto, flags)
661 else:
662 return self.run_in_executor(None, socket.getaddrinfo,
663 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664
665 def getnameinfo(self, sockaddr, flags=0):
666 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
667
Victor Stinnerf951d282014-06-29 00:46:45 +0200668 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700669 def create_connection(self, protocol_factory, host=None, port=None, *,
670 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700671 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200672 """Connect to a TCP server.
673
674 Create a streaming transport connection to a given Internet host and
675 port: socket family AF_INET or socket.AF_INET6 depending on host (or
676 family if specified), socket type SOCK_STREAM. protocol_factory must be
677 a callable returning a protocol instance.
678
679 This method is a coroutine which will try to establish the connection
680 in the background. When successful, the coroutine returns a
681 (transport, protocol) pair.
682 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700683 if server_hostname is not None and not ssl:
684 raise ValueError('server_hostname is only meaningful with ssl')
685
686 if server_hostname is None and ssl:
687 # Use host as default for server_hostname. It is an error
688 # if host is empty or not set, e.g. when an
689 # already-connected socket was passed or when only a port
690 # is given. To avoid this error, you can pass
691 # server_hostname='' -- this will bypass the hostname
692 # check. (This also means that if host is a numeric
693 # IP/IPv6 address, we will attempt to verify that exact
694 # address; this will probably fail, but it is possible to
695 # create a certificate for a specific IP address, so we
696 # don't judge it here.)
697 if not host:
698 raise ValueError('You must set server_hostname '
699 'when using ssl without a host')
700 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700701
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700702 if host is not None or port is not None:
703 if sock is not None:
704 raise ValueError(
705 'host/port and sock can not be specified at the same time')
706
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400707 f1 = _ensure_resolved((host, port), family=family,
708 type=socket.SOCK_STREAM, proto=proto,
709 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700710 fs = [f1]
711 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400712 f2 = _ensure_resolved(local_addr, family=family,
713 type=socket.SOCK_STREAM, proto=proto,
714 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700715 fs.append(f2)
716 else:
717 f2 = None
718
719 yield from tasks.wait(fs, loop=self)
720
721 infos = f1.result()
722 if not infos:
723 raise OSError('getaddrinfo() returned empty list')
724 if f2 is not None:
725 laddr_infos = f2.result()
726 if not laddr_infos:
727 raise OSError('getaddrinfo() returned empty list')
728
729 exceptions = []
730 for family, type, proto, cname, address in infos:
731 try:
732 sock = socket.socket(family=family, type=type, proto=proto)
733 sock.setblocking(False)
734 if f2 is not None:
735 for _, _, _, _, laddr in laddr_infos:
736 try:
737 sock.bind(laddr)
738 break
739 except OSError as exc:
740 exc = OSError(
741 exc.errno, 'error while '
742 'attempting to bind on address '
743 '{!r}: {}'.format(
744 laddr, exc.strerror.lower()))
745 exceptions.append(exc)
746 else:
747 sock.close()
748 sock = None
749 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200750 if self._debug:
751 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700752 yield from self.sock_connect(sock, address)
753 except OSError as exc:
754 if sock is not None:
755 sock.close()
756 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200757 except:
758 if sock is not None:
759 sock.close()
760 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700761 else:
762 break
763 else:
764 if len(exceptions) == 1:
765 raise exceptions[0]
766 else:
767 # If they all have the same str(), raise one.
768 model = str(exceptions[0])
769 if all(str(exc) == model for exc in exceptions):
770 raise exceptions[0]
771 # Raise a combined exception so the user can see all
772 # the various error messages.
773 raise OSError('Multiple exceptions: {}'.format(
774 ', '.join(str(exc) for exc in exceptions)))
775
776 elif sock is None:
777 raise ValueError(
778 'host and port was not specified and no sock specified')
779
Yury Selivanovb057c522014-02-18 12:15:06 -0500780 transport, protocol = yield from self._create_connection_transport(
781 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200782 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200783 # Get the socket from the transport because SSL transport closes
784 # the old socket and creates a new SSL socket
785 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200786 logger.debug("%r connected to %s:%r: (%r, %r)",
787 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500788 return transport, protocol
789
Victor Stinnerf951d282014-06-29 00:46:45 +0200790 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500791 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400792 server_hostname, server_side=False):
793
794 sock.setblocking(False)
795
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700796 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400797 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700798 if ssl:
799 sslcontext = None if isinstance(ssl, bool) else ssl
800 transport = self._make_ssl_transport(
801 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400802 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700803 else:
804 transport = self._make_socket_transport(sock, protocol, waiter)
805
Victor Stinner29ad0112015-01-15 00:04:21 +0100806 try:
807 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100808 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100809 transport.close()
810 raise
811
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700812 return transport, protocol
813
Victor Stinnerf951d282014-06-29 00:46:45 +0200814 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700815 def create_datagram_endpoint(self, protocol_factory,
816 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700817 family=0, proto=0, flags=0,
818 reuse_address=None, reuse_port=None,
819 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700820 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700821 if sock is not None:
822 if (local_addr or remote_addr or
823 family or proto or flags or
824 reuse_address or reuse_port or allow_broadcast):
825 # show the problematic kwargs in exception msg
826 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
827 family=family, proto=proto, flags=flags,
828 reuse_address=reuse_address, reuse_port=reuse_port,
829 allow_broadcast=allow_broadcast)
830 problems = ', '.join(
831 '{}={}'.format(k, v) for k, v in opts.items() if v)
832 raise ValueError(
833 'socket modifier keyword arguments can not be used '
834 'when sock is specified. ({})'.format(problems))
835 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700836 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700837 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700838 if not (local_addr or remote_addr):
839 if family == 0:
840 raise ValueError('unexpected address family')
841 addr_pairs_info = (((family, proto), (None, None)),)
842 else:
843 # join address by (family, protocol)
844 addr_infos = collections.OrderedDict()
845 for idx, addr in ((0, local_addr), (1, remote_addr)):
846 if addr is not None:
847 assert isinstance(addr, tuple) and len(addr) == 2, (
848 '2-tuple is expected')
849
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400850 infos = yield from _ensure_resolved(
851 addr, family=family, type=socket.SOCK_DGRAM,
852 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700853 if not infos:
854 raise OSError('getaddrinfo() returned empty list')
855
856 for fam, _, pro, _, address in infos:
857 key = (fam, pro)
858 if key not in addr_infos:
859 addr_infos[key] = [None, None]
860 addr_infos[key][idx] = address
861
862 # each addr has to have info for each (family, proto) pair
863 addr_pairs_info = [
864 (key, addr_pair) for key, addr_pair in addr_infos.items()
865 if not ((local_addr and addr_pair[0] is None) or
866 (remote_addr and addr_pair[1] is None))]
867
868 if not addr_pairs_info:
869 raise ValueError('can not get address information')
870
871 exceptions = []
872
873 if reuse_address is None:
874 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
875
876 for ((family, proto),
877 (local_address, remote_address)) in addr_pairs_info:
878 sock = None
879 r_addr = None
880 try:
881 sock = socket.socket(
882 family=family, type=socket.SOCK_DGRAM, proto=proto)
883 if reuse_address:
884 sock.setsockopt(
885 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
886 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400887 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700888 if allow_broadcast:
889 sock.setsockopt(
890 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
891 sock.setblocking(False)
892
893 if local_addr:
894 sock.bind(local_address)
895 if remote_addr:
896 yield from self.sock_connect(sock, remote_address)
897 r_addr = remote_address
898 except OSError as exc:
899 if sock is not None:
900 sock.close()
901 exceptions.append(exc)
902 except:
903 if sock is not None:
904 sock.close()
905 raise
906 else:
907 break
908 else:
909 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700910
911 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400912 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700913 transport = self._make_datagram_transport(
914 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200915 if self._debug:
916 if local_addr:
917 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
918 "created: (%r, %r)",
919 local_addr, remote_addr, transport, protocol)
920 else:
921 logger.debug("Datagram endpoint remote_addr=%r created: "
922 "(%r, %r)",
923 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100924
925 try:
926 yield from waiter
927 except:
928 transport.close()
929 raise
930
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700931 return transport, protocol
932
Victor Stinnerf951d282014-06-29 00:46:45 +0200933 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200934 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400935 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200936 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400937 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200938 if not infos:
939 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
940 return infos
941
942 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700943 def create_server(self, protocol_factory, host=None, port=None,
944 *,
945 family=socket.AF_UNSPEC,
946 flags=socket.AI_PASSIVE,
947 sock=None,
948 backlog=100,
949 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700950 reuse_address=None,
951 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200952 """Create a TCP server.
953
954 The host parameter can be a string, in that case the TCP server is bound
955 to host and port.
956
957 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500958 the TCP server is bound to all hosts of the sequence. If a host
959 appears multiple times (possibly indirectly e.g. when hostnames
960 resolve to the same IP address), the server is only bound once to that
961 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200962
Victor Stinneracdb7822014-07-14 18:33:40 +0200963 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200964
965 This method is a coroutine.
966 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700967 if isinstance(ssl, bool):
968 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700969 if host is not None or port is not None:
970 if sock is not None:
971 raise ValueError(
972 'host/port and sock can not be specified at the same time')
973
974 AF_INET6 = getattr(socket, 'AF_INET6', 0)
975 if reuse_address is None:
976 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
977 sockets = []
978 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200979 hosts = [None]
980 elif (isinstance(host, str) or
981 not isinstance(host, collections.Iterable)):
982 hosts = [host]
983 else:
984 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700985
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200986 fs = [self._create_server_getaddrinfo(host, port, family=family,
987 flags=flags)
988 for host in hosts]
989 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500990 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700991
992 completed = False
993 try:
994 for res in infos:
995 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700996 try:
997 sock = socket.socket(af, socktype, proto)
998 except socket.error:
999 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001000 if self._debug:
1001 logger.warning('create_server() failed to create '
1002 'socket.socket(%r, %r, %r)',
1003 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001004 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001005 sockets.append(sock)
1006 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001007 sock.setsockopt(
1008 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1009 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001010 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001011 # Disable IPv4/IPv6 dual stack support (enabled by
1012 # default on Linux) which makes a single socket
1013 # listen on both address families.
1014 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1015 sock.setsockopt(socket.IPPROTO_IPV6,
1016 socket.IPV6_V6ONLY,
1017 True)
1018 try:
1019 sock.bind(sa)
1020 except OSError as err:
1021 raise OSError(err.errno, 'error while attempting '
1022 'to bind on address %r: %s'
1023 % (sa, err.strerror.lower()))
1024 completed = True
1025 finally:
1026 if not completed:
1027 for sock in sockets:
1028 sock.close()
1029 else:
1030 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001031 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001032 sockets = [sock]
1033
1034 server = Server(self, sockets)
1035 for sock in sockets:
1036 sock.listen(backlog)
1037 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001038 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001039 if self._debug:
1040 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001041 return server
1042
Victor Stinnerf951d282014-06-29 00:46:45 +02001043 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001044 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1045 """Handle an accepted connection.
1046
1047 This is used by servers that accept connections outside of
1048 asyncio but that use asyncio to handle connections.
1049
1050 This method is a coroutine. When completed, the coroutine
1051 returns a (transport, protocol) pair.
1052 """
1053 transport, protocol = yield from self._create_connection_transport(
1054 sock, protocol_factory, ssl, '', server_side=True)
1055 if self._debug:
1056 # Get the socket from the transport because SSL transport closes
1057 # the old socket and creates a new SSL socket
1058 sock = transport.get_extra_info('socket')
1059 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1060 return transport, protocol
1061
1062 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001063 def connect_read_pipe(self, protocol_factory, pipe):
1064 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001065 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001066 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001067
1068 try:
1069 yield from waiter
1070 except:
1071 transport.close()
1072 raise
1073
Victor Stinneracdb7822014-07-14 18:33:40 +02001074 if self._debug:
1075 logger.debug('Read pipe %r connected: (%r, %r)',
1076 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001077 return transport, protocol
1078
Victor Stinnerf951d282014-06-29 00:46:45 +02001079 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001080 def connect_write_pipe(self, protocol_factory, pipe):
1081 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001082 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001083 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001084
1085 try:
1086 yield from waiter
1087 except:
1088 transport.close()
1089 raise
1090
Victor Stinneracdb7822014-07-14 18:33:40 +02001091 if self._debug:
1092 logger.debug('Write pipe %r connected: (%r, %r)',
1093 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001094 return transport, protocol
1095
Victor Stinneracdb7822014-07-14 18:33:40 +02001096 def _log_subprocess(self, msg, stdin, stdout, stderr):
1097 info = [msg]
1098 if stdin is not None:
1099 info.append('stdin=%s' % _format_pipe(stdin))
1100 if stdout is not None and stderr == subprocess.STDOUT:
1101 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1102 else:
1103 if stdout is not None:
1104 info.append('stdout=%s' % _format_pipe(stdout))
1105 if stderr is not None:
1106 info.append('stderr=%s' % _format_pipe(stderr))
1107 logger.debug(' '.join(info))
1108
Victor Stinnerf951d282014-06-29 00:46:45 +02001109 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001110 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1111 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1112 universal_newlines=False, shell=True, bufsize=0,
1113 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001114 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001115 raise ValueError("cmd must be a string")
1116 if universal_newlines:
1117 raise ValueError("universal_newlines must be False")
1118 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001119 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001120 if bufsize != 0:
1121 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001122 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001123 if self._debug:
1124 # don't log parameters: they may contain sensitive information
1125 # (password) and may be too long
1126 debug_log = 'run shell command %r' % cmd
1127 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001128 transport = yield from self._make_subprocess_transport(
1129 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001130 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001131 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001132 return transport, protocol
1133
Victor Stinnerf951d282014-06-29 00:46:45 +02001134 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001135 def subprocess_exec(self, protocol_factory, program, *args,
1136 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1137 stderr=subprocess.PIPE, universal_newlines=False,
1138 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001139 if universal_newlines:
1140 raise ValueError("universal_newlines must be False")
1141 if shell:
1142 raise ValueError("shell must be False")
1143 if bufsize != 0:
1144 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001145 popen_args = (program,) + args
1146 for arg in popen_args:
1147 if not isinstance(arg, (str, bytes)):
1148 raise TypeError("program arguments must be "
1149 "a bytes or text string, not %s"
1150 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001151 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001152 if self._debug:
1153 # don't log parameters: they may contain sensitive information
1154 # (password) and may be too long
1155 debug_log = 'execute program %r' % program
1156 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001157 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001158 protocol, popen_args, False, stdin, stdout, stderr,
1159 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001160 if self._debug:
Yury Selivanov4357cf62016-09-15 13:49:08 -04001161 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001162 return transport, protocol
1163
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001164 def get_exception_handler(self):
1165 """Return an exception handler, or None if the default one is in use.
1166 """
1167 return self._exception_handler
1168
Yury Selivanov569efa22014-02-18 18:02:19 -05001169 def set_exception_handler(self, handler):
1170 """Set handler as the new event loop exception handler.
1171
1172 If handler is None, the default exception handler will
1173 be set.
1174
1175 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001176 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001177 will be a reference to the active event loop, 'context'
1178 will be a dict object (see `call_exception_handler()`
1179 documentation for details about context).
1180 """
1181 if handler is not None and not callable(handler):
1182 raise TypeError('A callable object or None is expected, '
1183 'got {!r}'.format(handler))
1184 self._exception_handler = handler
1185
1186 def default_exception_handler(self, context):
1187 """Default exception handler.
1188
1189 This is called when an exception occurs and no exception
1190 handler is set, and can be called by a custom exception
1191 handler that wants to defer to the default behavior.
1192
Victor Stinneracdb7822014-07-14 18:33:40 +02001193 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001194 `call_exception_handler()`.
1195 """
1196 message = context.get('message')
1197 if not message:
1198 message = 'Unhandled exception in event loop'
1199
1200 exception = context.get('exception')
1201 if exception is not None:
1202 exc_info = (type(exception), exception, exception.__traceback__)
1203 else:
1204 exc_info = False
1205
Victor Stinnerff018e42015-01-28 00:30:40 +01001206 if ('source_traceback' not in context
1207 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001208 and self._current_handle._source_traceback):
1209 context['handle_traceback'] = self._current_handle._source_traceback
1210
Yury Selivanov569efa22014-02-18 18:02:19 -05001211 log_lines = [message]
1212 for key in sorted(context):
1213 if key in {'message', 'exception'}:
1214 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001215 value = context[key]
1216 if key == 'source_traceback':
1217 tb = ''.join(traceback.format_list(value))
1218 value = 'Object created at (most recent call last):\n'
1219 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001220 elif key == 'handle_traceback':
1221 tb = ''.join(traceback.format_list(value))
1222 value = 'Handle created at (most recent call last):\n'
1223 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001224 else:
1225 value = repr(value)
1226 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001227
1228 logger.error('\n'.join(log_lines), exc_info=exc_info)
1229
1230 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001231 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001232
Victor Stinneracdb7822014-07-14 18:33:40 +02001233 The context argument is a dict containing the following keys:
1234
Yury Selivanov569efa22014-02-18 18:02:19 -05001235 - 'message': Error message;
1236 - 'exception' (optional): Exception object;
1237 - 'future' (optional): Future instance;
1238 - 'handle' (optional): Handle instance;
1239 - 'protocol' (optional): Protocol instance;
1240 - 'transport' (optional): Transport instance;
Yury Selivanov4357cf62016-09-15 13:49:08 -04001241 - 'socket' (optional): Socket instance;
1242 - 'asyncgen' (optional): Asynchronous generator that caused
1243 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001244
Victor Stinneracdb7822014-07-14 18:33:40 +02001245 New keys maybe introduced in the future.
1246
1247 Note: do not overload this method in an event loop subclass.
1248 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001249 `set_exception_handler()` method.
1250 """
1251 if self._exception_handler is None:
1252 try:
1253 self.default_exception_handler(context)
1254 except Exception:
1255 # Second protection layer for unexpected errors
1256 # in the default implementation, as well as for subclassed
1257 # event loops with overloaded "default_exception_handler".
1258 logger.error('Exception in default exception handler',
1259 exc_info=True)
1260 else:
1261 try:
1262 self._exception_handler(self, context)
1263 except Exception as exc:
1264 # Exception in the user set custom exception handler.
1265 try:
1266 # Let's try default handler.
1267 self.default_exception_handler({
1268 'message': 'Unhandled error in exception handler',
1269 'exception': exc,
1270 'context': context,
1271 })
1272 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001273 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001274 # overloaded.
1275 logger.error('Exception in default exception handler '
1276 'while handling an unexpected error '
1277 'in custom exception handler',
1278 exc_info=True)
1279
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001280 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001281 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001282 assert isinstance(handle, events.Handle), 'A Handle is required here'
1283 if handle._cancelled:
1284 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001285 assert not isinstance(handle, events.TimerHandle)
1286 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001287
1288 def _add_callback_signalsafe(self, handle):
1289 """Like _add_callback() but called from a signal handler."""
1290 self._add_callback(handle)
1291 self._write_to_self()
1292
Yury Selivanov592ada92014-09-25 12:07:56 -04001293 def _timer_handle_cancelled(self, handle):
1294 """Notification that a TimerHandle has been cancelled."""
1295 if handle._scheduled:
1296 self._timer_cancelled_count += 1
1297
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001298 def _run_once(self):
1299 """Run one full iteration of the event loop.
1300
1301 This calls all currently ready callbacks, polls for I/O,
1302 schedules the resulting callbacks, and finally schedules
1303 'call_later' callbacks.
1304 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001305
Yury Selivanov592ada92014-09-25 12:07:56 -04001306 sched_count = len(self._scheduled)
1307 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1308 self._timer_cancelled_count / sched_count >
1309 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001310 # Remove delayed calls that were cancelled if their number
1311 # is too high
1312 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001313 for handle in self._scheduled:
1314 if handle._cancelled:
1315 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001316 else:
1317 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001318
Victor Stinner68da8fc2014-09-30 18:08:36 +02001319 heapq.heapify(new_scheduled)
1320 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001321 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001322 else:
1323 # Remove delayed calls that were cancelled from head of queue.
1324 while self._scheduled and self._scheduled[0]._cancelled:
1325 self._timer_cancelled_count -= 1
1326 handle = heapq.heappop(self._scheduled)
1327 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001328
1329 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001330 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001331 timeout = 0
1332 elif self._scheduled:
1333 # Compute the desired timeout.
1334 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001335 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001336
Victor Stinner770e48d2014-07-11 11:58:33 +02001337 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001338 t0 = self.time()
1339 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001340 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001341 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001342 level = logging.INFO
1343 else:
1344 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001345 nevent = len(event_list)
1346 if timeout is None:
1347 logger.log(level, 'poll took %.3f ms: %s events',
1348 dt * 1e3, nevent)
1349 elif nevent:
1350 logger.log(level,
1351 'poll %.3f ms took %.3f ms: %s events',
1352 timeout * 1e3, dt * 1e3, nevent)
1353 elif dt >= 1.0:
1354 logger.log(level,
1355 'poll %.3f ms took %.3f ms: timeout',
1356 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001357 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001358 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001359 self._process_events(event_list)
1360
1361 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001362 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001363 while self._scheduled:
1364 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001365 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001366 break
1367 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001368 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001369 self._ready.append(handle)
1370
1371 # This is the only place where callbacks are actually *called*.
1372 # All other places just add them to ready.
1373 # Note: We run all currently scheduled callbacks, but not any
1374 # callbacks scheduled by callbacks run this time around --
1375 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001376 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001377 ntodo = len(self._ready)
1378 for i in range(ntodo):
1379 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001380 if handle._cancelled:
1381 continue
1382 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001383 try:
1384 self._current_handle = handle
1385 t0 = self.time()
1386 handle._run()
1387 dt = self.time() - t0
1388 if dt >= self.slow_callback_duration:
1389 logger.warning('Executing %s took %.3f seconds',
1390 _format_handle(handle), dt)
1391 finally:
1392 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001393 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001394 handle._run()
1395 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001396
Yury Selivanove8944cb2015-05-12 11:43:04 -04001397 def _set_coroutine_wrapper(self, enabled):
1398 try:
1399 set_wrapper = sys.set_coroutine_wrapper
1400 get_wrapper = sys.get_coroutine_wrapper
1401 except AttributeError:
1402 return
1403
1404 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001405 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001406 return
1407
1408 wrapper = coroutines.debug_wrapper
1409 current_wrapper = get_wrapper()
1410
1411 if enabled:
1412 if current_wrapper not in (None, wrapper):
1413 warnings.warn(
1414 "loop.set_debug(True): cannot set debug coroutine "
1415 "wrapper; another wrapper is already set %r" %
1416 current_wrapper, RuntimeWarning)
1417 else:
1418 set_wrapper(wrapper)
1419 self._coroutine_wrapper_set = True
1420 else:
1421 if current_wrapper not in (None, wrapper):
1422 warnings.warn(
1423 "loop.set_debug(False): cannot unset debug coroutine "
1424 "wrapper; another wrapper was set %r" %
1425 current_wrapper, RuntimeWarning)
1426 else:
1427 set_wrapper(None)
1428 self._coroutine_wrapper_set = False
1429
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001430 def get_debug(self):
1431 return self._debug
1432
1433 def set_debug(self, enabled):
1434 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001435
Yury Selivanove8944cb2015-05-12 11:43:04 -04001436 if self.is_running():
1437 self._set_coroutine_wrapper(enabled)