blob: ab92a0b580726eff9a28f02fcd64f681204ea1c4 [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
Serhiy Storchaka2e576f52017-04-24 09:05:00 +030017import collections.abc
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import concurrent.futures
19import heapq
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
Victor Stinnerf951d282014-06-29 00:46:45 +020032from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070033from . import events
34from . import futures
35from . import tasks
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070036from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037
38
Victor Stinner8c1a4a22015-01-06 01:03:58 +010039__all__ = ['BaseEventLoop']
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040
41
Yury Selivanov592ada92014-09-25 12:07:56 -040042# Minimum number of _scheduled timer handles before cleanup of
43# cancelled handles is performed.
44_MIN_SCHEDULED_TIMER_HANDLES = 100
45
46# Minimum fraction of _scheduled timer handles that are cancelled
47# before cleanup of cancelled handles is performed.
48_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049
Victor Stinnerc94a93a2016-04-01 21:43:39 +020050# Exceptions which must not call the exception handler in fatal error
51# methods (_fatal_error())
52_FATAL_ERROR_IGNORE = (BrokenPipeError,
53 ConnectionResetError, ConnectionAbortedError)
54
55
Victor Stinner0e6f52a2014-06-20 17:34:15 +020056def _format_handle(handle):
57 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040058 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020059 # format the task
60 return repr(cb.__self__)
61 else:
62 return str(handle)
63
64
Victor Stinneracdb7822014-07-14 18:33:40 +020065def _format_pipe(fd):
66 if fd == subprocess.PIPE:
67 return '<pipe>'
68 elif fd == subprocess.STDOUT:
69 return '<stdout>'
70 else:
71 return repr(fd)
72
73
Yury Selivanov5587d7c2016-09-15 15:45:07 -040074def _set_reuseport(sock):
75 if not hasattr(socket, 'SO_REUSEPORT'):
76 raise ValueError('reuse_port not supported by socket module')
77 else:
78 try:
79 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
80 except OSError:
81 raise ValueError('reuse_port not supported by socket module, '
82 'SO_REUSEPORT defined but not implemented.')
83
84
Yury Selivanova1a8b7d2016-11-09 15:47:00 -050085def _is_stream_socket(sock):
86 # Linux's socket.type is a bitmask that can include extra info
87 # about socket, therefore we can't do simple
88 # `sock_type == socket.SOCK_STREAM`.
89 return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM
90
91
92def _is_dgram_socket(sock):
93 # Linux's socket.type is a bitmask that can include extra info
94 # about socket, therefore we can't do simple
95 # `sock_type == socket.SOCK_DGRAM`.
96 return (sock.type & socket.SOCK_DGRAM) == socket.SOCK_DGRAM
97
98
Yury Selivanovd5c2a622015-12-16 19:31:17 -050099def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400100 # Try to skip getaddrinfo if "host" is already an IP. Users might have
101 # handled name resolution in their own code and pass in resolved IPs.
102 if not hasattr(socket, 'inet_pton'):
103 return
104
105 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
106 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 return None
108
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500109 if type == socket.SOCK_STREAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500110 # Linux only:
111 # getaddrinfo() can raise when socket.type is a bit mask.
112 # So if socket.type is a bit mask of SOCK_STREAM, and say
113 # SOCK_NONBLOCK, we simply return None, which will trigger
114 # a call to getaddrinfo() letting it process this request.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500115 proto = socket.IPPROTO_TCP
116 elif type == socket.SOCK_DGRAM:
117 proto = socket.IPPROTO_UDP
118 else:
119 return None
120
Yury Selivanova7146162016-06-02 16:51:07 -0400121 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400122 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700123 elif isinstance(port, bytes) and port == b'':
124 port = 0
125 elif isinstance(port, str) and port == '':
126 port = 0
127 else:
128 # If port's a service name like "http", don't skip getaddrinfo.
129 try:
130 port = int(port)
131 except (TypeError, ValueError):
132 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400133
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400134 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500135 afs = [socket.AF_INET]
136 if hasattr(socket, 'AF_INET6'):
137 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 else:
139 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500140
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400141 if isinstance(host, bytes):
142 host = host.decode('idna')
143 if '%' in host:
144 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
145 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500146 return None
147
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400148 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500149 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150 socket.inet_pton(af, host)
151 # The host has already been resolved.
152 return af, type, proto, '', (host, port)
153 except OSError:
154 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500155
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400156 # "host" is not an IP address.
157 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500158
159
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400160def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
161 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500162 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400163 info = _ipaddr_info(host, port, family, type, proto)
164 if info is not None:
165 # "host" is already a resolved IP.
166 fut = loop.create_future()
167 fut.set_result([info])
168 return fut
169 else:
170 return loop.getaddrinfo(host, port, family=family, type=type,
171 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100172
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700173
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100174def _run_until_complete_cb(fut):
175 exc = fut._exception
176 if (isinstance(exc, BaseException)
177 and not isinstance(exc, Exception)):
178 # Issue #22429: run_forever() already finished, no need to
179 # stop it.
180 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800181 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100182
183
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700184class Server(events.AbstractServer):
185
186 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 self._active_count = 0
190 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191
Victor Stinnere912e652014-07-12 03:11:53 +0200192 def __repr__(self):
193 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
194
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200195 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700196 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200199 def _detach(self):
200 assert self._active_count > 0
201 self._active_count -= 1
202 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700203 self._wakeup()
204
205 def close(self):
206 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200207 if sockets is None:
208 return
209 self.sockets = None
210 for sock in sockets:
211 self._loop._stop_serving(sock)
212 if self._active_count == 0:
213 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700214
215 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200216 waiters = self._waiters
217 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 for waiter in waiters:
219 if not waiter.done():
220 waiter.set_result(waiter)
221
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200222 async def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200223 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700224 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400225 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200226 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200227 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700228
229
230class BaseEventLoop(events.AbstractEventLoop):
231
232 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400233 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200234 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800235 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700236 self._ready = collections.deque()
237 self._scheduled = []
238 self._default_executor = None
239 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100240 # Identifier of the thread running the event loop, or None if the
241 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100242 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100243 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500244 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800245 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200246 # In debug mode, if the execution of a callback or a step of a task
247 # exceed this duration in seconds, the slow callback/task is logged.
248 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100249 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400250 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400251 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700252
Yury Selivanov0a91d482016-09-15 13:24:03 -0400253 if hasattr(sys, 'get_asyncgen_hooks'):
254 # Python >= 3.6
255 # A weak set of all asynchronous generators that are
256 # being iterated by the loop.
257 self._asyncgens = weakref.WeakSet()
258 else:
259 self._asyncgens = None
Yury Selivanoveb636452016-09-08 22:01:51 -0700260
261 # Set to True when `loop.shutdown_asyncgens` is called.
262 self._asyncgens_shutdown_called = False
263
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200264 def __repr__(self):
265 return ('<%s running=%s closed=%s debug=%s>'
266 % (self.__class__.__name__, self.is_running(),
267 self.is_closed(), self.get_debug()))
268
Yury Selivanov7661db62016-05-16 15:38:39 -0400269 def create_future(self):
270 """Create a Future object attached to the loop."""
271 return futures.Future(loop=self)
272
Victor Stinner896a25a2014-07-08 11:29:25 +0200273 def create_task(self, coro):
274 """Schedule a coroutine object.
275
Victor Stinneracdb7822014-07-14 18:33:40 +0200276 Return a task object.
277 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100278 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400279 if self._task_factory is None:
280 task = tasks.Task(coro, loop=self)
281 if task._source_traceback:
282 del task._source_traceback[-1]
283 else:
284 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200285 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200286
Yury Selivanov740169c2015-05-11 14:23:38 -0400287 def set_task_factory(self, factory):
288 """Set a task factory that will be used by loop.create_task().
289
290 If factory is None the default task factory will be set.
291
292 If factory is a callable, it should have a signature matching
293 '(loop, coro)', where 'loop' will be a reference to the active
294 event loop, 'coro' will be a coroutine object. The callable
295 must return a Future.
296 """
297 if factory is not None and not callable(factory):
298 raise TypeError('task factory must be a callable or None')
299 self._task_factory = factory
300
301 def get_task_factory(self):
302 """Return a task factory, or None if the default one is in use."""
303 return self._task_factory
304
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 def _make_socket_transport(self, sock, protocol, waiter=None, *,
306 extra=None, server=None):
307 """Create socket transport."""
308 raise NotImplementedError
309
Victor Stinner15cc6782015-01-09 00:09:10 +0100310 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
311 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700312 extra=None, server=None):
313 """Create SSL transport."""
314 raise NotImplementedError
315
316 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200317 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700318 """Create datagram transport."""
319 raise NotImplementedError
320
321 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
322 extra=None):
323 """Create read pipe transport."""
324 raise NotImplementedError
325
326 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
327 extra=None):
328 """Create write pipe transport."""
329 raise NotImplementedError
330
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200331 async def _make_subprocess_transport(self, protocol, args, shell,
332 stdin, stdout, stderr, bufsize,
333 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700334 """Create subprocess transport."""
335 raise NotImplementedError
336
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700337 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200338 """Write a byte to self-pipe, to wake up the event loop.
339
340 This may be called from a different thread.
341
342 The subclass is responsible for implementing the self-pipe.
343 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344 raise NotImplementedError
345
346 def _process_events(self, event_list):
347 """Process selector events."""
348 raise NotImplementedError
349
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200350 def _check_closed(self):
351 if self._closed:
352 raise RuntimeError('Event loop is closed')
353
Yury Selivanoveb636452016-09-08 22:01:51 -0700354 def _asyncgen_finalizer_hook(self, agen):
355 self._asyncgens.discard(agen)
356 if not self.is_closed():
357 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400358 # Wake up the loop if the finalizer was called from
359 # a different thread.
360 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700361
362 def _asyncgen_firstiter_hook(self, agen):
363 if self._asyncgens_shutdown_called:
364 warnings.warn(
365 "asynchronous generator {!r} was scheduled after "
366 "loop.shutdown_asyncgens() call".format(agen),
367 ResourceWarning, source=self)
368
369 self._asyncgens.add(agen)
370
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200371 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700372 """Shutdown all active asynchronous generators."""
373 self._asyncgens_shutdown_called = True
374
Yury Selivanov0a91d482016-09-15 13:24:03 -0400375 if self._asyncgens is None or not len(self._asyncgens):
376 # If Python version is <3.6 or we don't have any asynchronous
377 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700378 return
379
380 closing_agens = list(self._asyncgens)
381 self._asyncgens.clear()
382
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200383 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700384 *[ag.aclose() for ag in closing_agens],
385 return_exceptions=True,
386 loop=self)
387
Yury Selivanoveb636452016-09-08 22:01:51 -0700388 for result, agen in zip(results, closing_agens):
389 if isinstance(result, Exception):
390 self.call_exception_handler({
391 'message': 'an error occurred during closing of '
392 'asynchronous generator {!r}'.format(agen),
393 'exception': result,
394 'asyncgen': agen
395 })
396
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700397 def run_forever(self):
398 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200399 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100400 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400401 raise RuntimeError('This event loop is already running')
402 if events._get_running_loop() is not None:
403 raise RuntimeError(
404 'Cannot run the event loop while another loop is running')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400405 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100406 self._thread_id = threading.get_ident()
Yury Selivanov0a91d482016-09-15 13:24:03 -0400407 if self._asyncgens is not None:
408 old_agen_hooks = sys.get_asyncgen_hooks()
409 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
410 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400412 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700413 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800414 self._run_once()
415 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700416 break
417 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800418 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100419 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400420 events._set_running_loop(None)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400421 self._set_coroutine_wrapper(False)
Yury Selivanov0a91d482016-09-15 13:24:03 -0400422 if self._asyncgens is not None:
423 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700424
425 def run_until_complete(self, future):
426 """Run until the Future is done.
427
428 If the argument is a coroutine, it is wrapped in a Task.
429
Victor Stinneracdb7822014-07-14 18:33:40 +0200430 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 with the same coroutine twice -- it would wrap it in two
432 different Tasks and that can't be good.
433
434 Return the Future's result, or raise its exception.
435 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200436 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200437
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700438 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400439 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200440 if new_task:
441 # An exception is raised if the future didn't complete, so there
442 # is no need to log the "destroy pending task" message
443 future._log_destroy_pending = False
444
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100445 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200446 try:
447 self.run_forever()
448 except:
449 if new_task and future.done() and not future.cancelled():
450 # The coroutine raised a BaseException. Consume the exception
451 # to not log a warning, the caller doesn't have access to the
452 # local task.
453 future.exception()
454 raise
jimmylai21b3e042017-05-22 22:32:46 -0700455 finally:
456 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700457 if not future.done():
458 raise RuntimeError('Event loop stopped before Future completed.')
459
460 return future.result()
461
462 def stop(self):
463 """Stop running the event loop.
464
Guido van Rossum41f69f42015-11-19 13:28:47 -0800465 Every callback already scheduled will still run. This simply informs
466 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800468 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700469
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200470 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700471 """Close the event loop.
472
473 This clears the queues and shuts down the executor,
474 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200475
476 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700477 """
Victor Stinner956de692014-12-26 21:07:52 +0100478 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200479 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200480 if self._closed:
481 return
Victor Stinnere912e652014-07-12 03:11:53 +0200482 if self._debug:
483 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400484 self._closed = True
485 self._ready.clear()
486 self._scheduled.clear()
487 executor = self._default_executor
488 if executor is not None:
489 self._default_executor = None
490 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200491
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200492 def is_closed(self):
493 """Returns True if the event loop was closed."""
494 return self._closed
495
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900496 def __del__(self):
497 if not self.is_closed():
498 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
499 source=self)
500 if not self.is_running():
501 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100502
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700503 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200504 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100505 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506
507 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200508 """Return the time according to the event loop's clock.
509
510 This is a float expressed in seconds since an epoch, but the
511 epoch, precision, accuracy and drift are unspecified and may
512 differ per event loop.
513 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 return time.monotonic()
515
516 def call_later(self, delay, callback, *args):
517 """Arrange for a callback to be called at a given time.
518
519 Return a Handle: an opaque object with a cancel() method that
520 can be used to cancel the call.
521
522 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200523 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 Each callback will be called exactly once. If two callbacks
526 are scheduled for exactly the same time, it undefined which
527 will be called first.
528
529 Any positional arguments after the callback will be passed to
530 the callback when it is called.
531 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200532 timer = self.call_at(self.time() + delay, callback, *args)
533 if timer._source_traceback:
534 del timer._source_traceback[-1]
535 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700536
537 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200538 """Like call_later(), but uses an absolute time.
539
540 Absolute time corresponds to the event loop's time() method.
541 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100542 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100543 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100544 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700545 self._check_callback(callback, 'call_at')
Yury Selivanov569efa22014-02-18 18:02:19 -0500546 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200547 if timer._source_traceback:
548 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400550 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 return timer
552
553 def call_soon(self, callback, *args):
554 """Arrange for a callback to be called as soon as possible.
555
Victor Stinneracdb7822014-07-14 18:33:40 +0200556 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557 order in which they are registered. Each callback will be
558 called exactly once.
559
560 Any positional arguments after the callback will be passed to
561 the callback when it is called.
562 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700563 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100564 if self._debug:
565 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700566 self._check_callback(callback, 'call_soon')
Victor Stinner956de692014-12-26 21:07:52 +0100567 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200568 if handle._source_traceback:
569 del handle._source_traceback[-1]
570 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100571
Yury Selivanov491a9122016-11-03 15:09:24 -0700572 def _check_callback(self, callback, method):
573 if (coroutines.iscoroutine(callback) or
574 coroutines.iscoroutinefunction(callback)):
575 raise TypeError(
576 "coroutines cannot be used with {}()".format(method))
577 if not callable(callback):
578 raise TypeError(
579 'a callable object was expected by {}(), got {!r}'.format(
580 method, callback))
581
582
Victor Stinner956de692014-12-26 21:07:52 +0100583 def _call_soon(self, callback, args):
Yury Selivanov569efa22014-02-18 18:02:19 -0500584 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200585 if handle._source_traceback:
586 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587 self._ready.append(handle)
588 return handle
589
Victor Stinner956de692014-12-26 21:07:52 +0100590 def _check_thread(self):
591 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100592
Victor Stinneracdb7822014-07-14 18:33:40 +0200593 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100594 likely behave incorrectly when the assumption is violated.
595
Victor Stinneracdb7822014-07-14 18:33:40 +0200596 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100597 responsible for checking this condition for performance reasons.
598 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100599 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200600 return
Victor Stinner956de692014-12-26 21:07:52 +0100601 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100602 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100603 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200604 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100605 "than the current one")
606
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700607 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200608 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700609 self._check_closed()
610 if self._debug:
611 self._check_callback(callback, 'call_soon_threadsafe')
Victor Stinner956de692014-12-26 21:07:52 +0100612 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200613 if handle._source_traceback:
614 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700615 self._write_to_self()
616 return handle
617
Yury Selivanov740169c2015-05-11 14:23:38 -0400618 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100619 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700620 if self._debug:
621 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622 if executor is None:
623 executor = self._default_executor
624 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400625 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700626 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400627 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700628
629 def set_default_executor(self, executor):
630 self._default_executor = executor
631
Victor Stinnere912e652014-07-12 03:11:53 +0200632 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
633 msg = ["%s:%r" % (host, port)]
634 if family:
635 msg.append('family=%r' % family)
636 if type:
637 msg.append('type=%r' % type)
638 if proto:
639 msg.append('proto=%r' % proto)
640 if flags:
641 msg.append('flags=%r' % flags)
642 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200643 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200644
645 t0 = self.time()
646 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
647 dt = self.time() - t0
648
Victor Stinneracdb7822014-07-14 18:33:40 +0200649 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200650 % (msg, dt * 1e3, addrinfo))
651 if dt >= self.slow_callback_duration:
652 logger.info(msg)
653 else:
654 logger.debug(msg)
655 return addrinfo
656
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657 def getaddrinfo(self, host, port, *,
658 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400659 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200660 return self.run_in_executor(None, self._getaddrinfo_debug,
661 host, port, family, type, proto, flags)
662 else:
663 return self.run_in_executor(None, socket.getaddrinfo,
664 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665
666 def getnameinfo(self, sockaddr, flags=0):
667 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
668
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200669 async def create_connection(self, protocol_factory, host=None, port=None,
670 *, ssl=None, family=0,
671 proto=0, flags=0, sock=None,
672 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200673 """Connect to a TCP server.
674
675 Create a streaming transport connection to a given Internet host and
676 port: socket family AF_INET or socket.AF_INET6 depending on host (or
677 family if specified), socket type SOCK_STREAM. protocol_factory must be
678 a callable returning a protocol instance.
679
680 This method is a coroutine which will try to establish the connection
681 in the background. When successful, the coroutine returns a
682 (transport, protocol) pair.
683 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700684 if server_hostname is not None and not ssl:
685 raise ValueError('server_hostname is only meaningful with ssl')
686
687 if server_hostname is None and ssl:
688 # Use host as default for server_hostname. It is an error
689 # if host is empty or not set, e.g. when an
690 # already-connected socket was passed or when only a port
691 # is given. To avoid this error, you can pass
692 # server_hostname='' -- this will bypass the hostname
693 # check. (This also means that if host is a numeric
694 # IP/IPv6 address, we will attempt to verify that exact
695 # address; this will probably fail, but it is possible to
696 # create a certificate for a specific IP address, so we
697 # don't judge it here.)
698 if not host:
699 raise ValueError('You must set server_hostname '
700 'when using ssl without a host')
701 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700702
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700703 if host is not None or port is not None:
704 if sock is not None:
705 raise ValueError(
706 'host/port and sock can not be specified at the same time')
707
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400708 f1 = _ensure_resolved((host, port), family=family,
709 type=socket.SOCK_STREAM, proto=proto,
710 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700711 fs = [f1]
712 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400713 f2 = _ensure_resolved(local_addr, family=family,
714 type=socket.SOCK_STREAM, proto=proto,
715 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700716 fs.append(f2)
717 else:
718 f2 = None
719
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200720 await tasks.wait(fs, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700721
722 infos = f1.result()
723 if not infos:
724 raise OSError('getaddrinfo() returned empty list')
725 if f2 is not None:
726 laddr_infos = f2.result()
727 if not laddr_infos:
728 raise OSError('getaddrinfo() returned empty list')
729
730 exceptions = []
731 for family, type, proto, cname, address in infos:
732 try:
733 sock = socket.socket(family=family, type=type, proto=proto)
734 sock.setblocking(False)
735 if f2 is not None:
736 for _, _, _, _, laddr in laddr_infos:
737 try:
738 sock.bind(laddr)
739 break
740 except OSError as exc:
741 exc = OSError(
742 exc.errno, 'error while '
743 'attempting to bind on address '
744 '{!r}: {}'.format(
745 laddr, exc.strerror.lower()))
746 exceptions.append(exc)
747 else:
748 sock.close()
749 sock = None
750 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200751 if self._debug:
752 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200753 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700754 except OSError as exc:
755 if sock is not None:
756 sock.close()
757 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200758 except:
759 if sock is not None:
760 sock.close()
761 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700762 else:
763 break
764 else:
765 if len(exceptions) == 1:
766 raise exceptions[0]
767 else:
768 # If they all have the same str(), raise one.
769 model = str(exceptions[0])
770 if all(str(exc) == model for exc in exceptions):
771 raise exceptions[0]
772 # Raise a combined exception so the user can see all
773 # the various error messages.
774 raise OSError('Multiple exceptions: {}'.format(
775 ', '.join(str(exc) for exc in exceptions)))
776
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500777 else:
778 if sock is None:
779 raise ValueError(
780 'host and port was not specified and no sock specified')
Yury Selivanovdab05842016-11-21 17:47:27 -0500781 if not _is_stream_socket(sock):
782 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
783 # are SOCK_STREAM.
784 # We support passing AF_UNIX sockets even though we have
785 # a dedicated API for that: create_unix_connection.
786 # Disallowing AF_UNIX in this method, breaks backwards
787 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500788 raise ValueError(
Yury Selivanovdab05842016-11-21 17:47:27 -0500789 'A Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700790
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200791 transport, protocol = await self._create_connection_transport(
Yury Selivanovb057c522014-02-18 12:15:06 -0500792 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200793 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200794 # Get the socket from the transport because SSL transport closes
795 # the old socket and creates a new SSL socket
796 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200797 logger.debug("%r connected to %s:%r: (%r, %r)",
798 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500799 return transport, protocol
800
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200801 async def _create_connection_transport(self, sock, protocol_factory, ssl,
802 server_hostname, server_side=False):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400803
804 sock.setblocking(False)
805
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700806 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400807 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700808 if ssl:
809 sslcontext = None if isinstance(ssl, bool) else ssl
810 transport = self._make_ssl_transport(
811 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400812 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700813 else:
814 transport = self._make_socket_transport(sock, protocol, waiter)
815
Victor Stinner29ad0112015-01-15 00:04:21 +0100816 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200817 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100818 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100819 transport.close()
820 raise
821
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700822 return transport, protocol
823
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200824 async def create_datagram_endpoint(self, protocol_factory,
825 local_addr=None, remote_addr=None, *,
826 family=0, proto=0, flags=0,
827 reuse_address=None, reuse_port=None,
828 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700829 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700830 if sock is not None:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500831 if not _is_dgram_socket(sock):
832 raise ValueError(
833 'A UDP Socket was expected, got {!r}'.format(sock))
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700834 if (local_addr or remote_addr or
835 family or proto or flags or
836 reuse_address or reuse_port or allow_broadcast):
837 # show the problematic kwargs in exception msg
838 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
839 family=family, proto=proto, flags=flags,
840 reuse_address=reuse_address, reuse_port=reuse_port,
841 allow_broadcast=allow_broadcast)
842 problems = ', '.join(
843 '{}={}'.format(k, v) for k, v in opts.items() if v)
844 raise ValueError(
845 'socket modifier keyword arguments can not be used '
846 'when sock is specified. ({})'.format(problems))
847 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700848 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700849 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700850 if not (local_addr or remote_addr):
851 if family == 0:
852 raise ValueError('unexpected address family')
853 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100854 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
855 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +0100856 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100857 raise TypeError('string is expected')
858 addr_pairs_info = (((family, proto),
859 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700860 else:
861 # join address by (family, protocol)
862 addr_infos = collections.OrderedDict()
863 for idx, addr in ((0, local_addr), (1, remote_addr)):
864 if addr is not None:
865 assert isinstance(addr, tuple) and len(addr) == 2, (
866 '2-tuple is expected')
867
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200868 infos = await _ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400869 addr, family=family, type=socket.SOCK_DGRAM,
870 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700871 if not infos:
872 raise OSError('getaddrinfo() returned empty list')
873
874 for fam, _, pro, _, address in infos:
875 key = (fam, pro)
876 if key not in addr_infos:
877 addr_infos[key] = [None, None]
878 addr_infos[key][idx] = address
879
880 # each addr has to have info for each (family, proto) pair
881 addr_pairs_info = [
882 (key, addr_pair) for key, addr_pair in addr_infos.items()
883 if not ((local_addr and addr_pair[0] is None) or
884 (remote_addr and addr_pair[1] is None))]
885
886 if not addr_pairs_info:
887 raise ValueError('can not get address information')
888
889 exceptions = []
890
891 if reuse_address is None:
892 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
893
894 for ((family, proto),
895 (local_address, remote_address)) in addr_pairs_info:
896 sock = None
897 r_addr = None
898 try:
899 sock = socket.socket(
900 family=family, type=socket.SOCK_DGRAM, proto=proto)
901 if reuse_address:
902 sock.setsockopt(
903 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
904 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -0400905 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700906 if allow_broadcast:
907 sock.setsockopt(
908 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
909 sock.setblocking(False)
910
911 if local_addr:
912 sock.bind(local_address)
913 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200914 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700915 r_addr = remote_address
916 except OSError as exc:
917 if sock is not None:
918 sock.close()
919 exceptions.append(exc)
920 except:
921 if sock is not None:
922 sock.close()
923 raise
924 else:
925 break
926 else:
927 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700928
929 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400930 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700931 transport = self._make_datagram_transport(
932 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200933 if self._debug:
934 if local_addr:
935 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
936 "created: (%r, %r)",
937 local_addr, remote_addr, transport, protocol)
938 else:
939 logger.debug("Datagram endpoint remote_addr=%r created: "
940 "(%r, %r)",
941 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100942
943 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200944 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +0100945 except:
946 transport.close()
947 raise
948
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700949 return transport, protocol
950
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200951 async def _create_server_getaddrinfo(self, host, port, family, flags):
952 infos = await _ensure_resolved((host, port), family=family,
953 type=socket.SOCK_STREAM,
954 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200955 if not infos:
956 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
957 return infos
958
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200959 async def create_server(self, protocol_factory, host=None, port=None,
960 *,
961 family=socket.AF_UNSPEC,
962 flags=socket.AI_PASSIVE,
963 sock=None,
964 backlog=100,
965 ssl=None,
966 reuse_address=None,
967 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200968 """Create a TCP server.
969
970 The host parameter can be a string, in that case the TCP server is bound
971 to host and port.
972
973 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500974 the TCP server is bound to all hosts of the sequence. If a host
975 appears multiple times (possibly indirectly e.g. when hostnames
976 resolve to the same IP address), the server is only bound once to that
977 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200978
Victor Stinneracdb7822014-07-14 18:33:40 +0200979 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200980
981 This method is a coroutine.
982 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700983 if isinstance(ssl, bool):
984 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700985 if host is not None or port is not None:
986 if sock is not None:
987 raise ValueError(
988 'host/port and sock can not be specified at the same time')
989
990 AF_INET6 = getattr(socket, 'AF_INET6', 0)
991 if reuse_address is None:
992 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
993 sockets = []
994 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200995 hosts = [None]
996 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +0300997 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200998 hosts = [host]
999 else:
1000 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001001
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001002 fs = [self._create_server_getaddrinfo(host, port, family=family,
1003 flags=flags)
1004 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001005 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001006 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001007
1008 completed = False
1009 try:
1010 for res in infos:
1011 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001012 try:
1013 sock = socket.socket(af, socktype, proto)
1014 except socket.error:
1015 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001016 if self._debug:
1017 logger.warning('create_server() failed to create '
1018 'socket.socket(%r, %r, %r)',
1019 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001020 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001021 sockets.append(sock)
1022 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001023 sock.setsockopt(
1024 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1025 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001026 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001027 # Disable IPv4/IPv6 dual stack support (enabled by
1028 # default on Linux) which makes a single socket
1029 # listen on both address families.
1030 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1031 sock.setsockopt(socket.IPPROTO_IPV6,
1032 socket.IPV6_V6ONLY,
1033 True)
1034 try:
1035 sock.bind(sa)
1036 except OSError as err:
1037 raise OSError(err.errno, 'error while attempting '
1038 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001039 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001040 completed = True
1041 finally:
1042 if not completed:
1043 for sock in sockets:
1044 sock.close()
1045 else:
1046 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001047 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanovdab05842016-11-21 17:47:27 -05001048 if not _is_stream_socket(sock):
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001049 raise ValueError(
Yury Selivanovdab05842016-11-21 17:47:27 -05001050 'A Stream Socket was expected, got {!r}'.format(sock))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001051 sockets = [sock]
1052
1053 server = Server(self, sockets)
1054 for sock in sockets:
1055 sock.listen(backlog)
1056 sock.setblocking(False)
Yury Selivanova1b0e7d2016-09-15 14:13:15 -04001057 self._start_serving(protocol_factory, sock, ssl, server, backlog)
Victor Stinnere912e652014-07-12 03:11:53 +02001058 if self._debug:
1059 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001060 return server
1061
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001062 async def connect_accepted_socket(self, protocol_factory, sock,
1063 *, ssl=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001064 """Handle an accepted connection.
1065
1066 This is used by servers that accept connections outside of
1067 asyncio but that use asyncio to handle connections.
1068
1069 This method is a coroutine. When completed, the coroutine
1070 returns a (transport, protocol) pair.
1071 """
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001072 if not _is_stream_socket(sock):
1073 raise ValueError(
1074 'A Stream Socket was expected, got {!r}'.format(sock))
1075
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001076 transport, protocol = await self._create_connection_transport(
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001077 sock, protocol_factory, ssl, '', server_side=True)
1078 if self._debug:
1079 # Get the socket from the transport because SSL transport closes
1080 # the old socket and creates a new SSL socket
1081 sock = transport.get_extra_info('socket')
1082 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1083 return transport, protocol
1084
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001085 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001086 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001087 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001088 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001089
1090 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001091 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001092 except:
1093 transport.close()
1094 raise
1095
Victor Stinneracdb7822014-07-14 18:33:40 +02001096 if self._debug:
1097 logger.debug('Read pipe %r connected: (%r, %r)',
1098 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001099 return transport, protocol
1100
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001101 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001102 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001103 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001104 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001105
1106 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001107 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001108 except:
1109 transport.close()
1110 raise
1111
Victor Stinneracdb7822014-07-14 18:33:40 +02001112 if self._debug:
1113 logger.debug('Write pipe %r connected: (%r, %r)',
1114 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001115 return transport, protocol
1116
Victor Stinneracdb7822014-07-14 18:33:40 +02001117 def _log_subprocess(self, msg, stdin, stdout, stderr):
1118 info = [msg]
1119 if stdin is not None:
1120 info.append('stdin=%s' % _format_pipe(stdin))
1121 if stdout is not None and stderr == subprocess.STDOUT:
1122 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1123 else:
1124 if stdout is not None:
1125 info.append('stdout=%s' % _format_pipe(stdout))
1126 if stderr is not None:
1127 info.append('stderr=%s' % _format_pipe(stderr))
1128 logger.debug(' '.join(info))
1129
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001130 async def subprocess_shell(self, protocol_factory, cmd, *,
1131 stdin=subprocess.PIPE,
1132 stdout=subprocess.PIPE,
1133 stderr=subprocess.PIPE,
1134 universal_newlines=False,
1135 shell=True, bufsize=0,
1136 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001137 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001138 raise ValueError("cmd must be a string")
1139 if universal_newlines:
1140 raise ValueError("universal_newlines must be False")
1141 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001142 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001143 if bufsize != 0:
1144 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001145 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001146 if self._debug:
1147 # don't log parameters: they may contain sensitive information
1148 # (password) and may be too long
1149 debug_log = 'run shell command %r' % cmd
1150 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001151 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001152 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001153 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001154 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001155 return transport, protocol
1156
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001157 async def subprocess_exec(self, protocol_factory, program, *args,
1158 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1159 stderr=subprocess.PIPE, universal_newlines=False,
1160 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001161 if universal_newlines:
1162 raise ValueError("universal_newlines must be False")
1163 if shell:
1164 raise ValueError("shell must be False")
1165 if bufsize != 0:
1166 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001167 popen_args = (program,) + args
1168 for arg in popen_args:
1169 if not isinstance(arg, (str, bytes)):
1170 raise TypeError("program arguments must be "
1171 "a bytes or text string, not %s"
1172 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001173 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001174 if self._debug:
1175 # don't log parameters: they may contain sensitive information
1176 # (password) and may be too long
1177 debug_log = 'execute program %r' % program
1178 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001179 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001180 protocol, popen_args, False, stdin, stdout, stderr,
1181 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001182 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001183 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001184 return transport, protocol
1185
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001186 def get_exception_handler(self):
1187 """Return an exception handler, or None if the default one is in use.
1188 """
1189 return self._exception_handler
1190
Yury Selivanov569efa22014-02-18 18:02:19 -05001191 def set_exception_handler(self, handler):
1192 """Set handler as the new event loop exception handler.
1193
1194 If handler is None, the default exception handler will
1195 be set.
1196
1197 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001198 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001199 will be a reference to the active event loop, 'context'
1200 will be a dict object (see `call_exception_handler()`
1201 documentation for details about context).
1202 """
1203 if handler is not None and not callable(handler):
1204 raise TypeError('A callable object or None is expected, '
1205 'got {!r}'.format(handler))
1206 self._exception_handler = handler
1207
1208 def default_exception_handler(self, context):
1209 """Default exception handler.
1210
1211 This is called when an exception occurs and no exception
1212 handler is set, and can be called by a custom exception
1213 handler that wants to defer to the default behavior.
1214
Antoine Pitrou921e9432017-11-07 17:23:29 +01001215 This default handler logs the error message and other
1216 context-dependent information. In debug mode, a truncated
1217 stack trace is also appended showing where the given object
1218 (e.g. a handle or future or task) was created, if any.
1219
Victor Stinneracdb7822014-07-14 18:33:40 +02001220 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001221 `call_exception_handler()`.
1222 """
1223 message = context.get('message')
1224 if not message:
1225 message = 'Unhandled exception in event loop'
1226
1227 exception = context.get('exception')
1228 if exception is not None:
1229 exc_info = (type(exception), exception, exception.__traceback__)
1230 else:
1231 exc_info = False
1232
Victor Stinnerff018e42015-01-28 00:30:40 +01001233 if ('source_traceback' not in context
1234 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001235 and self._current_handle._source_traceback):
1236 context['handle_traceback'] = self._current_handle._source_traceback
1237
Yury Selivanov569efa22014-02-18 18:02:19 -05001238 log_lines = [message]
1239 for key in sorted(context):
1240 if key in {'message', 'exception'}:
1241 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001242 value = context[key]
1243 if key == 'source_traceback':
1244 tb = ''.join(traceback.format_list(value))
1245 value = 'Object created at (most recent call last):\n'
1246 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001247 elif key == 'handle_traceback':
1248 tb = ''.join(traceback.format_list(value))
1249 value = 'Handle created at (most recent call last):\n'
1250 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001251 else:
1252 value = repr(value)
1253 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001254
1255 logger.error('\n'.join(log_lines), exc_info=exc_info)
1256
1257 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001258 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001259
Victor Stinneracdb7822014-07-14 18:33:40 +02001260 The context argument is a dict containing the following keys:
1261
Yury Selivanov569efa22014-02-18 18:02:19 -05001262 - 'message': Error message;
1263 - 'exception' (optional): Exception object;
1264 - 'future' (optional): Future instance;
1265 - 'handle' (optional): Handle instance;
1266 - 'protocol' (optional): Protocol instance;
1267 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001268 - 'socket' (optional): Socket instance;
1269 - 'asyncgen' (optional): Asynchronous generator that caused
1270 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001271
Victor Stinneracdb7822014-07-14 18:33:40 +02001272 New keys maybe introduced in the future.
1273
1274 Note: do not overload this method in an event loop subclass.
1275 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001276 `set_exception_handler()` method.
1277 """
1278 if self._exception_handler is None:
1279 try:
1280 self.default_exception_handler(context)
1281 except Exception:
1282 # Second protection layer for unexpected errors
1283 # in the default implementation, as well as for subclassed
1284 # event loops with overloaded "default_exception_handler".
1285 logger.error('Exception in default exception handler',
1286 exc_info=True)
1287 else:
1288 try:
1289 self._exception_handler(self, context)
1290 except Exception as exc:
1291 # Exception in the user set custom exception handler.
1292 try:
1293 # Let's try default handler.
1294 self.default_exception_handler({
1295 'message': 'Unhandled error in exception handler',
1296 'exception': exc,
1297 'context': context,
1298 })
1299 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001300 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001301 # overloaded.
1302 logger.error('Exception in default exception handler '
1303 'while handling an unexpected error '
1304 'in custom exception handler',
1305 exc_info=True)
1306
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001307 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001308 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001309 assert isinstance(handle, events.Handle), 'A Handle is required here'
1310 if handle._cancelled:
1311 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001312 assert not isinstance(handle, events.TimerHandle)
1313 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001314
1315 def _add_callback_signalsafe(self, handle):
1316 """Like _add_callback() but called from a signal handler."""
1317 self._add_callback(handle)
1318 self._write_to_self()
1319
Yury Selivanov592ada92014-09-25 12:07:56 -04001320 def _timer_handle_cancelled(self, handle):
1321 """Notification that a TimerHandle has been cancelled."""
1322 if handle._scheduled:
1323 self._timer_cancelled_count += 1
1324
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001325 def _run_once(self):
1326 """Run one full iteration of the event loop.
1327
1328 This calls all currently ready callbacks, polls for I/O,
1329 schedules the resulting callbacks, and finally schedules
1330 'call_later' callbacks.
1331 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001332
Yury Selivanov592ada92014-09-25 12:07:56 -04001333 sched_count = len(self._scheduled)
1334 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1335 self._timer_cancelled_count / sched_count >
1336 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001337 # Remove delayed calls that were cancelled if their number
1338 # is too high
1339 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001340 for handle in self._scheduled:
1341 if handle._cancelled:
1342 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001343 else:
1344 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001345
Victor Stinner68da8fc2014-09-30 18:08:36 +02001346 heapq.heapify(new_scheduled)
1347 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001348 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001349 else:
1350 # Remove delayed calls that were cancelled from head of queue.
1351 while self._scheduled and self._scheduled[0]._cancelled:
1352 self._timer_cancelled_count -= 1
1353 handle = heapq.heappop(self._scheduled)
1354 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001355
1356 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001357 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001358 timeout = 0
1359 elif self._scheduled:
1360 # Compute the desired timeout.
1361 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001362 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001363
Victor Stinner770e48d2014-07-11 11:58:33 +02001364 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001365 t0 = self.time()
1366 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001367 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001368 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001369 level = logging.INFO
1370 else:
1371 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001372 nevent = len(event_list)
1373 if timeout is None:
1374 logger.log(level, 'poll took %.3f ms: %s events',
1375 dt * 1e3, nevent)
1376 elif nevent:
1377 logger.log(level,
1378 'poll %.3f ms took %.3f ms: %s events',
1379 timeout * 1e3, dt * 1e3, nevent)
1380 elif dt >= 1.0:
1381 logger.log(level,
1382 'poll %.3f ms took %.3f ms: timeout',
1383 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001384 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001385 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001386 self._process_events(event_list)
1387
1388 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001389 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001390 while self._scheduled:
1391 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001392 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001393 break
1394 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001395 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001396 self._ready.append(handle)
1397
1398 # This is the only place where callbacks are actually *called*.
1399 # All other places just add them to ready.
1400 # Note: We run all currently scheduled callbacks, but not any
1401 # callbacks scheduled by callbacks run this time around --
1402 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001403 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001404 ntodo = len(self._ready)
1405 for i in range(ntodo):
1406 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001407 if handle._cancelled:
1408 continue
1409 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001410 try:
1411 self._current_handle = handle
1412 t0 = self.time()
1413 handle._run()
1414 dt = self.time() - t0
1415 if dt >= self.slow_callback_duration:
1416 logger.warning('Executing %s took %.3f seconds',
1417 _format_handle(handle), dt)
1418 finally:
1419 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001420 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001421 handle._run()
1422 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001423
Yury Selivanove8944cb2015-05-12 11:43:04 -04001424 def _set_coroutine_wrapper(self, enabled):
1425 try:
1426 set_wrapper = sys.set_coroutine_wrapper
1427 get_wrapper = sys.get_coroutine_wrapper
1428 except AttributeError:
1429 return
1430
1431 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001432 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001433 return
1434
1435 wrapper = coroutines.debug_wrapper
1436 current_wrapper = get_wrapper()
1437
1438 if enabled:
1439 if current_wrapper not in (None, wrapper):
1440 warnings.warn(
1441 "loop.set_debug(True): cannot set debug coroutine "
1442 "wrapper; another wrapper is already set %r" %
1443 current_wrapper, RuntimeWarning)
1444 else:
1445 set_wrapper(wrapper)
1446 self._coroutine_wrapper_set = True
1447 else:
1448 if current_wrapper not in (None, wrapper):
1449 warnings.warn(
1450 "loop.set_debug(False): cannot unset debug coroutine "
1451 "wrapper; another wrapper was set %r" %
1452 current_wrapper, RuntimeWarning)
1453 else:
1454 set_wrapper(None)
1455 self._coroutine_wrapper_set = False
1456
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001457 def get_debug(self):
1458 return self._debug
1459
1460 def set_debug(self, enabled):
1461 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001462
Yury Selivanove8944cb2015-05-12 11:43:04 -04001463 if self.is_running():
1464 self._set_coroutine_wrapper(enabled)