blob: 4eed46856ae44ba0f142b488cd35ce3641e9044d [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
Yury Selivanova0c1ba62016-10-28 12:52:37 -040060 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020061 # 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 Selivanova1a8b7d2016-11-09 15:47:00 -050087def _is_stream_socket(sock):
88 # Linux's socket.type is a bitmask that can include extra info
89 # about socket, therefore we can't do simple
90 # `sock_type == socket.SOCK_STREAM`.
91 return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM
92
93
94def _is_dgram_socket(sock):
95 # Linux's socket.type is a bitmask that can include extra info
96 # about socket, therefore we can't do simple
97 # `sock_type == socket.SOCK_DGRAM`.
98 return (sock.type & socket.SOCK_DGRAM) == socket.SOCK_DGRAM
99
100
101def _is_ip_socket(sock):
102 if sock.family == socket.AF_INET:
103 return True
104 if hasattr(socket, 'AF_INET6') and sock.family == socket.AF_INET6:
105 return True
106 return False
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107
108
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500109def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400110 # Try to skip getaddrinfo if "host" is already an IP. Users might have
111 # handled name resolution in their own code and pass in resolved IPs.
112 if not hasattr(socket, 'inet_pton'):
113 return
114
115 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
116 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500117 return None
118
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500119 if type == socket.SOCK_STREAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500120 # Linux only:
121 # getaddrinfo() can raise when socket.type is a bit mask.
122 # So if socket.type is a bit mask of SOCK_STREAM, and say
123 # SOCK_NONBLOCK, we simply return None, which will trigger
124 # a call to getaddrinfo() letting it process this request.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500125 proto = socket.IPPROTO_TCP
126 elif type == socket.SOCK_DGRAM:
127 proto = socket.IPPROTO_UDP
128 else:
129 return None
130
Yury Selivanova7146162016-06-02 16:51:07 -0400131 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400132 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700133 elif isinstance(port, bytes) and port == b'':
134 port = 0
135 elif isinstance(port, str) and port == '':
136 port = 0
137 else:
138 # If port's a service name like "http", don't skip getaddrinfo.
139 try:
140 port = int(port)
141 except (TypeError, ValueError):
142 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400143
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400144 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500145 afs = [socket.AF_INET]
146 if hasattr(socket, 'AF_INET6'):
147 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400148 else:
149 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500150
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400151 if isinstance(host, bytes):
152 host = host.decode('idna')
153 if '%' in host:
154 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
155 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500156 return None
157
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400158 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500159 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400160 socket.inet_pton(af, host)
161 # The host has already been resolved.
162 return af, type, proto, '', (host, port)
163 except OSError:
164 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500165
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400166 # "host" is not an IP address.
167 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500168
169
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400170def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
171 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500172 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400173 info = _ipaddr_info(host, port, family, type, proto)
174 if info is not None:
175 # "host" is already a resolved IP.
176 fut = loop.create_future()
177 fut.set_result([info])
178 return fut
179 else:
180 return loop.getaddrinfo(host, port, family=family, type=type,
181 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100182
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700183
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100184def _run_until_complete_cb(fut):
185 exc = fut._exception
186 if (isinstance(exc, BaseException)
187 and not isinstance(exc, Exception)):
188 # Issue #22429: run_forever() already finished, no need to
189 # stop it.
190 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800191 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100192
193
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194class Server(events.AbstractServer):
195
196 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200199 self._active_count = 0
200 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700201
Victor Stinnere912e652014-07-12 03:11:53 +0200202 def __repr__(self):
203 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
204
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200205 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700206 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200207 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200209 def _detach(self):
210 assert self._active_count > 0
211 self._active_count -= 1
212 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 self._wakeup()
214
215 def close(self):
216 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 if sockets is None:
218 return
219 self.sockets = None
220 for sock in sockets:
221 self._loop._stop_serving(sock)
222 if self._active_count == 0:
223 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700224
225 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200226 waiters = self._waiters
227 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700228 for waiter in waiters:
229 if not waiter.done():
230 waiter.set_result(waiter)
231
Victor Stinnerf951d282014-06-29 00:46:45 +0200232 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700233 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200234 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700235 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400236 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200237 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700238 yield from waiter
239
240
241class BaseEventLoop(events.AbstractEventLoop):
242
243 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400244 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200245 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800246 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700247 self._ready = collections.deque()
248 self._scheduled = []
249 self._default_executor = None
250 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100251 # Identifier of the thread running the event loop, or None if the
252 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100253 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100254 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500255 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400256 self.set_debug((not sys.flags.ignore_environment
257 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200258 # In debug mode, if the execution of a callback or a step of a task
259 # exceed this duration in seconds, the slow callback/task is logged.
260 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100261 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400262 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400263 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264
Yury Selivanov0a91d482016-09-15 13:24:03 -0400265 if hasattr(sys, 'get_asyncgen_hooks'):
266 # Python >= 3.6
267 # A weak set of all asynchronous generators that are
268 # being iterated by the loop.
269 self._asyncgens = weakref.WeakSet()
270 else:
271 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700272
273 # Set to True when `loop.shutdown_asyncgens` is called.
274 self._asyncgens_shutdown_called = False
275
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200276 def __repr__(self):
277 return ('<%s running=%s closed=%s debug=%s>'
278 % (self.__class__.__name__, self.is_running(),
279 self.is_closed(), self.get_debug()))
280
Yury Selivanov7661db62016-05-16 15:38:39 -0400281 def create_future(self):
282 """Create a Future object attached to the loop."""
283 return futures.Future(loop=self)
284
Victor Stinner896a25a2014-07-08 11:29:25 +0200285 def create_task(self, coro):
286 """Schedule a coroutine object.
287
Victor Stinneracdb7822014-07-14 18:33:40 +0200288 Return a task object.
289 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100290 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400291 if self._task_factory is None:
292 task = tasks.Task(coro, loop=self)
293 if task._source_traceback:
294 del task._source_traceback[-1]
295 else:
296 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200297 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200298
Yury Selivanov740169c2015-05-11 14:23:38 -0400299 def set_task_factory(self, factory):
300 """Set a task factory that will be used by loop.create_task().
301
302 If factory is None the default task factory will be set.
303
304 If factory is a callable, it should have a signature matching
305 '(loop, coro)', where 'loop' will be a reference to the active
306 event loop, 'coro' will be a coroutine object. The callable
307 must return a Future.
308 """
309 if factory is not None and not callable(factory):
310 raise TypeError('task factory must be a callable or None')
311 self._task_factory = factory
312
313 def get_task_factory(self):
314 """Return a task factory, or None if the default one is in use."""
315 return self._task_factory
316
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700317 def _make_socket_transport(self, sock, protocol, waiter=None, *,
318 extra=None, server=None):
319 """Create socket transport."""
320 raise NotImplementedError
321
Victor Stinner15cc6782015-01-09 00:09:10 +0100322 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
323 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700324 extra=None, server=None):
325 """Create SSL transport."""
326 raise NotImplementedError
327
328 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200329 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700330 """Create datagram transport."""
331 raise NotImplementedError
332
333 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
334 extra=None):
335 """Create read pipe transport."""
336 raise NotImplementedError
337
338 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
339 extra=None):
340 """Create write pipe transport."""
341 raise NotImplementedError
342
Victor Stinnerf951d282014-06-29 00:46:45 +0200343 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344 def _make_subprocess_transport(self, protocol, args, shell,
345 stdin, stdout, stderr, bufsize,
346 extra=None, **kwargs):
347 """Create subprocess transport."""
348 raise NotImplementedError
349
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700350 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200351 """Write a byte to self-pipe, to wake up the event loop.
352
353 This may be called from a different thread.
354
355 The subclass is responsible for implementing the self-pipe.
356 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700357 raise NotImplementedError
358
359 def _process_events(self, event_list):
360 """Process selector events."""
361 raise NotImplementedError
362
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200363 def _check_closed(self):
364 if self._closed:
365 raise RuntimeError('Event loop is closed')
366
Yury Selivanoveb636452016-09-08 22:01:51 -0700367 def _asyncgen_finalizer_hook(self, agen):
368 self._asyncgens.discard(agen)
369 if not self.is_closed():
370 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400371 # Wake up the loop if the finalizer was called from
372 # a different thread.
373 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700374
375 def _asyncgen_firstiter_hook(self, agen):
376 if self._asyncgens_shutdown_called:
377 warnings.warn(
378 "asynchronous generator {!r} was scheduled after "
379 "loop.shutdown_asyncgens() call".format(agen),
380 ResourceWarning, source=self)
381
382 self._asyncgens.add(agen)
383
384 @coroutine
385 def shutdown_asyncgens(self):
386 """Shutdown all active asynchronous generators."""
387 self._asyncgens_shutdown_called = True
388
Yury Selivanov0a91d482016-09-15 13:24:03 -0400389 if self._asyncgens is None or not len(self._asyncgens):
390 # If Python version is <3.6 or we don't have any asynchronous
391 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700392 return
393
394 closing_agens = list(self._asyncgens)
395 self._asyncgens.clear()
396
397 shutdown_coro = tasks.gather(
398 *[ag.aclose() for ag in closing_agens],
399 return_exceptions=True,
400 loop=self)
401
402 results = yield from shutdown_coro
403 for result, agen in zip(results, closing_agens):
404 if isinstance(result, Exception):
405 self.call_exception_handler({
406 'message': 'an error occurred during closing of '
407 'asynchronous generator {!r}'.format(agen),
408 'exception': result,
409 'asyncgen': agen
410 })
411
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700412 def run_forever(self):
413 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200414 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100415 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400416 raise RuntimeError('This event loop is already running')
417 if events._get_running_loop() is not None:
418 raise RuntimeError(
419 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400420 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100421 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400422 if self._asyncgens is not None:
423 old_agen_hooks = sys.get_asyncgen_hooks()
424 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
425 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700426 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400427 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700428 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800429 self._run_once()
430 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 break
432 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800433 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100434 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400435 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400436 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400437 if self._asyncgens is not None:
438 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700439
440 def run_until_complete(self, future):
441 """Run until the Future is done.
442
443 If the argument is a coroutine, it is wrapped in a Task.
444
Victor Stinneracdb7822014-07-14 18:33:40 +0200445 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446 with the same coroutine twice -- it would wrap it in two
447 different Tasks and that can't be good.
448
449 Return the Future's result, or raise its exception.
450 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200451 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200452
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700453 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400454 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200455 if new_task:
456 # An exception is raised if the future didn't complete, so there
457 # is no need to log the "destroy pending task" message
458 future._log_destroy_pending = False
459
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100460 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200461 try:
462 self.run_forever()
463 except:
464 if new_task and future.done() and not future.cancelled():
465 # The coroutine raised a BaseException. Consume the exception
466 # to not log a warning, the caller doesn't have access to the
467 # local task.
468 future.exception()
469 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100470 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700471 if not future.done():
472 raise RuntimeError('Event loop stopped before Future completed.')
473
474 return future.result()
475
476 def stop(self):
477 """Stop running the event loop.
478
Guido van Rossum41f69f42015-11-19 13:28:47 -0800479 Every callback already scheduled will still run. This simply informs
480 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700481 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800482 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700483
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200484 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700485 """Close the event loop.
486
487 This clears the queues and shuts down the executor,
488 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200489
490 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700491 """
Victor Stinner956de692014-12-26 21:07:52 +0100492 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200493 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200494 if self._closed:
495 return
Victor Stinnere912e652014-07-12 03:11:53 +0200496 if self._debug:
497 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400498 self._closed = True
499 self._ready.clear()
500 self._scheduled.clear()
501 executor = self._default_executor
502 if executor is not None:
503 self._default_executor = None
504 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200505
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200506 def is_closed(self):
507 """Returns True if the event loop was closed."""
508 return self._closed
509
Victor Stinner978a9af2015-01-29 17:50:58 +0100510 # On Python 3.3 and older, objects with a destructor part of a reference
511 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
512 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400513 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100514 def __del__(self):
515 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100516 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
517 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100518 if not self.is_running():
519 self.close()
520
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700521 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200522 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100523 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200526 """Return the time according to the event loop's clock.
527
528 This is a float expressed in seconds since an epoch, but the
529 epoch, precision, accuracy and drift are unspecified and may
530 differ per event loop.
531 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700532 return time.monotonic()
533
534 def call_later(self, delay, callback, *args):
535 """Arrange for a callback to be called at a given time.
536
537 Return a Handle: an opaque object with a cancel() method that
538 can be used to cancel the call.
539
540 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200541 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700542
543 Each callback will be called exactly once. If two callbacks
544 are scheduled for exactly the same time, it undefined which
545 will be called first.
546
547 Any positional arguments after the callback will be passed to
548 the callback when it is called.
549 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200550 timer = self.call_at(self.time() + delay, callback, *args)
551 if timer._source_traceback:
552 del timer._source_traceback[-1]
553 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554
555 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200556 """Like call_later(), but uses an absolute time.
557
558 Absolute time corresponds to the event loop's time() method.
559 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100560 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100561 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100562 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700563 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500564 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200565 if timer._source_traceback:
566 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700567 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400568 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700569 return timer
570
571 def call_soon(self, callback, *args):
572 """Arrange for a callback to be called as soon as possible.
573
Victor Stinneracdb7822014-07-14 18:33:40 +0200574 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700575 order in which they are registered. Each callback will be
576 called exactly once.
577
578 Any positional arguments after the callback will be passed to
579 the callback when it is called.
580 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700581 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100582 if self._debug:
583 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700584 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100585 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200586 if handle._source_traceback:
587 del handle._source_traceback[-1]
588 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100589
Yury Selivanov491a9122016-11-03 15:09:24 -0700590 def _check_callback(self, callback, method):
591 if (coroutines.iscoroutine(callback) or
592 coroutines.iscoroutinefunction(callback)):
593 raise TypeError(
594 "coroutines cannot be used with {}()".format(method))
595 if not callable(callback):
596 raise TypeError(
597 'a callable object was expected by {}(), got {!r}'.format(
598 method, callback))
599
600
Victor Stinner956de692014-12-26 21:07:52 +0100601 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500602 handle = events.Handle(callback, args, self)
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._ready.append(handle)
606 return handle
607
Victor Stinner956de692014-12-26 21:07:52 +0100608 def _check_thread(self):
609 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100610
Victor Stinneracdb7822014-07-14 18:33:40 +0200611 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100612 likely behave incorrectly when the assumption is violated.
613
Victor Stinneracdb7822014-07-14 18:33:40 +0200614 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100615 responsible for checking this condition for performance reasons.
616 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100617 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200618 return
Victor Stinner956de692014-12-26 21:07:52 +0100619 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100620 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100621 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200622 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100623 "than the current one")
624
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200626 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700627 self._check_closed()
628 if self._debug:
629 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100630 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200631 if handle._source_traceback:
632 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700633 self._write_to_self()
634 return handle
635
Yury Selivanov740169c2015-05-11 14:23:38 -0400636 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100637 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700638 if self._debug:
639 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700640 if executor is None:
641 executor = self._default_executor
642 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400643 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700644 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400645 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646
647 def set_default_executor(self, executor):
648 self._default_executor = executor
649
Victor Stinnere912e652014-07-12 03:11:53 +0200650 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
651 msg = ["%s:%r" % (host, port)]
652 if family:
653 msg.append('family=%r' % family)
654 if type:
655 msg.append('type=%r' % type)
656 if proto:
657 msg.append('proto=%r' % proto)
658 if flags:
659 msg.append('flags=%r' % flags)
660 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200661 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200662
663 t0 = self.time()
664 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
665 dt = self.time() - t0
666
Victor Stinneracdb7822014-07-14 18:33:40 +0200667 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200668 % (msg, dt * 1e3, addrinfo))
669 if dt >= self.slow_callback_duration:
670 logger.info(msg)
671 else:
672 logger.debug(msg)
673 return addrinfo
674
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700675 def getaddrinfo(self, host, port, *,
676 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400677 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200678 return self.run_in_executor(None, self._getaddrinfo_debug,
679 host, port, family, type, proto, flags)
680 else:
681 return self.run_in_executor(None, socket.getaddrinfo,
682 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700683
684 def getnameinfo(self, sockaddr, flags=0):
685 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
686
Victor Stinnerf951d282014-06-29 00:46:45 +0200687 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700688 def create_connection(self, protocol_factory, host=None, port=None, *,
689 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700690 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200691 """Connect to a TCP server.
692
693 Create a streaming transport connection to a given Internet host and
694 port: socket family AF_INET or socket.AF_INET6 depending on host (or
695 family if specified), socket type SOCK_STREAM. protocol_factory must be
696 a callable returning a protocol instance.
697
698 This method is a coroutine which will try to establish the connection
699 in the background. When successful, the coroutine returns a
700 (transport, protocol) pair.
701 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700702 if server_hostname is not None and not ssl:
703 raise ValueError('server_hostname is only meaningful with ssl')
704
705 if server_hostname is None and ssl:
706 # Use host as default for server_hostname. It is an error
707 # if host is empty or not set, e.g. when an
708 # already-connected socket was passed or when only a port
709 # is given. To avoid this error, you can pass
710 # server_hostname='' -- this will bypass the hostname
711 # check. (This also means that if host is a numeric
712 # IP/IPv6 address, we will attempt to verify that exact
713 # address; this will probably fail, but it is possible to
714 # create a certificate for a specific IP address, so we
715 # don't judge it here.)
716 if not host:
717 raise ValueError('You must set server_hostname '
718 'when using ssl without a host')
719 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700720
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700721 if host is not None or port is not None:
722 if sock is not None:
723 raise ValueError(
724 'host/port and sock can not be specified at the same time')
725
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400726 f1 = _ensure_resolved((host, port), family=family,
727 type=socket.SOCK_STREAM, proto=proto,
728 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700729 fs = [f1]
730 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400731 f2 = _ensure_resolved(local_addr, family=family,
732 type=socket.SOCK_STREAM, proto=proto,
733 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 fs.append(f2)
735 else:
736 f2 = None
737
738 yield from tasks.wait(fs, loop=self)
739
740 infos = f1.result()
741 if not infos:
742 raise OSError('getaddrinfo() returned empty list')
743 if f2 is not None:
744 laddr_infos = f2.result()
745 if not laddr_infos:
746 raise OSError('getaddrinfo() returned empty list')
747
748 exceptions = []
749 for family, type, proto, cname, address in infos:
750 try:
751 sock = socket.socket(family=family, type=type, proto=proto)
752 sock.setblocking(False)
753 if f2 is not None:
754 for _, _, _, _, laddr in laddr_infos:
755 try:
756 sock.bind(laddr)
757 break
758 except OSError as exc:
759 exc = OSError(
760 exc.errno, 'error while '
761 'attempting to bind on address '
762 '{!r}: {}'.format(
763 laddr, exc.strerror.lower()))
764 exceptions.append(exc)
765 else:
766 sock.close()
767 sock = None
768 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200769 if self._debug:
770 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700771 yield from self.sock_connect(sock, address)
772 except OSError as exc:
773 if sock is not None:
774 sock.close()
775 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200776 except:
777 if sock is not None:
778 sock.close()
779 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700780 else:
781 break
782 else:
783 if len(exceptions) == 1:
784 raise exceptions[0]
785 else:
786 # If they all have the same str(), raise one.
787 model = str(exceptions[0])
788 if all(str(exc) == model for exc in exceptions):
789 raise exceptions[0]
790 # Raise a combined exception so the user can see all
791 # the various error messages.
792 raise OSError('Multiple exceptions: {}'.format(
793 ', '.join(str(exc) for exc in exceptions)))
794
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500795 else:
796 if sock is None:
797 raise ValueError(
798 'host and port was not specified and no sock specified')
799 if not _is_stream_socket(sock) or not _is_ip_socket(sock):
800 raise ValueError(
801 'A TCP Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700802
Yury Selivanovb057c522014-02-18 12:15:06 -0500803 transport, protocol = yield from self._create_connection_transport(
804 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200805 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200806 # Get the socket from the transport because SSL transport closes
807 # the old socket and creates a new SSL socket
808 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200809 logger.debug("%r connected to %s:%r: (%r, %r)",
810 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500811 return transport, protocol
812
Victor Stinnerf951d282014-06-29 00:46:45 +0200813 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500814 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400815 server_hostname, server_side=False):
816
817 sock.setblocking(False)
818
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700819 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400820 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700821 if ssl:
822 sslcontext = None if isinstance(ssl, bool) else ssl
823 transport = self._make_ssl_transport(
824 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400825 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700826 else:
827 transport = self._make_socket_transport(sock, protocol, waiter)
828
Victor Stinner29ad0112015-01-15 00:04:21 +0100829 try:
830 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100831 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100832 transport.close()
833 raise
834
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700835 return transport, protocol
836
Victor Stinnerf951d282014-06-29 00:46:45 +0200837 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700838 def create_datagram_endpoint(self, protocol_factory,
839 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700840 family=0, proto=0, flags=0,
841 reuse_address=None, reuse_port=None,
842 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700843 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700844 if sock is not None:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500845 if not _is_dgram_socket(sock):
846 raise ValueError(
847 'A UDP Socket was expected, got {!r}'.format(sock))
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700848 if (local_addr or remote_addr or
849 family or proto or flags or
850 reuse_address or reuse_port or allow_broadcast):
851 # show the problematic kwargs in exception msg
852 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
853 family=family, proto=proto, flags=flags,
854 reuse_address=reuse_address, reuse_port=reuse_port,
855 allow_broadcast=allow_broadcast)
856 problems = ', '.join(
857 '{}={}'.format(k, v) for k, v in opts.items() if v)
858 raise ValueError(
859 'socket modifier keyword arguments can not be used '
860 'when sock is specified. ({})'.format(problems))
861 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700862 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700863 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700864 if not (local_addr or remote_addr):
865 if family == 0:
866 raise ValueError('unexpected address family')
867 addr_pairs_info = (((family, proto), (None, None)),)
868 else:
869 # join address by (family, protocol)
870 addr_infos = collections.OrderedDict()
871 for idx, addr in ((0, local_addr), (1, remote_addr)):
872 if addr is not None:
873 assert isinstance(addr, tuple) and len(addr) == 2, (
874 '2-tuple is expected')
875
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400876 infos = yield from _ensure_resolved(
877 addr, family=family, type=socket.SOCK_DGRAM,
878 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700879 if not infos:
880 raise OSError('getaddrinfo() returned empty list')
881
882 for fam, _, pro, _, address in infos:
883 key = (fam, pro)
884 if key not in addr_infos:
885 addr_infos[key] = [None, None]
886 addr_infos[key][idx] = address
887
888 # each addr has to have info for each (family, proto) pair
889 addr_pairs_info = [
890 (key, addr_pair) for key, addr_pair in addr_infos.items()
891 if not ((local_addr and addr_pair[0] is None) or
892 (remote_addr and addr_pair[1] is None))]
893
894 if not addr_pairs_info:
895 raise ValueError('can not get address information')
896
897 exceptions = []
898
899 if reuse_address is None:
900 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
901
902 for ((family, proto),
903 (local_address, remote_address)) in addr_pairs_info:
904 sock = None
905 r_addr = None
906 try:
907 sock = socket.socket(
908 family=family, type=socket.SOCK_DGRAM, proto=proto)
909 if reuse_address:
910 sock.setsockopt(
911 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
912 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400913 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700914 if allow_broadcast:
915 sock.setsockopt(
916 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
917 sock.setblocking(False)
918
919 if local_addr:
920 sock.bind(local_address)
921 if remote_addr:
922 yield from self.sock_connect(sock, remote_address)
923 r_addr = remote_address
924 except OSError as exc:
925 if sock is not None:
926 sock.close()
927 exceptions.append(exc)
928 except:
929 if sock is not None:
930 sock.close()
931 raise
932 else:
933 break
934 else:
935 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700936
937 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400938 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700939 transport = self._make_datagram_transport(
940 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200941 if self._debug:
942 if local_addr:
943 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
944 "created: (%r, %r)",
945 local_addr, remote_addr, transport, protocol)
946 else:
947 logger.debug("Datagram endpoint remote_addr=%r created: "
948 "(%r, %r)",
949 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100950
951 try:
952 yield from waiter
953 except:
954 transport.close()
955 raise
956
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700957 return transport, protocol
958
Victor Stinnerf951d282014-06-29 00:46:45 +0200959 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200960 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400961 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200962 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400963 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200964 if not infos:
965 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
966 return infos
967
968 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700969 def create_server(self, protocol_factory, host=None, port=None,
970 *,
971 family=socket.AF_UNSPEC,
972 flags=socket.AI_PASSIVE,
973 sock=None,
974 backlog=100,
975 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700976 reuse_address=None,
977 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200978 """Create a TCP server.
979
980 The host parameter can be a string, in that case the TCP server is bound
981 to host and port.
982
983 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500984 the TCP server is bound to all hosts of the sequence. If a host
985 appears multiple times (possibly indirectly e.g. when hostnames
986 resolve to the same IP address), the server is only bound once to that
987 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200988
Victor Stinneracdb7822014-07-14 18:33:40 +0200989 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200990
991 This method is a coroutine.
992 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700993 if isinstance(ssl, bool):
994 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700995 if host is not None or port is not None:
996 if sock is not None:
997 raise ValueError(
998 'host/port and sock can not be specified at the same time')
999
1000 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1001 if reuse_address is None:
1002 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1003 sockets = []
1004 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001005 hosts = [None]
1006 elif (isinstance(host, str) or
1007 not isinstance(host, collections.Iterable)):
1008 hosts = [host]
1009 else:
1010 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001011
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001012 fs = [self._create_server_getaddrinfo(host, port, family=family,
1013 flags=flags)
1014 for host in hosts]
1015 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001016 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001017
1018 completed = False
1019 try:
1020 for res in infos:
1021 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001022 try:
1023 sock = socket.socket(af, socktype, proto)
1024 except socket.error:
1025 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001026 if self._debug:
1027 logger.warning('create_server() failed to create '
1028 'socket.socket(%r, %r, %r)',
1029 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001030 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001031 sockets.append(sock)
1032 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001033 sock.setsockopt(
1034 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1035 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001036 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001037 # Disable IPv4/IPv6 dual stack support (enabled by
1038 # default on Linux) which makes a single socket
1039 # listen on both address families.
1040 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1041 sock.setsockopt(socket.IPPROTO_IPV6,
1042 socket.IPV6_V6ONLY,
1043 True)
1044 try:
1045 sock.bind(sa)
1046 except OSError as err:
1047 raise OSError(err.errno, 'error while attempting '
1048 'to bind on address %r: %s'
1049 % (sa, err.strerror.lower()))
1050 completed = True
1051 finally:
1052 if not completed:
1053 for sock in sockets:
1054 sock.close()
1055 else:
1056 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001057 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001058 if not _is_stream_socket(sock) or not _is_ip_socket(sock):
1059 raise ValueError(
1060 'A TCP Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001061 sockets = [sock]
1062
1063 server = Server(self, sockets)
1064 for sock in sockets:
1065 sock.listen(backlog)
1066 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001067 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001068 if self._debug:
1069 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001070 return server
1071
Victor Stinnerf951d282014-06-29 00:46:45 +02001072 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001073 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1074 """Handle an accepted connection.
1075
1076 This is used by servers that accept connections outside of
1077 asyncio but that use asyncio to handle connections.
1078
1079 This method is a coroutine. When completed, the coroutine
1080 returns a (transport, protocol) pair.
1081 """
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001082 if not _is_stream_socket(sock):
1083 raise ValueError(
1084 'A Stream Socket was expected, got {!r}'.format(sock))
1085
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001086 transport, protocol = yield from self._create_connection_transport(
1087 sock, protocol_factory, ssl, '', server_side=True)
1088 if self._debug:
1089 # Get the socket from the transport because SSL transport closes
1090 # the old socket and creates a new SSL socket
1091 sock = transport.get_extra_info('socket')
1092 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1093 return transport, protocol
1094
1095 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001096 def connect_read_pipe(self, protocol_factory, pipe):
1097 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001098 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001099 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001100
1101 try:
1102 yield from waiter
1103 except:
1104 transport.close()
1105 raise
1106
Victor Stinneracdb7822014-07-14 18:33:40 +02001107 if self._debug:
1108 logger.debug('Read pipe %r connected: (%r, %r)',
1109 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001110 return transport, protocol
1111
Victor Stinnerf951d282014-06-29 00:46:45 +02001112 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001113 def connect_write_pipe(self, protocol_factory, pipe):
1114 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001115 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001116 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001117
1118 try:
1119 yield from waiter
1120 except:
1121 transport.close()
1122 raise
1123
Victor Stinneracdb7822014-07-14 18:33:40 +02001124 if self._debug:
1125 logger.debug('Write pipe %r connected: (%r, %r)',
1126 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001127 return transport, protocol
1128
Victor Stinneracdb7822014-07-14 18:33:40 +02001129 def _log_subprocess(self, msg, stdin, stdout, stderr):
1130 info = [msg]
1131 if stdin is not None:
1132 info.append('stdin=%s' % _format_pipe(stdin))
1133 if stdout is not None and stderr == subprocess.STDOUT:
1134 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1135 else:
1136 if stdout is not None:
1137 info.append('stdout=%s' % _format_pipe(stdout))
1138 if stderr is not None:
1139 info.append('stderr=%s' % _format_pipe(stderr))
1140 logger.debug(' '.join(info))
1141
Victor Stinnerf951d282014-06-29 00:46:45 +02001142 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001143 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1144 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1145 universal_newlines=False, shell=True, bufsize=0,
1146 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001147 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001148 raise ValueError("cmd must be a string")
1149 if universal_newlines:
1150 raise ValueError("universal_newlines must be False")
1151 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001152 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001153 if bufsize != 0:
1154 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001155 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001156 if self._debug:
1157 # don't log parameters: they may contain sensitive information
1158 # (password) and may be too long
1159 debug_log = 'run shell command %r' % cmd
1160 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001161 transport = yield from self._make_subprocess_transport(
1162 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001163 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001164 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001165 return transport, protocol
1166
Victor Stinnerf951d282014-06-29 00:46:45 +02001167 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001168 def subprocess_exec(self, protocol_factory, program, *args,
1169 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1170 stderr=subprocess.PIPE, universal_newlines=False,
1171 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001172 if universal_newlines:
1173 raise ValueError("universal_newlines must be False")
1174 if shell:
1175 raise ValueError("shell must be False")
1176 if bufsize != 0:
1177 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001178 popen_args = (program,) + args
1179 for arg in popen_args:
1180 if not isinstance(arg, (str, bytes)):
1181 raise TypeError("program arguments must be "
1182 "a bytes or text string, not %s"
1183 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001184 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001185 if self._debug:
1186 # don't log parameters: they may contain sensitive information
1187 # (password) and may be too long
1188 debug_log = 'execute program %r' % program
1189 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001190 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001191 protocol, popen_args, False, stdin, stdout, stderr,
1192 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001193 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001194 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001195 return transport, protocol
1196
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001197 def get_exception_handler(self):
1198 """Return an exception handler, or None if the default one is in use.
1199 """
1200 return self._exception_handler
1201
Yury Selivanov569efa22014-02-18 18:02:19 -05001202 def set_exception_handler(self, handler):
1203 """Set handler as the new event loop exception handler.
1204
1205 If handler is None, the default exception handler will
1206 be set.
1207
1208 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001209 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001210 will be a reference to the active event loop, 'context'
1211 will be a dict object (see `call_exception_handler()`
1212 documentation for details about context).
1213 """
1214 if handler is not None and not callable(handler):
1215 raise TypeError('A callable object or None is expected, '
1216 'got {!r}'.format(handler))
1217 self._exception_handler = handler
1218
1219 def default_exception_handler(self, context):
1220 """Default exception handler.
1221
1222 This is called when an exception occurs and no exception
1223 handler is set, and can be called by a custom exception
1224 handler that wants to defer to the default behavior.
1225
Victor Stinneracdb7822014-07-14 18:33:40 +02001226 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001227 `call_exception_handler()`.
1228 """
1229 message = context.get('message')
1230 if not message:
1231 message = 'Unhandled exception in event loop'
1232
1233 exception = context.get('exception')
1234 if exception is not None:
1235 exc_info = (type(exception), exception, exception.__traceback__)
1236 else:
1237 exc_info = False
1238
Victor Stinnerff018e42015-01-28 00:30:40 +01001239 if ('source_traceback' not in context
1240 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001241 and self._current_handle._source_traceback):
1242 context['handle_traceback'] = self._current_handle._source_traceback
1243
Yury Selivanov569efa22014-02-18 18:02:19 -05001244 log_lines = [message]
1245 for key in sorted(context):
1246 if key in {'message', 'exception'}:
1247 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001248 value = context[key]
1249 if key == 'source_traceback':
1250 tb = ''.join(traceback.format_list(value))
1251 value = 'Object created at (most recent call last):\n'
1252 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001253 elif key == 'handle_traceback':
1254 tb = ''.join(traceback.format_list(value))
1255 value = 'Handle created at (most recent call last):\n'
1256 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001257 else:
1258 value = repr(value)
1259 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001260
1261 logger.error('\n'.join(log_lines), exc_info=exc_info)
1262
1263 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001264 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001265
Victor Stinneracdb7822014-07-14 18:33:40 +02001266 The context argument is a dict containing the following keys:
1267
Yury Selivanov569efa22014-02-18 18:02:19 -05001268 - 'message': Error message;
1269 - 'exception' (optional): Exception object;
1270 - 'future' (optional): Future instance;
1271 - 'handle' (optional): Handle instance;
1272 - 'protocol' (optional): Protocol instance;
1273 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001274 - 'socket' (optional): Socket instance;
1275 - 'asyncgen' (optional): Asynchronous generator that caused
1276 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001277
Victor Stinneracdb7822014-07-14 18:33:40 +02001278 New keys maybe introduced in the future.
1279
1280 Note: do not overload this method in an event loop subclass.
1281 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001282 `set_exception_handler()` method.
1283 """
1284 if self._exception_handler is None:
1285 try:
1286 self.default_exception_handler(context)
1287 except Exception:
1288 # Second protection layer for unexpected errors
1289 # in the default implementation, as well as for subclassed
1290 # event loops with overloaded "default_exception_handler".
1291 logger.error('Exception in default exception handler',
1292 exc_info=True)
1293 else:
1294 try:
1295 self._exception_handler(self, context)
1296 except Exception as exc:
1297 # Exception in the user set custom exception handler.
1298 try:
1299 # Let's try default handler.
1300 self.default_exception_handler({
1301 'message': 'Unhandled error in exception handler',
1302 'exception': exc,
1303 'context': context,
1304 })
1305 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001306 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001307 # overloaded.
1308 logger.error('Exception in default exception handler '
1309 'while handling an unexpected error '
1310 'in custom exception handler',
1311 exc_info=True)
1312
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001313 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001314 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001315 assert isinstance(handle, events.Handle), 'A Handle is required here'
1316 if handle._cancelled:
1317 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001318 assert not isinstance(handle, events.TimerHandle)
1319 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001320
1321 def _add_callback_signalsafe(self, handle):
1322 """Like _add_callback() but called from a signal handler."""
1323 self._add_callback(handle)
1324 self._write_to_self()
1325
Yury Selivanov592ada92014-09-25 12:07:56 -04001326 def _timer_handle_cancelled(self, handle):
1327 """Notification that a TimerHandle has been cancelled."""
1328 if handle._scheduled:
1329 self._timer_cancelled_count += 1
1330
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001331 def _run_once(self):
1332 """Run one full iteration of the event loop.
1333
1334 This calls all currently ready callbacks, polls for I/O,
1335 schedules the resulting callbacks, and finally schedules
1336 'call_later' callbacks.
1337 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001338
Yury Selivanov592ada92014-09-25 12:07:56 -04001339 sched_count = len(self._scheduled)
1340 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1341 self._timer_cancelled_count / sched_count >
1342 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001343 # Remove delayed calls that were cancelled if their number
1344 # is too high
1345 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001346 for handle in self._scheduled:
1347 if handle._cancelled:
1348 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001349 else:
1350 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001351
Victor Stinner68da8fc2014-09-30 18:08:36 +02001352 heapq.heapify(new_scheduled)
1353 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001354 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001355 else:
1356 # Remove delayed calls that were cancelled from head of queue.
1357 while self._scheduled and self._scheduled[0]._cancelled:
1358 self._timer_cancelled_count -= 1
1359 handle = heapq.heappop(self._scheduled)
1360 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001361
1362 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001363 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001364 timeout = 0
1365 elif self._scheduled:
1366 # Compute the desired timeout.
1367 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001368 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001369
Victor Stinner770e48d2014-07-11 11:58:33 +02001370 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001371 t0 = self.time()
1372 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001373 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001374 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001375 level = logging.INFO
1376 else:
1377 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001378 nevent = len(event_list)
1379 if timeout is None:
1380 logger.log(level, 'poll took %.3f ms: %s events',
1381 dt * 1e3, nevent)
1382 elif nevent:
1383 logger.log(level,
1384 'poll %.3f ms took %.3f ms: %s events',
1385 timeout * 1e3, dt * 1e3, nevent)
1386 elif dt >= 1.0:
1387 logger.log(level,
1388 'poll %.3f ms took %.3f ms: timeout',
1389 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001390 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001391 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001392 self._process_events(event_list)
1393
1394 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001395 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001396 while self._scheduled:
1397 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001398 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001399 break
1400 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001401 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001402 self._ready.append(handle)
1403
1404 # This is the only place where callbacks are actually *called*.
1405 # All other places just add them to ready.
1406 # Note: We run all currently scheduled callbacks, but not any
1407 # callbacks scheduled by callbacks run this time around --
1408 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001409 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001410 ntodo = len(self._ready)
1411 for i in range(ntodo):
1412 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001413 if handle._cancelled:
1414 continue
1415 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001416 try:
1417 self._current_handle = handle
1418 t0 = self.time()
1419 handle._run()
1420 dt = self.time() - t0
1421 if dt >= self.slow_callback_duration:
1422 logger.warning('Executing %s took %.3f seconds',
1423 _format_handle(handle), dt)
1424 finally:
1425 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001426 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001427 handle._run()
1428 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001429
Yury Selivanove8944cb2015-05-12 11:43:04 -04001430 def _set_coroutine_wrapper(self, enabled):
1431 try:
1432 set_wrapper = sys.set_coroutine_wrapper
1433 get_wrapper = sys.get_coroutine_wrapper
1434 except AttributeError:
1435 return
1436
1437 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001438 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001439 return
1440
1441 wrapper = coroutines.debug_wrapper
1442 current_wrapper = get_wrapper()
1443
1444 if enabled:
1445 if current_wrapper not in (None, wrapper):
1446 warnings.warn(
1447 "loop.set_debug(True): cannot set debug coroutine "
1448 "wrapper; another wrapper is already set %r" %
1449 current_wrapper, RuntimeWarning)
1450 else:
1451 set_wrapper(wrapper)
1452 self._coroutine_wrapper_set = True
1453 else:
1454 if current_wrapper not in (None, wrapper):
1455 warnings.warn(
1456 "loop.set_debug(False): cannot unset debug coroutine "
1457 "wrapper; another wrapper was set %r" %
1458 current_wrapper, RuntimeWarning)
1459 else:
1460 set_wrapper(None)
1461 self._coroutine_wrapper_set = False
1462
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001463 def get_debug(self):
1464 return self._debug
1465
1466 def set_debug(self, enabled):
1467 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001468
Yury Selivanove8944cb2015-05-12 11:43:04 -04001469 if self.is_running():
1470 self._set_coroutine_wrapper(enabled)