blob: a4967b854c5e68d9d689d0a446ba091aee0e2ba6 [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
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500101def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400102 # Try to skip getaddrinfo if "host" is already an IP. Users might have
103 # handled name resolution in their own code and pass in resolved IPs.
104 if not hasattr(socket, 'inet_pton'):
105 return
106
107 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
108 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500109 return None
110
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500111 if type == socket.SOCK_STREAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500112 # Linux only:
113 # getaddrinfo() can raise when socket.type is a bit mask.
114 # So if socket.type is a bit mask of SOCK_STREAM, and say
115 # SOCK_NONBLOCK, we simply return None, which will trigger
116 # a call to getaddrinfo() letting it process this request.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500117 proto = socket.IPPROTO_TCP
118 elif type == socket.SOCK_DGRAM:
119 proto = socket.IPPROTO_UDP
120 else:
121 return None
122
Yury Selivanova7146162016-06-02 16:51:07 -0400123 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400124 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700125 elif isinstance(port, bytes) and port == b'':
126 port = 0
127 elif isinstance(port, str) and port == '':
128 port = 0
129 else:
130 # If port's a service name like "http", don't skip getaddrinfo.
131 try:
132 port = int(port)
133 except (TypeError, ValueError):
134 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400135
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400136 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500137 afs = [socket.AF_INET]
138 if hasattr(socket, 'AF_INET6'):
139 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 else:
141 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500142
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400143 if isinstance(host, bytes):
144 host = host.decode('idna')
145 if '%' in host:
146 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
147 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148 return None
149
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500151 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400152 socket.inet_pton(af, host)
153 # The host has already been resolved.
154 return af, type, proto, '', (host, port)
155 except OSError:
156 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500157
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400158 # "host" is not an IP address.
159 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500160
161
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400162def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
163 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500164 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400165 info = _ipaddr_info(host, port, family, type, proto)
166 if info is not None:
167 # "host" is already a resolved IP.
168 fut = loop.create_future()
169 fut.set_result([info])
170 return fut
171 else:
172 return loop.getaddrinfo(host, port, family=family, type=type,
173 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100174
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700175
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100176def _run_until_complete_cb(fut):
177 exc = fut._exception
178 if (isinstance(exc, BaseException)
179 and not isinstance(exc, Exception)):
180 # Issue #22429: run_forever() already finished, no need to
181 # stop it.
182 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800183 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100184
185
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186class Server(events.AbstractServer):
187
188 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700190 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200191 self._active_count = 0
192 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193
Victor Stinnere912e652014-07-12 03:11:53 +0200194 def __repr__(self):
195 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
196
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200199 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700200
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200201 def _detach(self):
202 assert self._active_count > 0
203 self._active_count -= 1
204 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700205 self._wakeup()
206
207 def close(self):
208 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200209 if sockets is None:
210 return
211 self.sockets = None
212 for sock in sockets:
213 self._loop._stop_serving(sock)
214 if self._active_count == 0:
215 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700216
217 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200218 waiters = self._waiters
219 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700220 for waiter in waiters:
221 if not waiter.done():
222 waiter.set_result(waiter)
223
Victor Stinnerf951d282014-06-29 00:46:45 +0200224 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700225 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200226 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400228 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200229 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700230 yield from waiter
231
232
233class BaseEventLoop(events.AbstractEventLoop):
234
235 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400236 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200237 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800238 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700239 self._ready = collections.deque()
240 self._scheduled = []
241 self._default_executor = None
242 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100243 # Identifier of the thread running the event loop, or None if the
244 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100245 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100246 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500247 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400248 self.set_debug((not sys.flags.ignore_environment
249 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200250 # In debug mode, if the execution of a callback or a step of a task
251 # exceed this duration in seconds, the slow callback/task is logged.
252 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100253 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400254 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400255 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256
Yury Selivanov0a91d482016-09-15 13:24:03 -0400257 if hasattr(sys, 'get_asyncgen_hooks'):
258 # Python >= 3.6
259 # A weak set of all asynchronous generators that are
260 # being iterated by the loop.
261 self._asyncgens = weakref.WeakSet()
262 else:
263 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700264
265 # Set to True when `loop.shutdown_asyncgens` is called.
266 self._asyncgens_shutdown_called = False
267
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200268 def __repr__(self):
269 return ('<%s running=%s closed=%s debug=%s>'
270 % (self.__class__.__name__, self.is_running(),
271 self.is_closed(), self.get_debug()))
272
Yury Selivanov7661db62016-05-16 15:38:39 -0400273 def create_future(self):
274 """Create a Future object attached to the loop."""
275 return futures.Future(loop=self)
276
Victor Stinner896a25a2014-07-08 11:29:25 +0200277 def create_task(self, coro):
278 """Schedule a coroutine object.
279
Victor Stinneracdb7822014-07-14 18:33:40 +0200280 Return a task object.
281 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100282 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400283 if self._task_factory is None:
284 task = tasks.Task(coro, loop=self)
285 if task._source_traceback:
286 del task._source_traceback[-1]
287 else:
288 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200289 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200290
Yury Selivanov740169c2015-05-11 14:23:38 -0400291 def set_task_factory(self, factory):
292 """Set a task factory that will be used by loop.create_task().
293
294 If factory is None the default task factory will be set.
295
296 If factory is a callable, it should have a signature matching
297 '(loop, coro)', where 'loop' will be a reference to the active
298 event loop, 'coro' will be a coroutine object. The callable
299 must return a Future.
300 """
301 if factory is not None and not callable(factory):
302 raise TypeError('task factory must be a callable or None')
303 self._task_factory = factory
304
305 def get_task_factory(self):
306 """Return a task factory, or None if the default one is in use."""
307 return self._task_factory
308
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700309 def _make_socket_transport(self, sock, protocol, waiter=None, *,
310 extra=None, server=None):
311 """Create socket transport."""
312 raise NotImplementedError
313
Victor Stinner15cc6782015-01-09 00:09:10 +0100314 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
315 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700316 extra=None, server=None):
317 """Create SSL transport."""
318 raise NotImplementedError
319
320 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200321 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700322 """Create datagram transport."""
323 raise NotImplementedError
324
325 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
326 extra=None):
327 """Create read pipe transport."""
328 raise NotImplementedError
329
330 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
331 extra=None):
332 """Create write pipe transport."""
333 raise NotImplementedError
334
Victor Stinnerf951d282014-06-29 00:46:45 +0200335 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700336 def _make_subprocess_transport(self, protocol, args, shell,
337 stdin, stdout, stderr, bufsize,
338 extra=None, **kwargs):
339 """Create subprocess transport."""
340 raise NotImplementedError
341
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700342 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200343 """Write a byte to self-pipe, to wake up the event loop.
344
345 This may be called from a different thread.
346
347 The subclass is responsible for implementing the self-pipe.
348 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700349 raise NotImplementedError
350
351 def _process_events(self, event_list):
352 """Process selector events."""
353 raise NotImplementedError
354
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200355 def _check_closed(self):
356 if self._closed:
357 raise RuntimeError('Event loop is closed')
358
Yury Selivanoveb636452016-09-08 22:01:51 -0700359 def _asyncgen_finalizer_hook(self, agen):
360 self._asyncgens.discard(agen)
361 if not self.is_closed():
362 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400363 # Wake up the loop if the finalizer was called from
364 # a different thread.
365 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700366
367 def _asyncgen_firstiter_hook(self, agen):
368 if self._asyncgens_shutdown_called:
369 warnings.warn(
370 "asynchronous generator {!r} was scheduled after "
371 "loop.shutdown_asyncgens() call".format(agen),
372 ResourceWarning, source=self)
373
374 self._asyncgens.add(agen)
375
376 @coroutine
377 def shutdown_asyncgens(self):
378 """Shutdown all active asynchronous generators."""
379 self._asyncgens_shutdown_called = True
380
Yury Selivanov0a91d482016-09-15 13:24:03 -0400381 if self._asyncgens is None or not len(self._asyncgens):
382 # If Python version is <3.6 or we don't have any asynchronous
383 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700384 return
385
386 closing_agens = list(self._asyncgens)
387 self._asyncgens.clear()
388
389 shutdown_coro = tasks.gather(
390 *[ag.aclose() for ag in closing_agens],
391 return_exceptions=True,
392 loop=self)
393
394 results = yield from shutdown_coro
395 for result, agen in zip(results, closing_agens):
396 if isinstance(result, Exception):
397 self.call_exception_handler({
398 'message': 'an error occurred during closing of '
399 'asynchronous generator {!r}'.format(agen),
400 'exception': result,
401 'asyncgen': agen
402 })
403
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700404 def run_forever(self):
405 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200406 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100407 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400408 raise RuntimeError('This event loop is already running')
409 if events._get_running_loop() is not None:
410 raise RuntimeError(
411 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400412 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100413 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400414 if self._asyncgens is not None:
415 old_agen_hooks = sys.get_asyncgen_hooks()
416 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
417 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700418 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400419 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700420 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800421 self._run_once()
422 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700423 break
424 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800425 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100426 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400427 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400428 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400429 if self._asyncgens is not None:
430 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431
432 def run_until_complete(self, future):
433 """Run until the Future is done.
434
435 If the argument is a coroutine, it is wrapped in a Task.
436
Victor Stinneracdb7822014-07-14 18:33:40 +0200437 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700438 with the same coroutine twice -- it would wrap it in two
439 different Tasks and that can't be good.
440
441 Return the Future's result, or raise its exception.
442 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200443 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200444
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700445 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400446 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200447 if new_task:
448 # An exception is raised if the future didn't complete, so there
449 # is no need to log the "destroy pending task" message
450 future._log_destroy_pending = False
451
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100452 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200453 try:
454 self.run_forever()
455 except:
456 if new_task and future.done() and not future.cancelled():
457 # The coroutine raised a BaseException. Consume the exception
458 # to not log a warning, the caller doesn't have access to the
459 # local task.
460 future.exception()
461 raise
Łukasz Langa70705e32017-05-23 00:36:23 -0700462 finally:
463 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700464 if not future.done():
465 raise RuntimeError('Event loop stopped before Future completed.')
466
467 return future.result()
468
469 def stop(self):
470 """Stop running the event loop.
471
Guido van Rossum41f69f42015-11-19 13:28:47 -0800472 Every callback already scheduled will still run. This simply informs
473 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700474 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800475 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200477 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700478 """Close the event loop.
479
480 This clears the queues and shuts down the executor,
481 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200482
483 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700484 """
Victor Stinner956de692014-12-26 21:07:52 +0100485 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200486 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200487 if self._closed:
488 return
Victor Stinnere912e652014-07-12 03:11:53 +0200489 if self._debug:
490 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400491 self._closed = True
492 self._ready.clear()
493 self._scheduled.clear()
494 executor = self._default_executor
495 if executor is not None:
496 self._default_executor = None
497 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200498
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200499 def is_closed(self):
500 """Returns True if the event loop was closed."""
501 return self._closed
502
Victor Stinner978a9af2015-01-29 17:50:58 +0100503 # On Python 3.3 and older, objects with a destructor part of a reference
504 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
505 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400506 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100507 def __del__(self):
508 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100509 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
510 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100511 if not self.is_running():
512 self.close()
513
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200515 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100516 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517
518 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200519 """Return the time according to the event loop's clock.
520
521 This is a float expressed in seconds since an epoch, but the
522 epoch, precision, accuracy and drift are unspecified and may
523 differ per event loop.
524 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 return time.monotonic()
526
527 def call_later(self, delay, callback, *args):
528 """Arrange for a callback to be called at a given time.
529
530 Return a Handle: an opaque object with a cancel() method that
531 can be used to cancel the call.
532
533 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200534 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535
536 Each callback will be called exactly once. If two callbacks
537 are scheduled for exactly the same time, it undefined which
538 will be called first.
539
540 Any positional arguments after the callback will be passed to
541 the callback when it is called.
542 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200543 timer = self.call_at(self.time() + delay, callback, *args)
544 if timer._source_traceback:
545 del timer._source_traceback[-1]
546 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700547
548 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200549 """Like call_later(), but uses an absolute time.
550
551 Absolute time corresponds to the event loop's time() method.
552 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100553 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100554 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100555 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700556 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500557 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200558 if timer._source_traceback:
559 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400561 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562 return timer
563
564 def call_soon(self, callback, *args):
565 """Arrange for a callback to be called as soon as possible.
566
Victor Stinneracdb7822014-07-14 18:33:40 +0200567 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700568 order in which they are registered. Each callback will be
569 called exactly once.
570
571 Any positional arguments after the callback will be passed to
572 the callback when it is called.
573 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700574 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100575 if self._debug:
576 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700577 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100578 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200579 if handle._source_traceback:
580 del handle._source_traceback[-1]
581 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100582
Yury Selivanov491a9122016-11-03 15:09:24 -0700583 def _check_callback(self, callback, method):
584 if (coroutines.iscoroutine(callback) or
585 coroutines.iscoroutinefunction(callback)):
586 raise TypeError(
587 "coroutines cannot be used with {}()".format(method))
588 if not callable(callback):
589 raise TypeError(
590 'a callable object was expected by {}(), got {!r}'.format(
591 method, callback))
592
593
Victor Stinner956de692014-12-26 21:07:52 +0100594 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500595 handle = events.Handle(callback, args, self)
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._ready.append(handle)
599 return handle
600
Victor Stinner956de692014-12-26 21:07:52 +0100601 def _check_thread(self):
602 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100603
Victor Stinneracdb7822014-07-14 18:33:40 +0200604 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100605 likely behave incorrectly when the assumption is violated.
606
Victor Stinneracdb7822014-07-14 18:33:40 +0200607 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100608 responsible for checking this condition for performance reasons.
609 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100610 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200611 return
Victor Stinner956de692014-12-26 21:07:52 +0100612 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100613 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100614 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200615 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100616 "than the current one")
617
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700618 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200619 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700620 self._check_closed()
621 if self._debug:
622 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100623 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200624 if handle._source_traceback:
625 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700626 self._write_to_self()
627 return handle
628
Yury Selivanov740169c2015-05-11 14:23:38 -0400629 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100630 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700631 if self._debug:
632 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700633 if executor is None:
634 executor = self._default_executor
635 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400636 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400638 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700639
640 def set_default_executor(self, executor):
641 self._default_executor = executor
642
Victor Stinnere912e652014-07-12 03:11:53 +0200643 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
644 msg = ["%s:%r" % (host, port)]
645 if family:
646 msg.append('family=%r' % family)
647 if type:
648 msg.append('type=%r' % type)
649 if proto:
650 msg.append('proto=%r' % proto)
651 if flags:
652 msg.append('flags=%r' % flags)
653 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200654 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200655
656 t0 = self.time()
657 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
658 dt = self.time() - t0
659
Victor Stinneracdb7822014-07-14 18:33:40 +0200660 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200661 % (msg, dt * 1e3, addrinfo))
662 if dt >= self.slow_callback_duration:
663 logger.info(msg)
664 else:
665 logger.debug(msg)
666 return addrinfo
667
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700668 def getaddrinfo(self, host, port, *,
669 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400670 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200671 return self.run_in_executor(None, self._getaddrinfo_debug,
672 host, port, family, type, proto, flags)
673 else:
674 return self.run_in_executor(None, socket.getaddrinfo,
675 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700676
677 def getnameinfo(self, sockaddr, flags=0):
678 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
679
Victor Stinnerf951d282014-06-29 00:46:45 +0200680 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700681 def create_connection(self, protocol_factory, host=None, port=None, *,
682 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700683 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200684 """Connect to a TCP server.
685
686 Create a streaming transport connection to a given Internet host and
687 port: socket family AF_INET or socket.AF_INET6 depending on host (or
688 family if specified), socket type SOCK_STREAM. protocol_factory must be
689 a callable returning a protocol instance.
690
691 This method is a coroutine which will try to establish the connection
692 in the background. When successful, the coroutine returns a
693 (transport, protocol) pair.
694 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700695 if server_hostname is not None and not ssl:
696 raise ValueError('server_hostname is only meaningful with ssl')
697
698 if server_hostname is None and ssl:
699 # Use host as default for server_hostname. It is an error
700 # if host is empty or not set, e.g. when an
701 # already-connected socket was passed or when only a port
702 # is given. To avoid this error, you can pass
703 # server_hostname='' -- this will bypass the hostname
704 # check. (This also means that if host is a numeric
705 # IP/IPv6 address, we will attempt to verify that exact
706 # address; this will probably fail, but it is possible to
707 # create a certificate for a specific IP address, so we
708 # don't judge it here.)
709 if not host:
710 raise ValueError('You must set server_hostname '
711 'when using ssl without a host')
712 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700713
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700714 if host is not None or port is not None:
715 if sock is not None:
716 raise ValueError(
717 'host/port and sock can not be specified at the same time')
718
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400719 f1 = _ensure_resolved((host, port), family=family,
720 type=socket.SOCK_STREAM, proto=proto,
721 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700722 fs = [f1]
723 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400724 f2 = _ensure_resolved(local_addr, family=family,
725 type=socket.SOCK_STREAM, proto=proto,
726 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700727 fs.append(f2)
728 else:
729 f2 = None
730
731 yield from tasks.wait(fs, loop=self)
732
733 infos = f1.result()
734 if not infos:
735 raise OSError('getaddrinfo() returned empty list')
736 if f2 is not None:
737 laddr_infos = f2.result()
738 if not laddr_infos:
739 raise OSError('getaddrinfo() returned empty list')
740
741 exceptions = []
742 for family, type, proto, cname, address in infos:
743 try:
744 sock = socket.socket(family=family, type=type, proto=proto)
745 sock.setblocking(False)
746 if f2 is not None:
747 for _, _, _, _, laddr in laddr_infos:
748 try:
749 sock.bind(laddr)
750 break
751 except OSError as exc:
752 exc = OSError(
753 exc.errno, 'error while '
754 'attempting to bind on address '
755 '{!r}: {}'.format(
756 laddr, exc.strerror.lower()))
757 exceptions.append(exc)
758 else:
759 sock.close()
760 sock = None
761 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200762 if self._debug:
763 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700764 yield from self.sock_connect(sock, address)
765 except OSError as exc:
766 if sock is not None:
767 sock.close()
768 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200769 except:
770 if sock is not None:
771 sock.close()
772 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700773 else:
774 break
775 else:
776 if len(exceptions) == 1:
777 raise exceptions[0]
778 else:
779 # If they all have the same str(), raise one.
780 model = str(exceptions[0])
781 if all(str(exc) == model for exc in exceptions):
782 raise exceptions[0]
783 # Raise a combined exception so the user can see all
784 # the various error messages.
785 raise OSError('Multiple exceptions: {}'.format(
786 ', '.join(str(exc) for exc in exceptions)))
787
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500788 else:
789 if sock is None:
790 raise ValueError(
791 'host and port was not specified and no sock specified')
Yury Selivanovdab05842016-11-21 17:47:27 -0500792 if not _is_stream_socket(sock):
793 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
794 # are SOCK_STREAM.
795 # We support passing AF_UNIX sockets even though we have
796 # a dedicated API for that: create_unix_connection.
797 # Disallowing AF_UNIX in this method, breaks backwards
798 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500799 raise ValueError(
Yury Selivanovdab05842016-11-21 17:47:27 -0500800 'A Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700801
Yury Selivanovb057c522014-02-18 12:15:06 -0500802 transport, protocol = yield from self._create_connection_transport(
803 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200804 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200805 # Get the socket from the transport because SSL transport closes
806 # the old socket and creates a new SSL socket
807 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200808 logger.debug("%r connected to %s:%r: (%r, %r)",
809 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500810 return transport, protocol
811
Victor Stinnerf951d282014-06-29 00:46:45 +0200812 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500813 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400814 server_hostname, server_side=False):
815
816 sock.setblocking(False)
817
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700818 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400819 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700820 if ssl:
821 sslcontext = None if isinstance(ssl, bool) else ssl
822 transport = self._make_ssl_transport(
823 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400824 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700825 else:
826 transport = self._make_socket_transport(sock, protocol, waiter)
827
Victor Stinner29ad0112015-01-15 00:04:21 +0100828 try:
829 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100830 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100831 transport.close()
832 raise
833
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700834 return transport, protocol
835
Victor Stinnerf951d282014-06-29 00:46:45 +0200836 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700837 def create_datagram_endpoint(self, protocol_factory,
838 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700839 family=0, proto=0, flags=0,
840 reuse_address=None, reuse_port=None,
841 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700842 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700843 if sock is not None:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500844 if not _is_dgram_socket(sock):
845 raise ValueError(
846 'A UDP Socket was expected, got {!r}'.format(sock))
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700847 if (local_addr or remote_addr or
848 family or proto or flags or
849 reuse_address or reuse_port or allow_broadcast):
850 # show the problematic kwargs in exception msg
851 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
852 family=family, proto=proto, flags=flags,
853 reuse_address=reuse_address, reuse_port=reuse_port,
854 allow_broadcast=allow_broadcast)
855 problems = ', '.join(
856 '{}={}'.format(k, v) for k, v in opts.items() if v)
857 raise ValueError(
858 'socket modifier keyword arguments can not be used '
859 'when sock is specified. ({})'.format(problems))
860 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700861 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700862 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700863 if not (local_addr or remote_addr):
864 if family == 0:
865 raise ValueError('unexpected address family')
866 addr_pairs_info = (((family, proto), (None, None)),)
867 else:
868 # join address by (family, protocol)
869 addr_infos = collections.OrderedDict()
870 for idx, addr in ((0, local_addr), (1, remote_addr)):
871 if addr is not None:
872 assert isinstance(addr, tuple) and len(addr) == 2, (
873 '2-tuple is expected')
874
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400875 infos = yield from _ensure_resolved(
876 addr, family=family, type=socket.SOCK_DGRAM,
877 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700878 if not infos:
879 raise OSError('getaddrinfo() returned empty list')
880
881 for fam, _, pro, _, address in infos:
882 key = (fam, pro)
883 if key not in addr_infos:
884 addr_infos[key] = [None, None]
885 addr_infos[key][idx] = address
886
887 # each addr has to have info for each (family, proto) pair
888 addr_pairs_info = [
889 (key, addr_pair) for key, addr_pair in addr_infos.items()
890 if not ((local_addr and addr_pair[0] is None) or
891 (remote_addr and addr_pair[1] is None))]
892
893 if not addr_pairs_info:
894 raise ValueError('can not get address information')
895
896 exceptions = []
897
898 if reuse_address is None:
899 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
900
901 for ((family, proto),
902 (local_address, remote_address)) in addr_pairs_info:
903 sock = None
904 r_addr = None
905 try:
906 sock = socket.socket(
907 family=family, type=socket.SOCK_DGRAM, proto=proto)
908 if reuse_address:
909 sock.setsockopt(
910 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
911 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400912 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700913 if allow_broadcast:
914 sock.setsockopt(
915 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
916 sock.setblocking(False)
917
918 if local_addr:
919 sock.bind(local_address)
920 if remote_addr:
921 yield from self.sock_connect(sock, remote_address)
922 r_addr = remote_address
923 except OSError as exc:
924 if sock is not None:
925 sock.close()
926 exceptions.append(exc)
927 except:
928 if sock is not None:
929 sock.close()
930 raise
931 else:
932 break
933 else:
934 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700935
936 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400937 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700938 transport = self._make_datagram_transport(
939 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200940 if self._debug:
941 if local_addr:
942 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
943 "created: (%r, %r)",
944 local_addr, remote_addr, transport, protocol)
945 else:
946 logger.debug("Datagram endpoint remote_addr=%r created: "
947 "(%r, %r)",
948 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100949
950 try:
951 yield from waiter
952 except:
953 transport.close()
954 raise
955
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700956 return transport, protocol
957
Victor Stinnerf951d282014-06-29 00:46:45 +0200958 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200959 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400960 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200961 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400962 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200963 if not infos:
964 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
965 return infos
966
967 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700968 def create_server(self, protocol_factory, host=None, port=None,
969 *,
970 family=socket.AF_UNSPEC,
971 flags=socket.AI_PASSIVE,
972 sock=None,
973 backlog=100,
974 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700975 reuse_address=None,
976 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200977 """Create a TCP server.
978
979 The host parameter can be a string, in that case the TCP server is bound
980 to host and port.
981
982 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500983 the TCP server is bound to all hosts of the sequence. If a host
984 appears multiple times (possibly indirectly e.g. when hostnames
985 resolve to the same IP address), the server is only bound once to that
986 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200987
Victor Stinneracdb7822014-07-14 18:33:40 +0200988 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200989
990 This method is a coroutine.
991 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700992 if isinstance(ssl, bool):
993 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700994 if host is not None or port is not None:
995 if sock is not None:
996 raise ValueError(
997 'host/port and sock can not be specified at the same time')
998
999 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1000 if reuse_address is None:
1001 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1002 sockets = []
1003 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001004 hosts = [None]
1005 elif (isinstance(host, str) or
1006 not isinstance(host, collections.Iterable)):
1007 hosts = [host]
1008 else:
1009 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001010
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001011 fs = [self._create_server_getaddrinfo(host, port, family=family,
1012 flags=flags)
1013 for host in hosts]
1014 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001015 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001016
1017 completed = False
1018 try:
1019 for res in infos:
1020 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001021 try:
1022 sock = socket.socket(af, socktype, proto)
1023 except socket.error:
1024 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001025 if self._debug:
1026 logger.warning('create_server() failed to create '
1027 'socket.socket(%r, %r, %r)',
1028 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001029 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001030 sockets.append(sock)
1031 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001032 sock.setsockopt(
1033 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1034 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001035 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001036 # Disable IPv4/IPv6 dual stack support (enabled by
1037 # default on Linux) which makes a single socket
1038 # listen on both address families.
1039 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1040 sock.setsockopt(socket.IPPROTO_IPV6,
1041 socket.IPV6_V6ONLY,
1042 True)
1043 try:
1044 sock.bind(sa)
1045 except OSError as err:
1046 raise OSError(err.errno, 'error while attempting '
1047 'to bind on address %r: %s'
1048 % (sa, err.strerror.lower()))
1049 completed = True
1050 finally:
1051 if not completed:
1052 for sock in sockets:
1053 sock.close()
1054 else:
1055 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001056 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanovdab05842016-11-21 17:47:27 -05001057 if not _is_stream_socket(sock):
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001058 raise ValueError(
Yury Selivanovdab05842016-11-21 17:47:27 -05001059 'A Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001060 sockets = [sock]
1061
1062 server = Server(self, sockets)
1063 for sock in sockets:
1064 sock.listen(backlog)
1065 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001066 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001067 if self._debug:
1068 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001069 return server
1070
Victor Stinnerf951d282014-06-29 00:46:45 +02001071 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001072 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
1073 """Handle an accepted connection.
1074
1075 This is used by servers that accept connections outside of
1076 asyncio but that use asyncio to handle connections.
1077
1078 This method is a coroutine. When completed, the coroutine
1079 returns a (transport, protocol) pair.
1080 """
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001081 if not _is_stream_socket(sock):
1082 raise ValueError(
1083 'A Stream Socket was expected, got {!r}'.format(sock))
1084
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001085 transport, protocol = yield from self._create_connection_transport(
1086 sock, protocol_factory, ssl, '', server_side=True)
1087 if self._debug:
1088 # Get the socket from the transport because SSL transport closes
1089 # the old socket and creates a new SSL socket
1090 sock = transport.get_extra_info('socket')
1091 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1092 return transport, protocol
1093
1094 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001095 def connect_read_pipe(self, protocol_factory, pipe):
1096 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001097 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001098 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001099
1100 try:
1101 yield from waiter
1102 except:
1103 transport.close()
1104 raise
1105
Victor Stinneracdb7822014-07-14 18:33:40 +02001106 if self._debug:
1107 logger.debug('Read pipe %r connected: (%r, %r)',
1108 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001109 return transport, protocol
1110
Victor Stinnerf951d282014-06-29 00:46:45 +02001111 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001112 def connect_write_pipe(self, protocol_factory, pipe):
1113 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001114 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001115 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001116
1117 try:
1118 yield from waiter
1119 except:
1120 transport.close()
1121 raise
1122
Victor Stinneracdb7822014-07-14 18:33:40 +02001123 if self._debug:
1124 logger.debug('Write pipe %r connected: (%r, %r)',
1125 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001126 return transport, protocol
1127
Victor Stinneracdb7822014-07-14 18:33:40 +02001128 def _log_subprocess(self, msg, stdin, stdout, stderr):
1129 info = [msg]
1130 if stdin is not None:
1131 info.append('stdin=%s' % _format_pipe(stdin))
1132 if stdout is not None and stderr == subprocess.STDOUT:
1133 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1134 else:
1135 if stdout is not None:
1136 info.append('stdout=%s' % _format_pipe(stdout))
1137 if stderr is not None:
1138 info.append('stderr=%s' % _format_pipe(stderr))
1139 logger.debug(' '.join(info))
1140
Victor Stinnerf951d282014-06-29 00:46:45 +02001141 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001142 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1143 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1144 universal_newlines=False, shell=True, bufsize=0,
1145 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001146 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001147 raise ValueError("cmd must be a string")
1148 if universal_newlines:
1149 raise ValueError("universal_newlines must be False")
1150 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001151 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001152 if bufsize != 0:
1153 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001154 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001155 if self._debug:
1156 # don't log parameters: they may contain sensitive information
1157 # (password) and may be too long
1158 debug_log = 'run shell command %r' % cmd
1159 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001160 transport = yield from self._make_subprocess_transport(
1161 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001162 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001163 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001164 return transport, protocol
1165
Victor Stinnerf951d282014-06-29 00:46:45 +02001166 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001167 def subprocess_exec(self, protocol_factory, program, *args,
1168 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1169 stderr=subprocess.PIPE, universal_newlines=False,
1170 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001171 if universal_newlines:
1172 raise ValueError("universal_newlines must be False")
1173 if shell:
1174 raise ValueError("shell must be False")
1175 if bufsize != 0:
1176 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001177 popen_args = (program,) + args
1178 for arg in popen_args:
1179 if not isinstance(arg, (str, bytes)):
1180 raise TypeError("program arguments must be "
1181 "a bytes or text string, not %s"
1182 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001183 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001184 if self._debug:
1185 # don't log parameters: they may contain sensitive information
1186 # (password) and may be too long
1187 debug_log = 'execute program %r' % program
1188 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001189 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001190 protocol, popen_args, False, stdin, stdout, stderr,
1191 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001192 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001193 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001194 return transport, protocol
1195
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001196 def get_exception_handler(self):
1197 """Return an exception handler, or None if the default one is in use.
1198 """
1199 return self._exception_handler
1200
Yury Selivanov569efa22014-02-18 18:02:19 -05001201 def set_exception_handler(self, handler):
1202 """Set handler as the new event loop exception handler.
1203
1204 If handler is None, the default exception handler will
1205 be set.
1206
1207 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001208 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001209 will be a reference to the active event loop, 'context'
1210 will be a dict object (see `call_exception_handler()`
1211 documentation for details about context).
1212 """
1213 if handler is not None and not callable(handler):
1214 raise TypeError('A callable object or None is expected, '
1215 'got {!r}'.format(handler))
1216 self._exception_handler = handler
1217
1218 def default_exception_handler(self, context):
1219 """Default exception handler.
1220
1221 This is called when an exception occurs and no exception
1222 handler is set, and can be called by a custom exception
1223 handler that wants to defer to the default behavior.
1224
Victor Stinneracdb7822014-07-14 18:33:40 +02001225 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001226 `call_exception_handler()`.
1227 """
1228 message = context.get('message')
1229 if not message:
1230 message = 'Unhandled exception in event loop'
1231
1232 exception = context.get('exception')
1233 if exception is not None:
1234 exc_info = (type(exception), exception, exception.__traceback__)
1235 else:
1236 exc_info = False
1237
Victor Stinnerff018e42015-01-28 00:30:40 +01001238 if ('source_traceback' not in context
1239 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001240 and self._current_handle._source_traceback):
1241 context['handle_traceback'] = self._current_handle._source_traceback
1242
Yury Selivanov569efa22014-02-18 18:02:19 -05001243 log_lines = [message]
1244 for key in sorted(context):
1245 if key in {'message', 'exception'}:
1246 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001247 value = context[key]
1248 if key == 'source_traceback':
1249 tb = ''.join(traceback.format_list(value))
1250 value = 'Object created at (most recent call last):\n'
1251 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001252 elif key == 'handle_traceback':
1253 tb = ''.join(traceback.format_list(value))
1254 value = 'Handle created at (most recent call last):\n'
1255 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001256 else:
1257 value = repr(value)
1258 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001259
1260 logger.error('\n'.join(log_lines), exc_info=exc_info)
1261
1262 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001263 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001264
Victor Stinneracdb7822014-07-14 18:33:40 +02001265 The context argument is a dict containing the following keys:
1266
Yury Selivanov569efa22014-02-18 18:02:19 -05001267 - 'message': Error message;
1268 - 'exception' (optional): Exception object;
1269 - 'future' (optional): Future instance;
1270 - 'handle' (optional): Handle instance;
1271 - 'protocol' (optional): Protocol instance;
1272 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001273 - 'socket' (optional): Socket instance;
1274 - 'asyncgen' (optional): Asynchronous generator that caused
1275 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001276
Victor Stinneracdb7822014-07-14 18:33:40 +02001277 New keys maybe introduced in the future.
1278
1279 Note: do not overload this method in an event loop subclass.
1280 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001281 `set_exception_handler()` method.
1282 """
1283 if self._exception_handler is None:
1284 try:
1285 self.default_exception_handler(context)
1286 except Exception:
1287 # Second protection layer for unexpected errors
1288 # in the default implementation, as well as for subclassed
1289 # event loops with overloaded "default_exception_handler".
1290 logger.error('Exception in default exception handler',
1291 exc_info=True)
1292 else:
1293 try:
1294 self._exception_handler(self, context)
1295 except Exception as exc:
1296 # Exception in the user set custom exception handler.
1297 try:
1298 # Let's try default handler.
1299 self.default_exception_handler({
1300 'message': 'Unhandled error in exception handler',
1301 'exception': exc,
1302 'context': context,
1303 })
1304 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001305 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001306 # overloaded.
1307 logger.error('Exception in default exception handler '
1308 'while handling an unexpected error '
1309 'in custom exception handler',
1310 exc_info=True)
1311
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001312 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001313 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001314 assert isinstance(handle, events.Handle), 'A Handle is required here'
1315 if handle._cancelled:
1316 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001317 assert not isinstance(handle, events.TimerHandle)
1318 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001319
1320 def _add_callback_signalsafe(self, handle):
1321 """Like _add_callback() but called from a signal handler."""
1322 self._add_callback(handle)
1323 self._write_to_self()
1324
Yury Selivanov592ada92014-09-25 12:07:56 -04001325 def _timer_handle_cancelled(self, handle):
1326 """Notification that a TimerHandle has been cancelled."""
1327 if handle._scheduled:
1328 self._timer_cancelled_count += 1
1329
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001330 def _run_once(self):
1331 """Run one full iteration of the event loop.
1332
1333 This calls all currently ready callbacks, polls for I/O,
1334 schedules the resulting callbacks, and finally schedules
1335 'call_later' callbacks.
1336 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001337
Yury Selivanov592ada92014-09-25 12:07:56 -04001338 sched_count = len(self._scheduled)
1339 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1340 self._timer_cancelled_count / sched_count >
1341 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001342 # Remove delayed calls that were cancelled if their number
1343 # is too high
1344 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001345 for handle in self._scheduled:
1346 if handle._cancelled:
1347 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001348 else:
1349 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001350
Victor Stinner68da8fc2014-09-30 18:08:36 +02001351 heapq.heapify(new_scheduled)
1352 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001353 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001354 else:
1355 # Remove delayed calls that were cancelled from head of queue.
1356 while self._scheduled and self._scheduled[0]._cancelled:
1357 self._timer_cancelled_count -= 1
1358 handle = heapq.heappop(self._scheduled)
1359 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001360
1361 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001362 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001363 timeout = 0
1364 elif self._scheduled:
1365 # Compute the desired timeout.
1366 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001367 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001368
Victor Stinner770e48d2014-07-11 11:58:33 +02001369 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001370 t0 = self.time()
1371 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001372 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001373 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001374 level = logging.INFO
1375 else:
1376 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001377 nevent = len(event_list)
1378 if timeout is None:
1379 logger.log(level, 'poll took %.3f ms: %s events',
1380 dt * 1e3, nevent)
1381 elif nevent:
1382 logger.log(level,
1383 'poll %.3f ms took %.3f ms: %s events',
1384 timeout * 1e3, dt * 1e3, nevent)
1385 elif dt >= 1.0:
1386 logger.log(level,
1387 'poll %.3f ms took %.3f ms: timeout',
1388 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001389 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001390 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001391 self._process_events(event_list)
1392
1393 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001394 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001395 while self._scheduled:
1396 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001397 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001398 break
1399 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001400 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001401 self._ready.append(handle)
1402
1403 # This is the only place where callbacks are actually *called*.
1404 # All other places just add them to ready.
1405 # Note: We run all currently scheduled callbacks, but not any
1406 # callbacks scheduled by callbacks run this time around --
1407 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001408 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001409 ntodo = len(self._ready)
1410 for i in range(ntodo):
1411 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001412 if handle._cancelled:
1413 continue
1414 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001415 try:
1416 self._current_handle = handle
1417 t0 = self.time()
1418 handle._run()
1419 dt = self.time() - t0
1420 if dt >= self.slow_callback_duration:
1421 logger.warning('Executing %s took %.3f seconds',
1422 _format_handle(handle), dt)
1423 finally:
1424 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001425 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001426 handle._run()
1427 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001428
Yury Selivanove8944cb2015-05-12 11:43:04 -04001429 def _set_coroutine_wrapper(self, enabled):
1430 try:
1431 set_wrapper = sys.set_coroutine_wrapper
1432 get_wrapper = sys.get_coroutine_wrapper
1433 except AttributeError:
1434 return
1435
1436 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001437 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001438 return
1439
1440 wrapper = coroutines.debug_wrapper
1441 current_wrapper = get_wrapper()
1442
1443 if enabled:
1444 if current_wrapper not in (None, wrapper):
1445 warnings.warn(
1446 "loop.set_debug(True): cannot set debug coroutine "
1447 "wrapper; another wrapper is already set %r" %
1448 current_wrapper, RuntimeWarning)
1449 else:
1450 set_wrapper(wrapper)
1451 self._coroutine_wrapper_set = True
1452 else:
1453 if current_wrapper not in (None, wrapper):
1454 warnings.warn(
1455 "loop.set_debug(False): cannot unset debug coroutine "
1456 "wrapper; another wrapper was set %r" %
1457 current_wrapper, RuntimeWarning)
1458 else:
1459 set_wrapper(None)
1460 self._coroutine_wrapper_set = False
1461
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001462 def get_debug(self):
1463 return self._debug
1464
1465 def set_debug(self, enabled):
1466 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001467
Yury Selivanove8944cb2015-05-12 11:43:04 -04001468 if self.is_running():
1469 self._set_coroutine_wrapper(enabled)