blob: 58800617d974b6ded7ae241d6c1715c2a4fc9844 [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
Yury Selivanov592ada92014-09-25 12:07:56 -040044# Minimum number of _scheduled timer handles before cleanup of
45# cancelled handles is performed.
46_MIN_SCHEDULED_TIMER_HANDLES = 100
47
48# Minimum fraction of _scheduled timer handles that are cancelled
49# before cleanup of cancelled handles is performed.
50_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051
Victor Stinnerc94a93a2016-04-01 21:43:39 +020052# Exceptions which must not call the exception handler in fatal error
53# methods (_fatal_error())
54_FATAL_ERROR_IGNORE = (BrokenPipeError,
55 ConnectionResetError, ConnectionAbortedError)
56
57
Victor Stinner0e6f52a2014-06-20 17:34:15 +020058def _format_handle(handle):
59 cb = handle._callback
60 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
61 # format the task
62 return repr(cb.__self__)
63 else:
64 return str(handle)
65
66
Victor Stinneracdb7822014-07-14 18:33:40 +020067def _format_pipe(fd):
68 if fd == subprocess.PIPE:
69 return '<pipe>'
70 elif fd == subprocess.STDOUT:
71 return '<stdout>'
72 else:
73 return repr(fd)
74
75
Yury Selivanov5587d7c2016-09-15 15:45:07 -040076def _set_reuseport(sock):
77 if not hasattr(socket, 'SO_REUSEPORT'):
78 raise ValueError('reuse_port not supported by socket module')
79 else:
80 try:
81 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
82 except OSError:
83 raise ValueError('reuse_port not supported by socket module, '
84 'SO_REUSEPORT defined but not implemented.')
85
86
Yury Selivanovd5c2a622015-12-16 19:31:17 -050087# Linux's sock.type is a bitmask that can include extra info about socket.
88_SOCKET_TYPE_MASK = 0
89if hasattr(socket, 'SOCK_NONBLOCK'):
90 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
91if hasattr(socket, 'SOCK_CLOEXEC'):
92 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
93
94
Yury Selivanovd5c2a622015-12-16 19:31:17 -050095def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040096 # Try to skip getaddrinfo if "host" is already an IP. Users might have
97 # handled name resolution in their own code and pass in resolved IPs.
98 if not hasattr(socket, 'inet_pton'):
99 return
100
101 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
102 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500103 return None
104
105 type &= ~_SOCKET_TYPE_MASK
106 if type == socket.SOCK_STREAM:
107 proto = socket.IPPROTO_TCP
108 elif type == socket.SOCK_DGRAM:
109 proto = socket.IPPROTO_UDP
110 else:
111 return None
112
Yury Selivanova7146162016-06-02 16:51:07 -0400113 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400114 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700115 elif isinstance(port, bytes) and port == b'':
116 port = 0
117 elif isinstance(port, str) and port == '':
118 port = 0
119 else:
120 # If port's a service name like "http", don't skip getaddrinfo.
121 try:
122 port = int(port)
123 except (TypeError, ValueError):
124 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400125
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 if family == socket.AF_UNSPEC:
127 afs = [socket.AF_INET, socket.AF_INET6]
128 else:
129 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500130
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400131 if isinstance(host, bytes):
132 host = host.decode('idna')
133 if '%' in host:
134 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
135 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500136 return None
137
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500139 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 socket.inet_pton(af, host)
141 # The host has already been resolved.
142 return af, type, proto, '', (host, port)
143 except OSError:
144 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400146 # "host" is not an IP address.
147 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148
149
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
151 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500152 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400153 info = _ipaddr_info(host, port, family, type, proto)
154 if info is not None:
155 # "host" is already a resolved IP.
156 fut = loop.create_future()
157 fut.set_result([info])
158 return fut
159 else:
160 return loop.getaddrinfo(host, port, family=family, type=type,
161 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100162
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700163
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100164def _run_until_complete_cb(fut):
165 exc = fut._exception
166 if (isinstance(exc, BaseException)
167 and not isinstance(exc, Exception)):
168 # Issue #22429: run_forever() already finished, no need to
169 # stop it.
170 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800171 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100172
173
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174class Server(events.AbstractServer):
175
176 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200177 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700178 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200179 self._active_count = 0
180 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700181
Victor Stinnere912e652014-07-12 03:11:53 +0200182 def __repr__(self):
183 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
184
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200185 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 def _detach(self):
190 assert self._active_count > 0
191 self._active_count -= 1
192 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193 self._wakeup()
194
195 def close(self):
196 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 if sockets is None:
198 return
199 self.sockets = None
200 for sock in sockets:
201 self._loop._stop_serving(sock)
202 if self._active_count == 0:
203 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204
205 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 waiters = self._waiters
207 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208 for waiter in waiters:
209 if not waiter.done():
210 waiter.set_result(waiter)
211
Victor Stinnerf951d282014-06-29 00:46:45 +0200212 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200214 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700215 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400216 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 yield from waiter
219
220
221class BaseEventLoop(events.AbstractEventLoop):
222
223 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400224 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200225 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800226 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227 self._ready = collections.deque()
228 self._scheduled = []
229 self._default_executor = None
230 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100231 # Identifier of the thread running the event loop, or None if the
232 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100233 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100234 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500235 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400236 self.set_debug((not sys.flags.ignore_environment
237 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200238 # In debug mode, if the execution of a callback or a step of a task
239 # exceed this duration in seconds, the slow callback/task is logged.
240 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100241 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400242 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400243 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700244
Yury Selivanov0a91d482016-09-15 13:24:03 -0400245 if hasattr(sys, 'get_asyncgen_hooks'):
246 # Python >= 3.6
247 # A weak set of all asynchronous generators that are
248 # being iterated by the loop.
249 self._asyncgens = weakref.WeakSet()
250 else:
251 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700252
253 # Set to True when `loop.shutdown_asyncgens` is called.
254 self._asyncgens_shutdown_called = False
255
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200256 def __repr__(self):
257 return ('<%s running=%s closed=%s debug=%s>'
258 % (self.__class__.__name__, self.is_running(),
259 self.is_closed(), self.get_debug()))
260
Yury Selivanov7661db62016-05-16 15:38:39 -0400261 def create_future(self):
262 """Create a Future object attached to the loop."""
263 return futures.Future(loop=self)
264
Victor Stinner896a25a2014-07-08 11:29:25 +0200265 def create_task(self, coro):
266 """Schedule a coroutine object.
267
Victor Stinneracdb7822014-07-14 18:33:40 +0200268 Return a task object.
269 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100270 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400271 if self._task_factory is None:
272 task = tasks.Task(coro, loop=self)
273 if task._source_traceback:
274 del task._source_traceback[-1]
275 else:
276 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200277 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200278
Yury Selivanov740169c2015-05-11 14:23:38 -0400279 def set_task_factory(self, factory):
280 """Set a task factory that will be used by loop.create_task().
281
282 If factory is None the default task factory will be set.
283
284 If factory is a callable, it should have a signature matching
285 '(loop, coro)', where 'loop' will be a reference to the active
286 event loop, 'coro' will be a coroutine object. The callable
287 must return a Future.
288 """
289 if factory is not None and not callable(factory):
290 raise TypeError('task factory must be a callable or None')
291 self._task_factory = factory
292
293 def get_task_factory(self):
294 """Return a task factory, or None if the default one is in use."""
295 return self._task_factory
296
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 def _make_socket_transport(self, sock, protocol, waiter=None, *,
298 extra=None, server=None):
299 """Create socket transport."""
300 raise NotImplementedError
301
Victor Stinner15cc6782015-01-09 00:09:10 +0100302 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
303 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700304 extra=None, server=None):
305 """Create SSL transport."""
306 raise NotImplementedError
307
308 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200309 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700310 """Create datagram transport."""
311 raise NotImplementedError
312
313 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
314 extra=None):
315 """Create read pipe transport."""
316 raise NotImplementedError
317
318 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
319 extra=None):
320 """Create write pipe transport."""
321 raise NotImplementedError
322
Victor Stinnerf951d282014-06-29 00:46:45 +0200323 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700324 def _make_subprocess_transport(self, protocol, args, shell,
325 stdin, stdout, stderr, bufsize,
326 extra=None, **kwargs):
327 """Create subprocess transport."""
328 raise NotImplementedError
329
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700330 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200331 """Write a byte to self-pipe, to wake up the event loop.
332
333 This may be called from a different thread.
334
335 The subclass is responsible for implementing the self-pipe.
336 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700337 raise NotImplementedError
338
339 def _process_events(self, event_list):
340 """Process selector events."""
341 raise NotImplementedError
342
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200343 def _check_closed(self):
344 if self._closed:
345 raise RuntimeError('Event loop is closed')
346
Yury Selivanoveb636452016-09-08 22:01:51 -0700347 def _asyncgen_finalizer_hook(self, agen):
348 self._asyncgens.discard(agen)
349 if not self.is_closed():
350 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400351 # Wake up the loop if the finalizer was called from
352 # a different thread.
353 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700354
355 def _asyncgen_firstiter_hook(self, agen):
356 if self._asyncgens_shutdown_called:
357 warnings.warn(
358 "asynchronous generator {!r} was scheduled after "
359 "loop.shutdown_asyncgens() call".format(agen),
360 ResourceWarning, source=self)
361
362 self._asyncgens.add(agen)
363
364 @coroutine
365 def shutdown_asyncgens(self):
366 """Shutdown all active asynchronous generators."""
367 self._asyncgens_shutdown_called = True
368
Yury Selivanov0a91d482016-09-15 13:24:03 -0400369 if self._asyncgens is None or not len(self._asyncgens):
370 # If Python version is <3.6 or we don't have any asynchronous
371 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700372 return
373
374 closing_agens = list(self._asyncgens)
375 self._asyncgens.clear()
376
377 shutdown_coro = tasks.gather(
378 *[ag.aclose() for ag in closing_agens],
379 return_exceptions=True,
380 loop=self)
381
382 results = yield from shutdown_coro
383 for result, agen in zip(results, closing_agens):
384 if isinstance(result, Exception):
385 self.call_exception_handler({
386 'message': 'an error occurred during closing of '
387 'asynchronous generator {!r}'.format(agen),
388 'exception': result,
389 'asyncgen': agen
390 })
391
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700392 def run_forever(self):
393 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200394 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100395 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700396 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400397 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100398 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400399 if self._asyncgens is not None:
400 old_agen_hooks = sys.get_asyncgen_hooks()
401 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
402 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700403 try:
404 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800405 self._run_once()
406 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700407 break
408 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800409 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100410 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400411 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400412 if self._asyncgens is not None:
413 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700414
415 def run_until_complete(self, future):
416 """Run until the Future is done.
417
418 If the argument is a coroutine, it is wrapped in a Task.
419
Victor Stinneracdb7822014-07-14 18:33:40 +0200420 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700421 with the same coroutine twice -- it would wrap it in two
422 different Tasks and that can't be good.
423
424 Return the Future's result, or raise its exception.
425 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200426 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200427
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700428 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400429 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200430 if new_task:
431 # An exception is raised if the future didn't complete, so there
432 # is no need to log the "destroy pending task" message
433 future._log_destroy_pending = False
434
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100435 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200436 try:
437 self.run_forever()
438 except:
439 if new_task and future.done() and not future.cancelled():
440 # The coroutine raised a BaseException. Consume the exception
441 # to not log a warning, the caller doesn't have access to the
442 # local task.
443 future.exception()
444 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100445 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446 if not future.done():
447 raise RuntimeError('Event loop stopped before Future completed.')
448
449 return future.result()
450
451 def stop(self):
452 """Stop running the event loop.
453
Guido van Rossum41f69f42015-11-19 13:28:47 -0800454 Every callback already scheduled will still run. This simply informs
455 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700456 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800457 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700458
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200459 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700460 """Close the event loop.
461
462 This clears the queues and shuts down the executor,
463 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200464
465 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700466 """
Victor Stinner956de692014-12-26 21:07:52 +0100467 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200468 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200469 if self._closed:
470 return
Victor Stinnere912e652014-07-12 03:11:53 +0200471 if self._debug:
472 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400473 self._closed = True
474 self._ready.clear()
475 self._scheduled.clear()
476 executor = self._default_executor
477 if executor is not None:
478 self._default_executor = None
479 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200480
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200481 def is_closed(self):
482 """Returns True if the event loop was closed."""
483 return self._closed
484
Victor Stinner978a9af2015-01-29 17:50:58 +0100485 # On Python 3.3 and older, objects with a destructor part of a reference
486 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
487 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400488 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100489 def __del__(self):
490 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100491 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
492 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100493 if not self.is_running():
494 self.close()
495
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700496 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200497 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100498 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700499
500 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200501 """Return the time according to the event loop's clock.
502
503 This is a float expressed in seconds since an epoch, but the
504 epoch, precision, accuracy and drift are unspecified and may
505 differ per event loop.
506 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700507 return time.monotonic()
508
509 def call_later(self, delay, callback, *args):
510 """Arrange for a callback to be called at a given time.
511
512 Return a Handle: an opaque object with a cancel() method that
513 can be used to cancel the call.
514
515 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200516 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517
518 Each callback will be called exactly once. If two callbacks
519 are scheduled for exactly the same time, it undefined which
520 will be called first.
521
522 Any positional arguments after the callback will be passed to
523 the callback when it is called.
524 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200525 timer = self.call_at(self.time() + delay, callback, *args)
526 if timer._source_traceback:
527 del timer._source_traceback[-1]
528 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700529
530 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200531 """Like call_later(), but uses an absolute time.
532
533 Absolute time corresponds to the event loop's time() method.
534 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100535 if (coroutines.iscoroutine(callback)
536 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100537 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100538 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100539 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100540 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500541 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200542 if timer._source_traceback:
543 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400545 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700546 return timer
547
548 def call_soon(self, callback, *args):
549 """Arrange for a callback to be called as soon as possible.
550
Victor Stinneracdb7822014-07-14 18:33:40 +0200551 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552 order in which they are registered. Each callback will be
553 called exactly once.
554
555 Any positional arguments after the callback will be passed to
556 the callback when it is called.
557 """
Victor Stinner956de692014-12-26 21:07:52 +0100558 if self._debug:
559 self._check_thread()
560 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200561 if handle._source_traceback:
562 del handle._source_traceback[-1]
563 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100564
Victor Stinner956de692014-12-26 21:07:52 +0100565 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100566 if (coroutines.iscoroutine(callback)
567 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100568 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100569 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500570 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200571 if handle._source_traceback:
572 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573 self._ready.append(handle)
574 return handle
575
Victor Stinner956de692014-12-26 21:07:52 +0100576 def _check_thread(self):
577 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100578
Victor Stinneracdb7822014-07-14 18:33:40 +0200579 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100580 likely behave incorrectly when the assumption is violated.
581
Victor Stinneracdb7822014-07-14 18:33:40 +0200582 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100583 responsible for checking this condition for performance reasons.
584 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100585 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200586 return
Victor Stinner956de692014-12-26 21:07:52 +0100587 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100588 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100589 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200590 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100591 "than the current one")
592
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700593 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200594 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100595 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200596 if handle._source_traceback:
597 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 self._write_to_self()
599 return handle
600
Yury Selivanov740169c2015-05-11 14:23:38 -0400601 def run_in_executor(self, executor, func, *args):
602 if (coroutines.iscoroutine(func)
603 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100604 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100605 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400606 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700607 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400608 assert not isinstance(func, events.TimerHandle)
Yury Selivanov0de3de62016-10-05 18:28:09 -0400609 warnings.warn(
610 "Passing Handle to loop.run_in_executor() is deprecated",
611 DeprecationWarning)
Yury Selivanov740169c2015-05-11 14:23:38 -0400612 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400613 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700614 f.set_result(None)
615 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400616 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700617 if executor is None:
618 executor = self._default_executor
619 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400620 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400622 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623
624 def set_default_executor(self, executor):
625 self._default_executor = executor
626
Victor Stinnere912e652014-07-12 03:11:53 +0200627 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
628 msg = ["%s:%r" % (host, port)]
629 if family:
630 msg.append('family=%r' % family)
631 if type:
632 msg.append('type=%r' % type)
633 if proto:
634 msg.append('proto=%r' % proto)
635 if flags:
636 msg.append('flags=%r' % flags)
637 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200638 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200639
640 t0 = self.time()
641 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
642 dt = self.time() - t0
643
Victor Stinneracdb7822014-07-14 18:33:40 +0200644 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200645 % (msg, dt * 1e3, addrinfo))
646 if dt >= self.slow_callback_duration:
647 logger.info(msg)
648 else:
649 logger.debug(msg)
650 return addrinfo
651
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700652 def getaddrinfo(self, host, port, *,
653 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400654 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200655 return self.run_in_executor(None, self._getaddrinfo_debug,
656 host, port, family, type, proto, flags)
657 else:
658 return self.run_in_executor(None, socket.getaddrinfo,
659 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700660
661 def getnameinfo(self, sockaddr, flags=0):
662 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
663
Victor Stinnerf951d282014-06-29 00:46:45 +0200664 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665 def create_connection(self, protocol_factory, host=None, port=None, *,
666 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700667 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200668 """Connect to a TCP server.
669
670 Create a streaming transport connection to a given Internet host and
671 port: socket family AF_INET or socket.AF_INET6 depending on host (or
672 family if specified), socket type SOCK_STREAM. protocol_factory must be
673 a callable returning a protocol instance.
674
675 This method is a coroutine which will try to establish the connection
676 in the background. When successful, the coroutine returns a
677 (transport, protocol) pair.
678 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700679 if server_hostname is not None and not ssl:
680 raise ValueError('server_hostname is only meaningful with ssl')
681
682 if server_hostname is None and ssl:
683 # Use host as default for server_hostname. It is an error
684 # if host is empty or not set, e.g. when an
685 # already-connected socket was passed or when only a port
686 # is given. To avoid this error, you can pass
687 # server_hostname='' -- this will bypass the hostname
688 # check. (This also means that if host is a numeric
689 # IP/IPv6 address, we will attempt to verify that exact
690 # address; this will probably fail, but it is possible to
691 # create a certificate for a specific IP address, so we
692 # don't judge it here.)
693 if not host:
694 raise ValueError('You must set server_hostname '
695 'when using ssl without a host')
696 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700697
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700698 if host is not None or port is not None:
699 if sock is not None:
700 raise ValueError(
701 'host/port and sock can not be specified at the same time')
702
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400703 f1 = _ensure_resolved((host, port), family=family,
704 type=socket.SOCK_STREAM, proto=proto,
705 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700706 fs = [f1]
707 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400708 f2 = _ensure_resolved(local_addr, family=family,
709 type=socket.SOCK_STREAM, proto=proto,
710 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700711 fs.append(f2)
712 else:
713 f2 = None
714
715 yield from tasks.wait(fs, loop=self)
716
717 infos = f1.result()
718 if not infos:
719 raise OSError('getaddrinfo() returned empty list')
720 if f2 is not None:
721 laddr_infos = f2.result()
722 if not laddr_infos:
723 raise OSError('getaddrinfo() returned empty list')
724
725 exceptions = []
726 for family, type, proto, cname, address in infos:
727 try:
728 sock = socket.socket(family=family, type=type, proto=proto)
729 sock.setblocking(False)
730 if f2 is not None:
731 for _, _, _, _, laddr in laddr_infos:
732 try:
733 sock.bind(laddr)
734 break
735 except OSError as exc:
736 exc = OSError(
737 exc.errno, 'error while '
738 'attempting to bind on address '
739 '{!r}: {}'.format(
740 laddr, exc.strerror.lower()))
741 exceptions.append(exc)
742 else:
743 sock.close()
744 sock = None
745 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200746 if self._debug:
747 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700748 yield from self.sock_connect(sock, address)
749 except OSError as exc:
750 if sock is not None:
751 sock.close()
752 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200753 except:
754 if sock is not None:
755 sock.close()
756 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700757 else:
758 break
759 else:
760 if len(exceptions) == 1:
761 raise exceptions[0]
762 else:
763 # If they all have the same str(), raise one.
764 model = str(exceptions[0])
765 if all(str(exc) == model for exc in exceptions):
766 raise exceptions[0]
767 # Raise a combined exception so the user can see all
768 # the various error messages.
769 raise OSError('Multiple exceptions: {}'.format(
770 ', '.join(str(exc) for exc in exceptions)))
771
772 elif sock is None:
773 raise ValueError(
774 'host and port was not specified and no sock specified')
775
Yury Selivanovb057c522014-02-18 12:15:06 -0500776 transport, protocol = yield from self._create_connection_transport(
777 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200778 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200779 # Get the socket from the transport because SSL transport closes
780 # the old socket and creates a new SSL socket
781 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200782 logger.debug("%r connected to %s:%r: (%r, %r)",
783 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500784 return transport, protocol
785
Victor Stinnerf951d282014-06-29 00:46:45 +0200786 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500787 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400788 server_hostname, server_side=False):
789
790 sock.setblocking(False)
791
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700792 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400793 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700794 if ssl:
795 sslcontext = None if isinstance(ssl, bool) else ssl
796 transport = self._make_ssl_transport(
797 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400798 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700799 else:
800 transport = self._make_socket_transport(sock, protocol, waiter)
801
Victor Stinner29ad0112015-01-15 00:04:21 +0100802 try:
803 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100804 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100805 transport.close()
806 raise
807
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700808 return transport, protocol
809
Victor Stinnerf951d282014-06-29 00:46:45 +0200810 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700811 def create_datagram_endpoint(self, protocol_factory,
812 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700813 family=0, proto=0, flags=0,
814 reuse_address=None, reuse_port=None,
815 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700816 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700817 if sock is not None:
818 if (local_addr or remote_addr or
819 family or proto or flags or
820 reuse_address or reuse_port or allow_broadcast):
821 # show the problematic kwargs in exception msg
822 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
823 family=family, proto=proto, flags=flags,
824 reuse_address=reuse_address, reuse_port=reuse_port,
825 allow_broadcast=allow_broadcast)
826 problems = ', '.join(
827 '{}={}'.format(k, v) for k, v in opts.items() if v)
828 raise ValueError(
829 'socket modifier keyword arguments can not be used '
830 'when sock is specified. ({})'.format(problems))
831 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700832 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700833 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700834 if not (local_addr or remote_addr):
835 if family == 0:
836 raise ValueError('unexpected address family')
837 addr_pairs_info = (((family, proto), (None, None)),)
838 else:
839 # join address by (family, protocol)
840 addr_infos = collections.OrderedDict()
841 for idx, addr in ((0, local_addr), (1, remote_addr)):
842 if addr is not None:
843 assert isinstance(addr, tuple) and len(addr) == 2, (
844 '2-tuple is expected')
845
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400846 infos = yield from _ensure_resolved(
847 addr, family=family, type=socket.SOCK_DGRAM,
848 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700849 if not infos:
850 raise OSError('getaddrinfo() returned empty list')
851
852 for fam, _, pro, _, address in infos:
853 key = (fam, pro)
854 if key not in addr_infos:
855 addr_infos[key] = [None, None]
856 addr_infos[key][idx] = address
857
858 # each addr has to have info for each (family, proto) pair
859 addr_pairs_info = [
860 (key, addr_pair) for key, addr_pair in addr_infos.items()
861 if not ((local_addr and addr_pair[0] is None) or
862 (remote_addr and addr_pair[1] is None))]
863
864 if not addr_pairs_info:
865 raise ValueError('can not get address information')
866
867 exceptions = []
868
869 if reuse_address is None:
870 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
871
872 for ((family, proto),
873 (local_address, remote_address)) in addr_pairs_info:
874 sock = None
875 r_addr = None
876 try:
877 sock = socket.socket(
878 family=family, type=socket.SOCK_DGRAM, proto=proto)
879 if reuse_address:
880 sock.setsockopt(
881 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
882 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400883 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700884 if allow_broadcast:
885 sock.setsockopt(
886 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
887 sock.setblocking(False)
888
889 if local_addr:
890 sock.bind(local_address)
891 if remote_addr:
892 yield from self.sock_connect(sock, remote_address)
893 r_addr = remote_address
894 except OSError as exc:
895 if sock is not None:
896 sock.close()
897 exceptions.append(exc)
898 except:
899 if sock is not None:
900 sock.close()
901 raise
902 else:
903 break
904 else:
905 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700906
907 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400908 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700909 transport = self._make_datagram_transport(
910 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200911 if self._debug:
912 if local_addr:
913 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
914 "created: (%r, %r)",
915 local_addr, remote_addr, transport, protocol)
916 else:
917 logger.debug("Datagram endpoint remote_addr=%r created: "
918 "(%r, %r)",
919 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100920
921 try:
922 yield from waiter
923 except:
924 transport.close()
925 raise
926
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700927 return transport, protocol
928
Victor Stinnerf951d282014-06-29 00:46:45 +0200929 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200930 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400931 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200932 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400933 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200934 if not infos:
935 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
936 return infos
937
938 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700939 def create_server(self, protocol_factory, host=None, port=None,
940 *,
941 family=socket.AF_UNSPEC,
942 flags=socket.AI_PASSIVE,
943 sock=None,
944 backlog=100,
945 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700946 reuse_address=None,
947 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200948 """Create a TCP server.
949
950 The host parameter can be a string, in that case the TCP server is bound
951 to host and port.
952
953 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500954 the TCP server is bound to all hosts of the sequence. If a host
955 appears multiple times (possibly indirectly e.g. when hostnames
956 resolve to the same IP address), the server is only bound once to that
957 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200958
Victor Stinneracdb7822014-07-14 18:33:40 +0200959 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200960
961 This method is a coroutine.
962 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700963 if isinstance(ssl, bool):
964 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700965 if host is not None or port is not None:
966 if sock is not None:
967 raise ValueError(
968 'host/port and sock can not be specified at the same time')
969
970 AF_INET6 = getattr(socket, 'AF_INET6', 0)
971 if reuse_address is None:
972 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
973 sockets = []
974 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200975 hosts = [None]
976 elif (isinstance(host, str) or
977 not isinstance(host, collections.Iterable)):
978 hosts = [host]
979 else:
980 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700981
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200982 fs = [self._create_server_getaddrinfo(host, port, family=family,
983 flags=flags)
984 for host in hosts]
985 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500986 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700987
988 completed = False
989 try:
990 for res in infos:
991 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700992 try:
993 sock = socket.socket(af, socktype, proto)
994 except socket.error:
995 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200996 if self._debug:
997 logger.warning('create_server() failed to create '
998 'socket.socket(%r, %r, %r)',
999 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001000 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001001 sockets.append(sock)
1002 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001003 sock.setsockopt(
1004 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1005 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001006 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001007 # Disable IPv4/IPv6 dual stack support (enabled by
1008 # default on Linux) which makes a single socket
1009 # listen on both address families.
1010 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1011 sock.setsockopt(socket.IPPROTO_IPV6,
1012 socket.IPV6_V6ONLY,
1013 True)
1014 try:
1015 sock.bind(sa)
1016 except OSError as err:
1017 raise OSError(err.errno, 'error while attempting '
1018 'to bind on address %r: %s'
1019 % (sa, err.strerror.lower()))
1020 completed = True
1021 finally:
1022 if not completed:
1023 for sock in sockets:
1024 sock.close()
1025 else:
1026 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001027 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001028 sockets = [sock]
1029
1030 server = Server(self, sockets)
1031 for sock in sockets:
1032 sock.listen(backlog)
1033 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001034 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001035 if self._debug:
1036 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001037 return server
1038
Victor Stinnerf951d282014-06-29 00:46:45 +02001039 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001040 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1041 """Handle an accepted connection.
1042
1043 This is used by servers that accept connections outside of
1044 asyncio but that use asyncio to handle connections.
1045
1046 This method is a coroutine. When completed, the coroutine
1047 returns a (transport, protocol) pair.
1048 """
1049 transport, protocol = yield from self._create_connection_transport(
1050 sock, protocol_factory, ssl, '', server_side=True)
1051 if self._debug:
1052 # Get the socket from the transport because SSL transport closes
1053 # the old socket and creates a new SSL socket
1054 sock = transport.get_extra_info('socket')
1055 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1056 return transport, protocol
1057
1058 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001059 def connect_read_pipe(self, protocol_factory, pipe):
1060 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001061 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001062 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001063
1064 try:
1065 yield from waiter
1066 except:
1067 transport.close()
1068 raise
1069
Victor Stinneracdb7822014-07-14 18:33:40 +02001070 if self._debug:
1071 logger.debug('Read pipe %r connected: (%r, %r)',
1072 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001073 return transport, protocol
1074
Victor Stinnerf951d282014-06-29 00:46:45 +02001075 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001076 def connect_write_pipe(self, protocol_factory, pipe):
1077 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001078 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001079 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001080
1081 try:
1082 yield from waiter
1083 except:
1084 transport.close()
1085 raise
1086
Victor Stinneracdb7822014-07-14 18:33:40 +02001087 if self._debug:
1088 logger.debug('Write pipe %r connected: (%r, %r)',
1089 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001090 return transport, protocol
1091
Victor Stinneracdb7822014-07-14 18:33:40 +02001092 def _log_subprocess(self, msg, stdin, stdout, stderr):
1093 info = [msg]
1094 if stdin is not None:
1095 info.append('stdin=%s' % _format_pipe(stdin))
1096 if stdout is not None and stderr == subprocess.STDOUT:
1097 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1098 else:
1099 if stdout is not None:
1100 info.append('stdout=%s' % _format_pipe(stdout))
1101 if stderr is not None:
1102 info.append('stderr=%s' % _format_pipe(stderr))
1103 logger.debug(' '.join(info))
1104
Victor Stinnerf951d282014-06-29 00:46:45 +02001105 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001106 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1107 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1108 universal_newlines=False, shell=True, bufsize=0,
1109 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001110 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001111 raise ValueError("cmd must be a string")
1112 if universal_newlines:
1113 raise ValueError("universal_newlines must be False")
1114 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001115 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001116 if bufsize != 0:
1117 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001118 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001119 if self._debug:
1120 # don't log parameters: they may contain sensitive information
1121 # (password) and may be too long
1122 debug_log = 'run shell command %r' % cmd
1123 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001124 transport = yield from self._make_subprocess_transport(
1125 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001126 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001127 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001128 return transport, protocol
1129
Victor Stinnerf951d282014-06-29 00:46:45 +02001130 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001131 def subprocess_exec(self, protocol_factory, program, *args,
1132 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1133 stderr=subprocess.PIPE, universal_newlines=False,
1134 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001135 if universal_newlines:
1136 raise ValueError("universal_newlines must be False")
1137 if shell:
1138 raise ValueError("shell must be False")
1139 if bufsize != 0:
1140 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001141 popen_args = (program,) + args
1142 for arg in popen_args:
1143 if not isinstance(arg, (str, bytes)):
1144 raise TypeError("program arguments must be "
1145 "a bytes or text string, not %s"
1146 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001147 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001148 if self._debug:
1149 # don't log parameters: they may contain sensitive information
1150 # (password) and may be too long
1151 debug_log = 'execute program %r' % program
1152 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001153 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001154 protocol, popen_args, False, stdin, stdout, stderr,
1155 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001156 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001157 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001158 return transport, protocol
1159
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001160 def get_exception_handler(self):
1161 """Return an exception handler, or None if the default one is in use.
1162 """
1163 return self._exception_handler
1164
Yury Selivanov569efa22014-02-18 18:02:19 -05001165 def set_exception_handler(self, handler):
1166 """Set handler as the new event loop exception handler.
1167
1168 If handler is None, the default exception handler will
1169 be set.
1170
1171 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001172 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001173 will be a reference to the active event loop, 'context'
1174 will be a dict object (see `call_exception_handler()`
1175 documentation for details about context).
1176 """
1177 if handler is not None and not callable(handler):
1178 raise TypeError('A callable object or None is expected, '
1179 'got {!r}'.format(handler))
1180 self._exception_handler = handler
1181
1182 def default_exception_handler(self, context):
1183 """Default exception handler.
1184
1185 This is called when an exception occurs and no exception
1186 handler is set, and can be called by a custom exception
1187 handler that wants to defer to the default behavior.
1188
Victor Stinneracdb7822014-07-14 18:33:40 +02001189 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001190 `call_exception_handler()`.
1191 """
1192 message = context.get('message')
1193 if not message:
1194 message = 'Unhandled exception in event loop'
1195
1196 exception = context.get('exception')
1197 if exception is not None:
1198 exc_info = (type(exception), exception, exception.__traceback__)
1199 else:
1200 exc_info = False
1201
Victor Stinnerff018e42015-01-28 00:30:40 +01001202 if ('source_traceback' not in context
1203 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001204 and self._current_handle._source_traceback):
1205 context['handle_traceback'] = self._current_handle._source_traceback
1206
Yury Selivanov569efa22014-02-18 18:02:19 -05001207 log_lines = [message]
1208 for key in sorted(context):
1209 if key in {'message', 'exception'}:
1210 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001211 value = context[key]
1212 if key == 'source_traceback':
1213 tb = ''.join(traceback.format_list(value))
1214 value = 'Object created at (most recent call last):\n'
1215 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001216 elif key == 'handle_traceback':
1217 tb = ''.join(traceback.format_list(value))
1218 value = 'Handle created at (most recent call last):\n'
1219 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001220 else:
1221 value = repr(value)
1222 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001223
1224 logger.error('\n'.join(log_lines), exc_info=exc_info)
1225
1226 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001227 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001228
Victor Stinneracdb7822014-07-14 18:33:40 +02001229 The context argument is a dict containing the following keys:
1230
Yury Selivanov569efa22014-02-18 18:02:19 -05001231 - 'message': Error message;
1232 - 'exception' (optional): Exception object;
1233 - 'future' (optional): Future instance;
1234 - 'handle' (optional): Handle instance;
1235 - 'protocol' (optional): Protocol instance;
1236 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001237 - 'socket' (optional): Socket instance;
1238 - 'asyncgen' (optional): Asynchronous generator that caused
1239 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001240
Victor Stinneracdb7822014-07-14 18:33:40 +02001241 New keys maybe introduced in the future.
1242
1243 Note: do not overload this method in an event loop subclass.
1244 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001245 `set_exception_handler()` method.
1246 """
1247 if self._exception_handler is None:
1248 try:
1249 self.default_exception_handler(context)
1250 except Exception:
1251 # Second protection layer for unexpected errors
1252 # in the default implementation, as well as for subclassed
1253 # event loops with overloaded "default_exception_handler".
1254 logger.error('Exception in default exception handler',
1255 exc_info=True)
1256 else:
1257 try:
1258 self._exception_handler(self, context)
1259 except Exception as exc:
1260 # Exception in the user set custom exception handler.
1261 try:
1262 # Let's try default handler.
1263 self.default_exception_handler({
1264 'message': 'Unhandled error in exception handler',
1265 'exception': exc,
1266 'context': context,
1267 })
1268 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001269 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001270 # overloaded.
1271 logger.error('Exception in default exception handler '
1272 'while handling an unexpected error '
1273 'in custom exception handler',
1274 exc_info=True)
1275
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001276 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001277 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001278 assert isinstance(handle, events.Handle), 'A Handle is required here'
1279 if handle._cancelled:
1280 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001281 assert not isinstance(handle, events.TimerHandle)
1282 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001283
1284 def _add_callback_signalsafe(self, handle):
1285 """Like _add_callback() but called from a signal handler."""
1286 self._add_callback(handle)
1287 self._write_to_self()
1288
Yury Selivanov592ada92014-09-25 12:07:56 -04001289 def _timer_handle_cancelled(self, handle):
1290 """Notification that a TimerHandle has been cancelled."""
1291 if handle._scheduled:
1292 self._timer_cancelled_count += 1
1293
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001294 def _run_once(self):
1295 """Run one full iteration of the event loop.
1296
1297 This calls all currently ready callbacks, polls for I/O,
1298 schedules the resulting callbacks, and finally schedules
1299 'call_later' callbacks.
1300 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001301
Yury Selivanov592ada92014-09-25 12:07:56 -04001302 sched_count = len(self._scheduled)
1303 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1304 self._timer_cancelled_count / sched_count >
1305 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001306 # Remove delayed calls that were cancelled if their number
1307 # is too high
1308 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001309 for handle in self._scheduled:
1310 if handle._cancelled:
1311 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001312 else:
1313 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001314
Victor Stinner68da8fc2014-09-30 18:08:36 +02001315 heapq.heapify(new_scheduled)
1316 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001317 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001318 else:
1319 # Remove delayed calls that were cancelled from head of queue.
1320 while self._scheduled and self._scheduled[0]._cancelled:
1321 self._timer_cancelled_count -= 1
1322 handle = heapq.heappop(self._scheduled)
1323 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001324
1325 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001326 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001327 timeout = 0
1328 elif self._scheduled:
1329 # Compute the desired timeout.
1330 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001331 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001332
Victor Stinner770e48d2014-07-11 11:58:33 +02001333 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001334 t0 = self.time()
1335 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001336 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001337 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001338 level = logging.INFO
1339 else:
1340 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001341 nevent = len(event_list)
1342 if timeout is None:
1343 logger.log(level, 'poll took %.3f ms: %s events',
1344 dt * 1e3, nevent)
1345 elif nevent:
1346 logger.log(level,
1347 'poll %.3f ms took %.3f ms: %s events',
1348 timeout * 1e3, dt * 1e3, nevent)
1349 elif dt >= 1.0:
1350 logger.log(level,
1351 'poll %.3f ms took %.3f ms: timeout',
1352 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001353 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001354 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001355 self._process_events(event_list)
1356
1357 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001358 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001359 while self._scheduled:
1360 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001361 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001362 break
1363 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001364 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001365 self._ready.append(handle)
1366
1367 # This is the only place where callbacks are actually *called*.
1368 # All other places just add them to ready.
1369 # Note: We run all currently scheduled callbacks, but not any
1370 # callbacks scheduled by callbacks run this time around --
1371 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001372 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001373 ntodo = len(self._ready)
1374 for i in range(ntodo):
1375 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001376 if handle._cancelled:
1377 continue
1378 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001379 try:
1380 self._current_handle = handle
1381 t0 = self.time()
1382 handle._run()
1383 dt = self.time() - t0
1384 if dt >= self.slow_callback_duration:
1385 logger.warning('Executing %s took %.3f seconds',
1386 _format_handle(handle), dt)
1387 finally:
1388 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001389 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001390 handle._run()
1391 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001392
Yury Selivanove8944cb2015-05-12 11:43:04 -04001393 def _set_coroutine_wrapper(self, enabled):
1394 try:
1395 set_wrapper = sys.set_coroutine_wrapper
1396 get_wrapper = sys.get_coroutine_wrapper
1397 except AttributeError:
1398 return
1399
1400 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001401 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001402 return
1403
1404 wrapper = coroutines.debug_wrapper
1405 current_wrapper = get_wrapper()
1406
1407 if enabled:
1408 if current_wrapper not in (None, wrapper):
1409 warnings.warn(
1410 "loop.set_debug(True): cannot set debug coroutine "
1411 "wrapper; another wrapper is already set %r" %
1412 current_wrapper, RuntimeWarning)
1413 else:
1414 set_wrapper(wrapper)
1415 self._coroutine_wrapper_set = True
1416 else:
1417 if current_wrapper not in (None, wrapper):
1418 warnings.warn(
1419 "loop.set_debug(False): cannot unset debug coroutine "
1420 "wrapper; another wrapper was set %r" %
1421 current_wrapper, RuntimeWarning)
1422 else:
1423 set_wrapper(None)
1424 self._coroutine_wrapper_set = False
1425
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001426 def get_debug(self):
1427 return self._debug
1428
1429 def set_debug(self, enabled):
1430 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001431
Yury Selivanove8944cb2015-05-12 11:43:04 -04001432 if self.is_running():
1433 self._set_coroutine_wrapper(enabled)