Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1 | """Base implementation of event loop. |
| 2 | |
| 3 | The event loop can be broken up into a multiplexer (the part |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 4 | responsible for notifying us of I/O events) and the event loop proper, |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 5 | which wraps a multiplexer with functionality for scheduling callbacks, |
| 6 | immediately or at a given time in the future. |
| 7 | |
| 8 | Whenever a public API takes a callback, subsequent positional |
| 9 | arguments will be passed to the callback if/when it is called. This |
| 10 | avoids the proliferation of trivial lambdas implementing closures. |
| 11 | Keyword arguments for the callback are not supported; this is a |
| 12 | conscious design decision, leaving the door open for keyword arguments |
| 13 | to modify the meaning of the API call itself. |
| 14 | """ |
| 15 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 16 | import collections |
| 17 | import concurrent.futures |
| 18 | import heapq |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 19 | import inspect |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 20 | import itertools |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 21 | import logging |
Victor Stinner | b75380f | 2014-06-30 14:39:11 +0200 | [diff] [blame] | 22 | import os |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 23 | import socket |
| 24 | import subprocess |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 25 | import threading |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 26 | import time |
Victor Stinner | b75380f | 2014-06-30 14:39:11 +0200 | [diff] [blame] | 27 | import traceback |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 28 | import sys |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 29 | import warnings |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 30 | import weakref |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 31 | |
Yury Selivanov | 2a8911c | 2015-08-04 15:56:33 -0400 | [diff] [blame] | 32 | from . import compat |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 33 | from . import coroutines |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 34 | from . import events |
| 35 | from . import futures |
| 36 | from . import tasks |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 37 | from .coroutines import coroutine |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 38 | from .log import logger |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 39 | |
| 40 | |
Victor Stinner | 8c1a4a2 | 2015-01-06 01:03:58 +0100 | [diff] [blame] | 41 | __all__ = ['BaseEventLoop'] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 42 | |
| 43 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 44 | # 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 51 | |
Victor Stinner | c94a93a | 2016-04-01 21:43:39 +0200 | [diff] [blame] | 52 | # 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 Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 58 | def _format_handle(handle): |
| 59 | cb = handle._callback |
| 60 | if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task): |
| 61 | # format the task |
| 62 | return repr(cb.__self__) |
| 63 | else: |
| 64 | return str(handle) |
| 65 | |
| 66 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 67 | def _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 Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 76 | def _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 Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 87 | def _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 | |
| 94 | def _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 Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 101 | def _ipaddr_info(host, port, family, type, proto): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 102 | # 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 Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 109 | return None |
| 110 | |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 111 | if type == socket.SOCK_STREAM: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 112 | # 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 Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 117 | proto = socket.IPPROTO_TCP |
| 118 | elif type == socket.SOCK_DGRAM: |
| 119 | proto = socket.IPPROTO_UDP |
| 120 | else: |
| 121 | return None |
| 122 | |
Yury Selivanov | a714616 | 2016-06-02 16:51:07 -0400 | [diff] [blame] | 123 | if port is None: |
Yury Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 124 | port = 0 |
Guido van Rossum | e3c65a7 | 2016-09-30 08:17:15 -0700 | [diff] [blame] | 125 | 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 Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 135 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 136 | if family == socket.AF_UNSPEC: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 137 | afs = [socket.AF_INET] |
| 138 | if hasattr(socket, 'AF_INET6'): |
| 139 | afs.append(socket.AF_INET6) |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 140 | else: |
| 141 | afs = [family] |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 142 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 143 | 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 Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 148 | return None |
| 149 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 150 | for af in afs: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 151 | try: |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 152 | 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 Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 157 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 158 | # "host" is not an IP address. |
| 159 | return None |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 160 | |
| 161 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 162 | def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0, |
| 163 | flags=0, loop): |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 164 | host, port = address[:2] |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 165 | 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 Stinner | 1b0580b | 2014-02-13 09:24:37 +0100 | [diff] [blame] | 174 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 175 | |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 176 | def _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 Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 183 | fut._loop.stop() |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 184 | |
| 185 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 186 | class Server(events.AbstractServer): |
| 187 | |
| 188 | def __init__(self, loop, sockets): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 189 | self._loop = loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 190 | self.sockets = sockets |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 191 | self._active_count = 0 |
| 192 | self._waiters = [] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 193 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 194 | def __repr__(self): |
| 195 | return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets) |
| 196 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 197 | def _attach(self): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 198 | assert self.sockets is not None |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 199 | self._active_count += 1 |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 200 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 201 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 205 | self._wakeup() |
| 206 | |
| 207 | def close(self): |
| 208 | sockets = self.sockets |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 209 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 216 | |
| 217 | def _wakeup(self): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 218 | waiters = self._waiters |
| 219 | self._waiters = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 220 | for waiter in waiters: |
| 221 | if not waiter.done(): |
| 222 | waiter.set_result(waiter) |
| 223 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 224 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 225 | def wait_closed(self): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 226 | if self.sockets is None or self._waiters is None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 227 | return |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 228 | waiter = self._loop.create_future() |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 229 | self._waiters.append(waiter) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 230 | yield from waiter |
| 231 | |
| 232 | |
| 233 | class BaseEventLoop(events.AbstractEventLoop): |
| 234 | |
| 235 | def __init__(self): |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 236 | self._timer_cancelled_count = 0 |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 237 | self._closed = False |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 238 | self._stopping = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 239 | self._ready = collections.deque() |
| 240 | self._scheduled = [] |
| 241 | self._default_executor = None |
| 242 | self._internal_fds = 0 |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 243 | # Identifier of the thread running the event loop, or None if the |
| 244 | # event loop is not running |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 245 | self._thread_id = None |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 246 | self._clock_resolution = time.get_clock_info('monotonic').resolution |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 247 | self._exception_handler = None |
Yury Selivanov | 1af2bf7 | 2015-05-11 22:27:25 -0400 | [diff] [blame] | 248 | self.set_debug((not sys.flags.ignore_environment |
| 249 | and bool(os.environ.get('PYTHONASYNCIODEBUG')))) |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 250 | # 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 Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 253 | self._current_handle = None |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 254 | self._task_factory = None |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 255 | self._coroutine_wrapper_set = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 256 | |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 257 | 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 |
| 264 | |
| 265 | # Set to True when `loop.shutdown_asyncgens` is called. |
| 266 | self._asyncgens_shutdown_called = False |
| 267 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 268 | 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 Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 273 | def create_future(self): |
| 274 | """Create a Future object attached to the loop.""" |
| 275 | return futures.Future(loop=self) |
| 276 | |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 277 | def create_task(self, coro): |
| 278 | """Schedule a coroutine object. |
| 279 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 280 | Return a task object. |
| 281 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 282 | self._check_closed() |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 283 | 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 Stinner | c39ba7d | 2014-07-11 00:21:27 +0200 | [diff] [blame] | 289 | return task |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 290 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 291 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 309 | def _make_socket_transport(self, sock, protocol, waiter=None, *, |
| 310 | extra=None, server=None): |
| 311 | """Create socket transport.""" |
| 312 | raise NotImplementedError |
| 313 | |
Victor Stinner | 15cc678 | 2015-01-09 00:09:10 +0100 | [diff] [blame] | 314 | def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None, |
| 315 | *, server_side=False, server_hostname=None, |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 316 | extra=None, server=None): |
| 317 | """Create SSL transport.""" |
| 318 | raise NotImplementedError |
| 319 | |
| 320 | def _make_datagram_transport(self, sock, protocol, |
Victor Stinner | bfff45d | 2014-07-08 23:57:31 +0200 | [diff] [blame] | 321 | address=None, waiter=None, extra=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 322 | """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 Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 335 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 336 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 342 | def _write_to_self(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 343 | """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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 349 | raise NotImplementedError |
| 350 | |
| 351 | def _process_events(self, event_list): |
| 352 | """Process selector events.""" |
| 353 | raise NotImplementedError |
| 354 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 355 | def _check_closed(self): |
| 356 | if self._closed: |
| 357 | raise RuntimeError('Event loop is closed') |
| 358 | |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 359 | def _asyncgen_finalizer_hook(self, agen): |
| 360 | self._asyncgens.discard(agen) |
| 361 | if not self.is_closed(): |
| 362 | self.create_task(agen.aclose()) |
Yury Selivanov | c542049 | 2016-11-03 15:35:23 -0700 | [diff] [blame] | 363 | # Wake up the loop if the finalizer was called from |
| 364 | # a different thread. |
| 365 | self._write_to_self() |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 366 | |
| 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 | |
| 381 | 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. |
| 384 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 404 | def run_forever(self): |
| 405 | """Run until stop() is called.""" |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 406 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 407 | if self.is_running(): |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 408 | 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 Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 412 | self._set_coroutine_wrapper(self._debug) |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 413 | self._thread_id = threading.get_ident() |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 414 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 418 | try: |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 419 | events._set_running_loop(self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 420 | while True: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 421 | self._run_once() |
| 422 | if self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 423 | break |
| 424 | finally: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 425 | self._stopping = False |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 426 | self._thread_id = None |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 427 | events._set_running_loop(None) |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 428 | self._set_coroutine_wrapper(False) |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 429 | if self._asyncgens is not None: |
| 430 | sys.set_asyncgen_hooks(*old_agen_hooks) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 431 | |
| 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 Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 437 | WARNING: It would be disastrous to call run_until_complete() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 438 | 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 Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 443 | self._check_closed() |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 444 | |
Guido van Rossum | 7b3b3dc | 2016-09-09 14:26:31 -0700 | [diff] [blame] | 445 | new_task = not futures.isfuture(future) |
Yury Selivanov | 59eb9a4 | 2015-05-11 14:48:38 -0400 | [diff] [blame] | 446 | future = tasks.ensure_future(future, loop=self) |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 447 | 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 Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 452 | future.add_done_callback(_run_until_complete_cb) |
Victor Stinner | c8bd53f | 2014-10-11 14:30:18 +0200 | [diff] [blame] | 453 | 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 |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 462 | future.remove_done_callback(_run_until_complete_cb) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 463 | if not future.done(): |
| 464 | raise RuntimeError('Event loop stopped before Future completed.') |
| 465 | |
| 466 | return future.result() |
| 467 | |
| 468 | def stop(self): |
| 469 | """Stop running the event loop. |
| 470 | |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 471 | Every callback already scheduled will still run. This simply informs |
| 472 | run_forever to stop looping after a complete iteration. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 473 | """ |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 474 | self._stopping = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 475 | |
Antoine Pitrou | 4ca7355 | 2013-10-20 00:54:10 +0200 | [diff] [blame] | 476 | def close(self): |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 477 | """Close the event loop. |
| 478 | |
| 479 | This clears the queues and shuts down the executor, |
| 480 | but does not wait for the executor to finish. |
Victor Stinner | f328c7d | 2014-06-23 01:02:37 +0200 | [diff] [blame] | 481 | |
| 482 | The event loop must not be running. |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 483 | """ |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 484 | if self.is_running(): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 485 | raise RuntimeError("Cannot close a running event loop") |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 486 | if self._closed: |
| 487 | return |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 488 | if self._debug: |
| 489 | logger.debug("Close %r", self) |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 490 | self._closed = True |
| 491 | self._ready.clear() |
| 492 | self._scheduled.clear() |
| 493 | executor = self._default_executor |
| 494 | if executor is not None: |
| 495 | self._default_executor = None |
| 496 | executor.shutdown(wait=False) |
Antoine Pitrou | 4ca7355 | 2013-10-20 00:54:10 +0200 | [diff] [blame] | 497 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 498 | def is_closed(self): |
| 499 | """Returns True if the event loop was closed.""" |
| 500 | return self._closed |
| 501 | |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 502 | # On Python 3.3 and older, objects with a destructor part of a reference |
| 503 | # cycle are never destroyed. It's not more the case on Python 3.4 thanks |
| 504 | # to the PEP 442. |
Yury Selivanov | 2a8911c | 2015-08-04 15:56:33 -0400 | [diff] [blame] | 505 | if compat.PY34: |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 506 | def __del__(self): |
| 507 | if not self.is_closed(): |
| 508 | warnings.warn("unclosed event loop %r" % self, ResourceWarning) |
| 509 | if not self.is_running(): |
| 510 | self.close() |
| 511 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 512 | def is_running(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 513 | """Returns True if the event loop is running.""" |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 514 | return (self._thread_id is not None) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 515 | |
| 516 | def time(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 517 | """Return the time according to the event loop's clock. |
| 518 | |
| 519 | This is a float expressed in seconds since an epoch, but the |
| 520 | epoch, precision, accuracy and drift are unspecified and may |
| 521 | differ per event loop. |
| 522 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 523 | return time.monotonic() |
| 524 | |
| 525 | def call_later(self, delay, callback, *args): |
| 526 | """Arrange for a callback to be called at a given time. |
| 527 | |
| 528 | Return a Handle: an opaque object with a cancel() method that |
| 529 | can be used to cancel the call. |
| 530 | |
| 531 | The delay can be an int or float, expressed in seconds. It is |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 532 | always relative to the current time. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 533 | |
| 534 | Each callback will be called exactly once. If two callbacks |
| 535 | are scheduled for exactly the same time, it undefined which |
| 536 | will be called first. |
| 537 | |
| 538 | Any positional arguments after the callback will be passed to |
| 539 | the callback when it is called. |
| 540 | """ |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 541 | timer = self.call_at(self.time() + delay, callback, *args) |
| 542 | if timer._source_traceback: |
| 543 | del timer._source_traceback[-1] |
| 544 | return timer |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 545 | |
| 546 | def call_at(self, when, callback, *args): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 547 | """Like call_later(), but uses an absolute time. |
| 548 | |
| 549 | Absolute time corresponds to the event loop's time() method. |
| 550 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 551 | self._check_closed() |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 552 | if self._debug: |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 553 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 554 | self._check_callback(callback, 'call_at') |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 555 | timer = events.TimerHandle(when, callback, args, self) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 556 | if timer._source_traceback: |
| 557 | del timer._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 558 | heapq.heappush(self._scheduled, timer) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 559 | timer._scheduled = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 560 | return timer |
| 561 | |
| 562 | def call_soon(self, callback, *args): |
| 563 | """Arrange for a callback to be called as soon as possible. |
| 564 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 565 | This operates as a FIFO queue: callbacks are called in the |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 566 | order in which they are registered. Each callback will be |
| 567 | called exactly once. |
| 568 | |
| 569 | Any positional arguments after the callback will be passed to |
| 570 | the callback when it is called. |
| 571 | """ |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 572 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 573 | if self._debug: |
| 574 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 575 | self._check_callback(callback, 'call_soon') |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 576 | handle = self._call_soon(callback, args) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 577 | if handle._source_traceback: |
| 578 | del handle._source_traceback[-1] |
| 579 | return handle |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 580 | |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 581 | def _check_callback(self, callback, method): |
| 582 | if (coroutines.iscoroutine(callback) or |
| 583 | coroutines.iscoroutinefunction(callback)): |
| 584 | raise TypeError( |
| 585 | "coroutines cannot be used with {}()".format(method)) |
| 586 | if not callable(callback): |
| 587 | raise TypeError( |
| 588 | 'a callable object was expected by {}(), got {!r}'.format( |
| 589 | method, callback)) |
| 590 | |
| 591 | |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 592 | def _call_soon(self, callback, args): |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 593 | handle = events.Handle(callback, args, self) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 594 | if handle._source_traceback: |
| 595 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 596 | self._ready.append(handle) |
| 597 | return handle |
| 598 | |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 599 | def _check_thread(self): |
| 600 | """Check that the current thread is the thread running the event loop. |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 601 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 602 | Non-thread-safe methods of this class make this assumption and will |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 603 | likely behave incorrectly when the assumption is violated. |
| 604 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 605 | Should only be called when (self._debug == True). The caller is |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 606 | responsible for checking this condition for performance reasons. |
| 607 | """ |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 608 | if self._thread_id is None: |
Victor Stinner | 751c7c0 | 2014-06-23 15:14:13 +0200 | [diff] [blame] | 609 | return |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 610 | thread_id = threading.get_ident() |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 611 | if thread_id != self._thread_id: |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 612 | raise RuntimeError( |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 613 | "Non-thread-safe operation invoked on an event loop other " |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 614 | "than the current one") |
| 615 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 616 | def call_soon_threadsafe(self, callback, *args): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 617 | """Like call_soon(), but thread-safe.""" |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 618 | self._check_closed() |
| 619 | if self._debug: |
| 620 | self._check_callback(callback, 'call_soon_threadsafe') |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 621 | handle = self._call_soon(callback, args) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 622 | if handle._source_traceback: |
| 623 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 624 | self._write_to_self() |
| 625 | return handle |
| 626 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 627 | def run_in_executor(self, executor, func, *args): |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 628 | self._check_closed() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 629 | if self._debug: |
| 630 | self._check_callback(func, 'run_in_executor') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 631 | if executor is None: |
| 632 | executor = self._default_executor |
| 633 | if executor is None: |
Yury Selivanov | e8a6045 | 2016-10-21 17:40:42 -0400 | [diff] [blame] | 634 | executor = concurrent.futures.ThreadPoolExecutor() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 635 | self._default_executor = executor |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 636 | return futures.wrap_future(executor.submit(func, *args), loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 637 | |
| 638 | def set_default_executor(self, executor): |
| 639 | self._default_executor = executor |
| 640 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 641 | def _getaddrinfo_debug(self, host, port, family, type, proto, flags): |
| 642 | msg = ["%s:%r" % (host, port)] |
| 643 | if family: |
| 644 | msg.append('family=%r' % family) |
| 645 | if type: |
| 646 | msg.append('type=%r' % type) |
| 647 | if proto: |
| 648 | msg.append('proto=%r' % proto) |
| 649 | if flags: |
| 650 | msg.append('flags=%r' % flags) |
| 651 | msg = ', '.join(msg) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 652 | logger.debug('Get address info %s', msg) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 653 | |
| 654 | t0 = self.time() |
| 655 | addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags) |
| 656 | dt = self.time() - t0 |
| 657 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 658 | msg = ('Getting address info %s took %.3f ms: %r' |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 659 | % (msg, dt * 1e3, addrinfo)) |
| 660 | if dt >= self.slow_callback_duration: |
| 661 | logger.info(msg) |
| 662 | else: |
| 663 | logger.debug(msg) |
| 664 | return addrinfo |
| 665 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 666 | def getaddrinfo(self, host, port, *, |
| 667 | family=0, type=0, proto=0, flags=0): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 668 | if self._debug: |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 669 | return self.run_in_executor(None, self._getaddrinfo_debug, |
| 670 | host, port, family, type, proto, flags) |
| 671 | else: |
| 672 | return self.run_in_executor(None, socket.getaddrinfo, |
| 673 | host, port, family, type, proto, flags) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 674 | |
| 675 | def getnameinfo(self, sockaddr, flags=0): |
| 676 | return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags) |
| 677 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 678 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 679 | def create_connection(self, protocol_factory, host=None, port=None, *, |
| 680 | ssl=None, family=0, proto=0, flags=0, sock=None, |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 681 | local_addr=None, server_hostname=None): |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 682 | """Connect to a TCP server. |
| 683 | |
| 684 | Create a streaming transport connection to a given Internet host and |
| 685 | port: socket family AF_INET or socket.AF_INET6 depending on host (or |
| 686 | family if specified), socket type SOCK_STREAM. protocol_factory must be |
| 687 | a callable returning a protocol instance. |
| 688 | |
| 689 | This method is a coroutine which will try to establish the connection |
| 690 | in the background. When successful, the coroutine returns a |
| 691 | (transport, protocol) pair. |
| 692 | """ |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 693 | if server_hostname is not None and not ssl: |
| 694 | raise ValueError('server_hostname is only meaningful with ssl') |
| 695 | |
| 696 | if server_hostname is None and ssl: |
| 697 | # Use host as default for server_hostname. It is an error |
| 698 | # if host is empty or not set, e.g. when an |
| 699 | # already-connected socket was passed or when only a port |
| 700 | # is given. To avoid this error, you can pass |
| 701 | # server_hostname='' -- this will bypass the hostname |
| 702 | # check. (This also means that if host is a numeric |
| 703 | # IP/IPv6 address, we will attempt to verify that exact |
| 704 | # address; this will probably fail, but it is possible to |
| 705 | # create a certificate for a specific IP address, so we |
| 706 | # don't judge it here.) |
| 707 | if not host: |
| 708 | raise ValueError('You must set server_hostname ' |
| 709 | 'when using ssl without a host') |
| 710 | server_hostname = host |
Guido van Rossum | a8d630a | 2013-11-01 14:20:55 -0700 | [diff] [blame] | 711 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 712 | if host is not None or port is not None: |
| 713 | if sock is not None: |
| 714 | raise ValueError( |
| 715 | 'host/port and sock can not be specified at the same time') |
| 716 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 717 | f1 = _ensure_resolved((host, port), family=family, |
| 718 | type=socket.SOCK_STREAM, proto=proto, |
| 719 | flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 720 | fs = [f1] |
| 721 | if local_addr is not None: |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 722 | f2 = _ensure_resolved(local_addr, family=family, |
| 723 | type=socket.SOCK_STREAM, proto=proto, |
| 724 | flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 725 | fs.append(f2) |
| 726 | else: |
| 727 | f2 = None |
| 728 | |
| 729 | yield from tasks.wait(fs, loop=self) |
| 730 | |
| 731 | infos = f1.result() |
| 732 | if not infos: |
| 733 | raise OSError('getaddrinfo() returned empty list') |
| 734 | if f2 is not None: |
| 735 | laddr_infos = f2.result() |
| 736 | if not laddr_infos: |
| 737 | raise OSError('getaddrinfo() returned empty list') |
| 738 | |
| 739 | exceptions = [] |
| 740 | for family, type, proto, cname, address in infos: |
| 741 | try: |
| 742 | sock = socket.socket(family=family, type=type, proto=proto) |
| 743 | sock.setblocking(False) |
| 744 | if f2 is not None: |
| 745 | for _, _, _, _, laddr in laddr_infos: |
| 746 | try: |
| 747 | sock.bind(laddr) |
| 748 | break |
| 749 | except OSError as exc: |
| 750 | exc = OSError( |
| 751 | exc.errno, 'error while ' |
| 752 | 'attempting to bind on address ' |
| 753 | '{!r}: {}'.format( |
| 754 | laddr, exc.strerror.lower())) |
| 755 | exceptions.append(exc) |
| 756 | else: |
| 757 | sock.close() |
| 758 | sock = None |
| 759 | continue |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 760 | if self._debug: |
| 761 | logger.debug("connect %r to %r", sock, address) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 762 | yield from self.sock_connect(sock, address) |
| 763 | except OSError as exc: |
| 764 | if sock is not None: |
| 765 | sock.close() |
| 766 | exceptions.append(exc) |
Victor Stinner | 223a624 | 2014-06-04 00:11:52 +0200 | [diff] [blame] | 767 | except: |
| 768 | if sock is not None: |
| 769 | sock.close() |
| 770 | raise |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 771 | else: |
| 772 | break |
| 773 | else: |
| 774 | if len(exceptions) == 1: |
| 775 | raise exceptions[0] |
| 776 | else: |
| 777 | # If they all have the same str(), raise one. |
| 778 | model = str(exceptions[0]) |
| 779 | if all(str(exc) == model for exc in exceptions): |
| 780 | raise exceptions[0] |
| 781 | # Raise a combined exception so the user can see all |
| 782 | # the various error messages. |
| 783 | raise OSError('Multiple exceptions: {}'.format( |
| 784 | ', '.join(str(exc) for exc in exceptions))) |
| 785 | |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 786 | else: |
| 787 | if sock is None: |
| 788 | raise ValueError( |
| 789 | 'host and port was not specified and no sock specified') |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 790 | if not _is_stream_socket(sock): |
| 791 | # We allow AF_INET, AF_INET6, AF_UNIX as long as they |
| 792 | # are SOCK_STREAM. |
| 793 | # We support passing AF_UNIX sockets even though we have |
| 794 | # a dedicated API for that: create_unix_connection. |
| 795 | # Disallowing AF_UNIX in this method, breaks backwards |
| 796 | # compatibility. |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 797 | raise ValueError( |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 798 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 799 | |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 800 | transport, protocol = yield from self._create_connection_transport( |
| 801 | sock, protocol_factory, ssl, server_hostname) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 802 | if self._debug: |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 803 | # Get the socket from the transport because SSL transport closes |
| 804 | # the old socket and creates a new SSL socket |
| 805 | sock = transport.get_extra_info('socket') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 806 | logger.debug("%r connected to %s:%r: (%r, %r)", |
| 807 | sock, host, port, transport, protocol) |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 808 | return transport, protocol |
| 809 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 810 | @coroutine |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 811 | def _create_connection_transport(self, sock, protocol_factory, ssl, |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 812 | server_hostname, server_side=False): |
| 813 | |
| 814 | sock.setblocking(False) |
| 815 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 816 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 817 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 818 | if ssl: |
| 819 | sslcontext = None if isinstance(ssl, bool) else ssl |
| 820 | transport = self._make_ssl_transport( |
| 821 | sock, protocol, sslcontext, waiter, |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 822 | server_side=server_side, server_hostname=server_hostname) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 823 | else: |
| 824 | transport = self._make_socket_transport(sock, protocol, waiter) |
| 825 | |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 826 | try: |
| 827 | yield from waiter |
Victor Stinner | 0c2e408 | 2015-01-22 00:17:41 +0100 | [diff] [blame] | 828 | except: |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 829 | transport.close() |
| 830 | raise |
| 831 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 832 | return transport, protocol |
| 833 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 834 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 835 | def create_datagram_endpoint(self, protocol_factory, |
| 836 | local_addr=None, remote_addr=None, *, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 837 | family=0, proto=0, flags=0, |
| 838 | reuse_address=None, reuse_port=None, |
| 839 | allow_broadcast=None, sock=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 840 | """Create datagram connection.""" |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 841 | if sock is not None: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 842 | if not _is_dgram_socket(sock): |
| 843 | raise ValueError( |
| 844 | 'A UDP Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 845 | if (local_addr or remote_addr or |
| 846 | family or proto or flags or |
| 847 | reuse_address or reuse_port or allow_broadcast): |
| 848 | # show the problematic kwargs in exception msg |
| 849 | opts = dict(local_addr=local_addr, remote_addr=remote_addr, |
| 850 | family=family, proto=proto, flags=flags, |
| 851 | reuse_address=reuse_address, reuse_port=reuse_port, |
| 852 | allow_broadcast=allow_broadcast) |
| 853 | problems = ', '.join( |
| 854 | '{}={}'.format(k, v) for k, v in opts.items() if v) |
| 855 | raise ValueError( |
| 856 | 'socket modifier keyword arguments can not be used ' |
| 857 | 'when sock is specified. ({})'.format(problems)) |
| 858 | sock.setblocking(False) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 859 | r_addr = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 860 | else: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 861 | if not (local_addr or remote_addr): |
| 862 | if family == 0: |
| 863 | raise ValueError('unexpected address family') |
| 864 | addr_pairs_info = (((family, proto), (None, None)),) |
| 865 | else: |
| 866 | # join address by (family, protocol) |
| 867 | addr_infos = collections.OrderedDict() |
| 868 | for idx, addr in ((0, local_addr), (1, remote_addr)): |
| 869 | if addr is not None: |
| 870 | assert isinstance(addr, tuple) and len(addr) == 2, ( |
| 871 | '2-tuple is expected') |
| 872 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 873 | infos = yield from _ensure_resolved( |
| 874 | addr, family=family, type=socket.SOCK_DGRAM, |
| 875 | proto=proto, flags=flags, loop=self) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 876 | if not infos: |
| 877 | raise OSError('getaddrinfo() returned empty list') |
| 878 | |
| 879 | for fam, _, pro, _, address in infos: |
| 880 | key = (fam, pro) |
| 881 | if key not in addr_infos: |
| 882 | addr_infos[key] = [None, None] |
| 883 | addr_infos[key][idx] = address |
| 884 | |
| 885 | # each addr has to have info for each (family, proto) pair |
| 886 | addr_pairs_info = [ |
| 887 | (key, addr_pair) for key, addr_pair in addr_infos.items() |
| 888 | if not ((local_addr and addr_pair[0] is None) or |
| 889 | (remote_addr and addr_pair[1] is None))] |
| 890 | |
| 891 | if not addr_pairs_info: |
| 892 | raise ValueError('can not get address information') |
| 893 | |
| 894 | exceptions = [] |
| 895 | |
| 896 | if reuse_address is None: |
| 897 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 898 | |
| 899 | for ((family, proto), |
| 900 | (local_address, remote_address)) in addr_pairs_info: |
| 901 | sock = None |
| 902 | r_addr = None |
| 903 | try: |
| 904 | sock = socket.socket( |
| 905 | family=family, type=socket.SOCK_DGRAM, proto=proto) |
| 906 | if reuse_address: |
| 907 | sock.setsockopt( |
| 908 | socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 909 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 910 | _set_reuseport(sock) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 911 | if allow_broadcast: |
| 912 | sock.setsockopt( |
| 913 | socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 914 | sock.setblocking(False) |
| 915 | |
| 916 | if local_addr: |
| 917 | sock.bind(local_address) |
| 918 | if remote_addr: |
| 919 | yield from self.sock_connect(sock, remote_address) |
| 920 | r_addr = remote_address |
| 921 | except OSError as exc: |
| 922 | if sock is not None: |
| 923 | sock.close() |
| 924 | exceptions.append(exc) |
| 925 | except: |
| 926 | if sock is not None: |
| 927 | sock.close() |
| 928 | raise |
| 929 | else: |
| 930 | break |
| 931 | else: |
| 932 | raise exceptions[0] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 933 | |
| 934 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 935 | waiter = self.create_future() |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 936 | transport = self._make_datagram_transport( |
| 937 | sock, protocol, r_addr, waiter) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 938 | if self._debug: |
| 939 | if local_addr: |
| 940 | logger.info("Datagram endpoint local_addr=%r remote_addr=%r " |
| 941 | "created: (%r, %r)", |
| 942 | local_addr, remote_addr, transport, protocol) |
| 943 | else: |
| 944 | logger.debug("Datagram endpoint remote_addr=%r created: " |
| 945 | "(%r, %r)", |
| 946 | remote_addr, transport, protocol) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 947 | |
| 948 | try: |
| 949 | yield from waiter |
| 950 | except: |
| 951 | transport.close() |
| 952 | raise |
| 953 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 954 | return transport, protocol |
| 955 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 956 | @coroutine |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 957 | def _create_server_getaddrinfo(self, host, port, family, flags): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 958 | infos = yield from _ensure_resolved((host, port), family=family, |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 959 | type=socket.SOCK_STREAM, |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 960 | flags=flags, loop=self) |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 961 | if not infos: |
| 962 | raise OSError('getaddrinfo({!r}) returned empty list'.format(host)) |
| 963 | return infos |
| 964 | |
| 965 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 966 | def create_server(self, protocol_factory, host=None, port=None, |
| 967 | *, |
| 968 | family=socket.AF_UNSPEC, |
| 969 | flags=socket.AI_PASSIVE, |
| 970 | sock=None, |
| 971 | backlog=100, |
| 972 | ssl=None, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 973 | reuse_address=None, |
| 974 | reuse_port=None): |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 975 | """Create a TCP server. |
| 976 | |
| 977 | The host parameter can be a string, in that case the TCP server is bound |
| 978 | to host and port. |
| 979 | |
| 980 | The host parameter can also be a sequence of strings and in that case |
Yury Selivanov | e076ffb | 2016-03-02 11:17:01 -0500 | [diff] [blame] | 981 | the TCP server is bound to all hosts of the sequence. If a host |
| 982 | appears multiple times (possibly indirectly e.g. when hostnames |
| 983 | resolve to the same IP address), the server is only bound once to that |
| 984 | host. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 985 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 986 | Return a Server object which can be used to stop the service. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 987 | |
| 988 | This method is a coroutine. |
| 989 | """ |
Guido van Rossum | 28dff0d | 2013-11-01 14:22:30 -0700 | [diff] [blame] | 990 | if isinstance(ssl, bool): |
| 991 | raise TypeError('ssl argument must be an SSLContext or None') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 992 | if host is not None or port is not None: |
| 993 | if sock is not None: |
| 994 | raise ValueError( |
| 995 | 'host/port and sock can not be specified at the same time') |
| 996 | |
| 997 | AF_INET6 = getattr(socket, 'AF_INET6', 0) |
| 998 | if reuse_address is None: |
| 999 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 1000 | sockets = [] |
| 1001 | if host == '': |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1002 | hosts = [None] |
| 1003 | elif (isinstance(host, str) or |
| 1004 | not isinstance(host, collections.Iterable)): |
| 1005 | hosts = [host] |
| 1006 | else: |
| 1007 | hosts = host |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1008 | |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1009 | fs = [self._create_server_getaddrinfo(host, port, family=family, |
| 1010 | flags=flags) |
| 1011 | for host in hosts] |
| 1012 | infos = yield from tasks.gather(*fs, loop=self) |
Yury Selivanov | e076ffb | 2016-03-02 11:17:01 -0500 | [diff] [blame] | 1013 | infos = set(itertools.chain.from_iterable(infos)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1014 | |
| 1015 | completed = False |
| 1016 | try: |
| 1017 | for res in infos: |
| 1018 | af, socktype, proto, canonname, sa = res |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1019 | try: |
| 1020 | sock = socket.socket(af, socktype, proto) |
| 1021 | except socket.error: |
| 1022 | # Assume it's a bad family/type/protocol combination. |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 1023 | if self._debug: |
| 1024 | logger.warning('create_server() failed to create ' |
| 1025 | 'socket.socket(%r, %r, %r)', |
| 1026 | af, socktype, proto, exc_info=True) |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1027 | continue |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1028 | sockets.append(sock) |
| 1029 | if reuse_address: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1030 | sock.setsockopt( |
| 1031 | socket.SOL_SOCKET, socket.SO_REUSEADDR, True) |
| 1032 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 1033 | _set_reuseport(sock) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1034 | # Disable IPv4/IPv6 dual stack support (enabled by |
| 1035 | # default on Linux) which makes a single socket |
| 1036 | # listen on both address families. |
| 1037 | if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'): |
| 1038 | sock.setsockopt(socket.IPPROTO_IPV6, |
| 1039 | socket.IPV6_V6ONLY, |
| 1040 | True) |
| 1041 | try: |
| 1042 | sock.bind(sa) |
| 1043 | except OSError as err: |
| 1044 | raise OSError(err.errno, 'error while attempting ' |
| 1045 | 'to bind on address %r: %s' |
| 1046 | % (sa, err.strerror.lower())) |
| 1047 | completed = True |
| 1048 | finally: |
| 1049 | if not completed: |
| 1050 | for sock in sockets: |
| 1051 | sock.close() |
| 1052 | else: |
| 1053 | if sock is None: |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1054 | raise ValueError('Neither host/port nor sock were specified') |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 1055 | if not _is_stream_socket(sock): |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1056 | raise ValueError( |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 1057 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1058 | sockets = [sock] |
| 1059 | |
| 1060 | server = Server(self, sockets) |
| 1061 | for sock in sockets: |
| 1062 | sock.listen(backlog) |
| 1063 | sock.setblocking(False) |
Yury Selivanov | a1b0e7d | 2016-09-15 14:13:15 -0400 | [diff] [blame] | 1064 | self._start_serving(protocol_factory, sock, ssl, server, backlog) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 1065 | if self._debug: |
| 1066 | logger.info("%r is serving", server) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1067 | return server |
| 1068 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1069 | @coroutine |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1070 | def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None): |
| 1071 | """Handle an accepted connection. |
| 1072 | |
| 1073 | This is used by servers that accept connections outside of |
| 1074 | asyncio but that use asyncio to handle connections. |
| 1075 | |
| 1076 | This method is a coroutine. When completed, the coroutine |
| 1077 | returns a (transport, protocol) pair. |
| 1078 | """ |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1079 | if not _is_stream_socket(sock): |
| 1080 | raise ValueError( |
| 1081 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
| 1082 | |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1083 | transport, protocol = yield from self._create_connection_transport( |
| 1084 | sock, protocol_factory, ssl, '', server_side=True) |
| 1085 | if self._debug: |
| 1086 | # Get the socket from the transport because SSL transport closes |
| 1087 | # the old socket and creates a new SSL socket |
| 1088 | sock = transport.get_extra_info('socket') |
| 1089 | logger.debug("%r handled: (%r, %r)", sock, transport, protocol) |
| 1090 | return transport, protocol |
| 1091 | |
| 1092 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1093 | def connect_read_pipe(self, protocol_factory, pipe): |
| 1094 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1095 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1096 | transport = self._make_read_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1097 | |
| 1098 | try: |
| 1099 | yield from waiter |
| 1100 | except: |
| 1101 | transport.close() |
| 1102 | raise |
| 1103 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1104 | if self._debug: |
| 1105 | logger.debug('Read pipe %r connected: (%r, %r)', |
| 1106 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1107 | return transport, protocol |
| 1108 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1109 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1110 | def connect_write_pipe(self, protocol_factory, pipe): |
| 1111 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1112 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1113 | transport = self._make_write_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1114 | |
| 1115 | try: |
| 1116 | yield from waiter |
| 1117 | except: |
| 1118 | transport.close() |
| 1119 | raise |
| 1120 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1121 | if self._debug: |
| 1122 | logger.debug('Write pipe %r connected: (%r, %r)', |
| 1123 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1124 | return transport, protocol |
| 1125 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1126 | def _log_subprocess(self, msg, stdin, stdout, stderr): |
| 1127 | info = [msg] |
| 1128 | if stdin is not None: |
| 1129 | info.append('stdin=%s' % _format_pipe(stdin)) |
| 1130 | if stdout is not None and stderr == subprocess.STDOUT: |
| 1131 | info.append('stdout=stderr=%s' % _format_pipe(stdout)) |
| 1132 | else: |
| 1133 | if stdout is not None: |
| 1134 | info.append('stdout=%s' % _format_pipe(stdout)) |
| 1135 | if stderr is not None: |
| 1136 | info.append('stderr=%s' % _format_pipe(stderr)) |
| 1137 | logger.debug(' '.join(info)) |
| 1138 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1139 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1140 | def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE, |
| 1141 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 1142 | universal_newlines=False, shell=True, bufsize=0, |
| 1143 | **kwargs): |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1144 | if not isinstance(cmd, (bytes, str)): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1145 | raise ValueError("cmd must be a string") |
| 1146 | if universal_newlines: |
| 1147 | raise ValueError("universal_newlines must be False") |
| 1148 | if not shell: |
Victor Stinner | 323748e | 2014-01-31 12:28:30 +0100 | [diff] [blame] | 1149 | raise ValueError("shell must be True") |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1150 | if bufsize != 0: |
| 1151 | raise ValueError("bufsize must be 0") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1152 | protocol = protocol_factory() |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1153 | if self._debug: |
| 1154 | # don't log parameters: they may contain sensitive information |
| 1155 | # (password) and may be too long |
| 1156 | debug_log = 'run shell command %r' % cmd |
| 1157 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1158 | transport = yield from self._make_subprocess_transport( |
| 1159 | protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1160 | if self._debug: |
Yury Selivanov | 4357cf6 | 2016-09-15 13:49:08 -0400 | [diff] [blame] | 1161 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1162 | return transport, protocol |
| 1163 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1164 | @coroutine |
Yury Selivanov | 5779752 | 2014-02-18 22:56:15 -0500 | [diff] [blame] | 1165 | def subprocess_exec(self, protocol_factory, program, *args, |
| 1166 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1167 | stderr=subprocess.PIPE, universal_newlines=False, |
| 1168 | shell=False, bufsize=0, **kwargs): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1169 | if universal_newlines: |
| 1170 | raise ValueError("universal_newlines must be False") |
| 1171 | if shell: |
| 1172 | raise ValueError("shell must be False") |
| 1173 | if bufsize != 0: |
| 1174 | raise ValueError("bufsize must be 0") |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1175 | popen_args = (program,) + args |
| 1176 | for arg in popen_args: |
| 1177 | if not isinstance(arg, (str, bytes)): |
| 1178 | raise TypeError("program arguments must be " |
| 1179 | "a bytes or text string, not %s" |
| 1180 | % type(arg).__name__) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1181 | protocol = protocol_factory() |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1182 | if self._debug: |
| 1183 | # don't log parameters: they may contain sensitive information |
| 1184 | # (password) and may be too long |
| 1185 | debug_log = 'execute program %r' % program |
| 1186 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1187 | transport = yield from self._make_subprocess_transport( |
Yury Selivanov | 5779752 | 2014-02-18 22:56:15 -0500 | [diff] [blame] | 1188 | protocol, popen_args, False, stdin, stdout, stderr, |
| 1189 | bufsize, **kwargs) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1190 | if self._debug: |
Yury Selivanov | 4357cf6 | 2016-09-15 13:49:08 -0400 | [diff] [blame] | 1191 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1192 | return transport, protocol |
| 1193 | |
Yury Selivanov | 7ed7ce6 | 2016-05-16 15:20:38 -0400 | [diff] [blame] | 1194 | def get_exception_handler(self): |
| 1195 | """Return an exception handler, or None if the default one is in use. |
| 1196 | """ |
| 1197 | return self._exception_handler |
| 1198 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1199 | def set_exception_handler(self, handler): |
| 1200 | """Set handler as the new event loop exception handler. |
| 1201 | |
| 1202 | If handler is None, the default exception handler will |
| 1203 | be set. |
| 1204 | |
| 1205 | If handler is a callable object, it should have a |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1206 | signature matching '(loop, context)', where 'loop' |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1207 | will be a reference to the active event loop, 'context' |
| 1208 | will be a dict object (see `call_exception_handler()` |
| 1209 | documentation for details about context). |
| 1210 | """ |
| 1211 | if handler is not None and not callable(handler): |
| 1212 | raise TypeError('A callable object or None is expected, ' |
| 1213 | 'got {!r}'.format(handler)) |
| 1214 | self._exception_handler = handler |
| 1215 | |
| 1216 | def default_exception_handler(self, context): |
| 1217 | """Default exception handler. |
| 1218 | |
| 1219 | This is called when an exception occurs and no exception |
| 1220 | handler is set, and can be called by a custom exception |
| 1221 | handler that wants to defer to the default behavior. |
| 1222 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1223 | The context parameter has the same meaning as in |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1224 | `call_exception_handler()`. |
| 1225 | """ |
| 1226 | message = context.get('message') |
| 1227 | if not message: |
| 1228 | message = 'Unhandled exception in event loop' |
| 1229 | |
| 1230 | exception = context.get('exception') |
| 1231 | if exception is not None: |
| 1232 | exc_info = (type(exception), exception, exception.__traceback__) |
| 1233 | else: |
| 1234 | exc_info = False |
| 1235 | |
Victor Stinner | ff018e4 | 2015-01-28 00:30:40 +0100 | [diff] [blame] | 1236 | if ('source_traceback' not in context |
| 1237 | and self._current_handle is not None |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1238 | and self._current_handle._source_traceback): |
| 1239 | context['handle_traceback'] = self._current_handle._source_traceback |
| 1240 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1241 | log_lines = [message] |
| 1242 | for key in sorted(context): |
| 1243 | if key in {'message', 'exception'}: |
| 1244 | continue |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1245 | value = context[key] |
| 1246 | if key == 'source_traceback': |
| 1247 | tb = ''.join(traceback.format_list(value)) |
| 1248 | value = 'Object created at (most recent call last):\n' |
| 1249 | value += tb.rstrip() |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1250 | elif key == 'handle_traceback': |
| 1251 | tb = ''.join(traceback.format_list(value)) |
| 1252 | value = 'Handle created at (most recent call last):\n' |
| 1253 | value += tb.rstrip() |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1254 | else: |
| 1255 | value = repr(value) |
| 1256 | log_lines.append('{}: {}'.format(key, value)) |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1257 | |
| 1258 | logger.error('\n'.join(log_lines), exc_info=exc_info) |
| 1259 | |
| 1260 | def call_exception_handler(self, context): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1261 | """Call the current event loop's exception handler. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1262 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1263 | The context argument is a dict containing the following keys: |
| 1264 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1265 | - 'message': Error message; |
| 1266 | - 'exception' (optional): Exception object; |
| 1267 | - 'future' (optional): Future instance; |
| 1268 | - 'handle' (optional): Handle instance; |
| 1269 | - 'protocol' (optional): Protocol instance; |
| 1270 | - 'transport' (optional): Transport instance; |
Yury Selivanov | 4357cf6 | 2016-09-15 13:49:08 -0400 | [diff] [blame] | 1271 | - 'socket' (optional): Socket instance; |
| 1272 | - 'asyncgen' (optional): Asynchronous generator that caused |
| 1273 | the exception. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1274 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1275 | New keys maybe introduced in the future. |
| 1276 | |
| 1277 | Note: do not overload this method in an event loop subclass. |
| 1278 | For custom exception handling, use the |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1279 | `set_exception_handler()` method. |
| 1280 | """ |
| 1281 | if self._exception_handler is None: |
| 1282 | try: |
| 1283 | self.default_exception_handler(context) |
| 1284 | except Exception: |
| 1285 | # Second protection layer for unexpected errors |
| 1286 | # in the default implementation, as well as for subclassed |
| 1287 | # event loops with overloaded "default_exception_handler". |
| 1288 | logger.error('Exception in default exception handler', |
| 1289 | exc_info=True) |
| 1290 | else: |
| 1291 | try: |
| 1292 | self._exception_handler(self, context) |
| 1293 | except Exception as exc: |
| 1294 | # Exception in the user set custom exception handler. |
| 1295 | try: |
| 1296 | # Let's try default handler. |
| 1297 | self.default_exception_handler({ |
| 1298 | 'message': 'Unhandled error in exception handler', |
| 1299 | 'exception': exc, |
| 1300 | 'context': context, |
| 1301 | }) |
| 1302 | except Exception: |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1303 | # Guard 'default_exception_handler' in case it is |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1304 | # overloaded. |
| 1305 | logger.error('Exception in default exception handler ' |
| 1306 | 'while handling an unexpected error ' |
| 1307 | 'in custom exception handler', |
| 1308 | exc_info=True) |
| 1309 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1310 | def _add_callback(self, handle): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1311 | """Add a Handle to _scheduled (TimerHandle) or _ready.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1312 | assert isinstance(handle, events.Handle), 'A Handle is required here' |
| 1313 | if handle._cancelled: |
| 1314 | return |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1315 | assert not isinstance(handle, events.TimerHandle) |
| 1316 | self._ready.append(handle) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1317 | |
| 1318 | def _add_callback_signalsafe(self, handle): |
| 1319 | """Like _add_callback() but called from a signal handler.""" |
| 1320 | self._add_callback(handle) |
| 1321 | self._write_to_self() |
| 1322 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1323 | def _timer_handle_cancelled(self, handle): |
| 1324 | """Notification that a TimerHandle has been cancelled.""" |
| 1325 | if handle._scheduled: |
| 1326 | self._timer_cancelled_count += 1 |
| 1327 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1328 | def _run_once(self): |
| 1329 | """Run one full iteration of the event loop. |
| 1330 | |
| 1331 | This calls all currently ready callbacks, polls for I/O, |
| 1332 | schedules the resulting callbacks, and finally schedules |
| 1333 | 'call_later' callbacks. |
| 1334 | """ |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1335 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1336 | sched_count = len(self._scheduled) |
| 1337 | if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and |
| 1338 | self._timer_cancelled_count / sched_count > |
| 1339 | _MIN_CANCELLED_TIMER_HANDLES_FRACTION): |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1340 | # Remove delayed calls that were cancelled if their number |
| 1341 | # is too high |
| 1342 | new_scheduled = [] |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1343 | for handle in self._scheduled: |
| 1344 | if handle._cancelled: |
| 1345 | handle._scheduled = False |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1346 | else: |
| 1347 | new_scheduled.append(handle) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1348 | |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1349 | heapq.heapify(new_scheduled) |
| 1350 | self._scheduled = new_scheduled |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1351 | self._timer_cancelled_count = 0 |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1352 | else: |
| 1353 | # Remove delayed calls that were cancelled from head of queue. |
| 1354 | while self._scheduled and self._scheduled[0]._cancelled: |
| 1355 | self._timer_cancelled_count -= 1 |
| 1356 | handle = heapq.heappop(self._scheduled) |
| 1357 | handle._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1358 | |
| 1359 | timeout = None |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 1360 | if self._ready or self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1361 | timeout = 0 |
| 1362 | elif self._scheduled: |
| 1363 | # Compute the desired timeout. |
| 1364 | when = self._scheduled[0]._when |
Guido van Rossum | 3d1bc60 | 2014-05-10 15:47:15 -0700 | [diff] [blame] | 1365 | timeout = max(0, when - self.time()) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1366 | |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1367 | if self._debug and timeout != 0: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1368 | t0 = self.time() |
| 1369 | event_list = self._selector.select(timeout) |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1370 | dt = self.time() - t0 |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1371 | if dt >= 1.0: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1372 | level = logging.INFO |
| 1373 | else: |
| 1374 | level = logging.DEBUG |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1375 | nevent = len(event_list) |
| 1376 | if timeout is None: |
| 1377 | logger.log(level, 'poll took %.3f ms: %s events', |
| 1378 | dt * 1e3, nevent) |
| 1379 | elif nevent: |
| 1380 | logger.log(level, |
| 1381 | 'poll %.3f ms took %.3f ms: %s events', |
| 1382 | timeout * 1e3, dt * 1e3, nevent) |
| 1383 | elif dt >= 1.0: |
| 1384 | logger.log(level, |
| 1385 | 'poll %.3f ms took %.3f ms: timeout', |
| 1386 | timeout * 1e3, dt * 1e3) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1387 | else: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1388 | event_list = self._selector.select(timeout) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1389 | self._process_events(event_list) |
| 1390 | |
| 1391 | # Handle 'later' callbacks that are ready. |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1392 | end_time = self.time() + self._clock_resolution |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1393 | while self._scheduled: |
| 1394 | handle = self._scheduled[0] |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1395 | if handle._when >= end_time: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1396 | break |
| 1397 | handle = heapq.heappop(self._scheduled) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1398 | handle._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1399 | self._ready.append(handle) |
| 1400 | |
| 1401 | # This is the only place where callbacks are actually *called*. |
| 1402 | # All other places just add them to ready. |
| 1403 | # Note: We run all currently scheduled callbacks, but not any |
| 1404 | # callbacks scheduled by callbacks run this time around -- |
| 1405 | # they will be run the next time (after another I/O poll). |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1406 | # Use an idiom that is thread-safe without using locks. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1407 | ntodo = len(self._ready) |
| 1408 | for i in range(ntodo): |
| 1409 | handle = self._ready.popleft() |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1410 | if handle._cancelled: |
| 1411 | continue |
| 1412 | if self._debug: |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1413 | try: |
| 1414 | self._current_handle = handle |
| 1415 | t0 = self.time() |
| 1416 | handle._run() |
| 1417 | dt = self.time() - t0 |
| 1418 | if dt >= self.slow_callback_duration: |
| 1419 | logger.warning('Executing %s took %.3f seconds', |
| 1420 | _format_handle(handle), dt) |
| 1421 | finally: |
| 1422 | self._current_handle = None |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1423 | else: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1424 | handle._run() |
| 1425 | handle = None # Needed to break cycles when an exception occurs. |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1426 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1427 | def _set_coroutine_wrapper(self, enabled): |
| 1428 | try: |
| 1429 | set_wrapper = sys.set_coroutine_wrapper |
| 1430 | get_wrapper = sys.get_coroutine_wrapper |
| 1431 | except AttributeError: |
| 1432 | return |
| 1433 | |
| 1434 | enabled = bool(enabled) |
Yury Selivanov | 996083d | 2015-08-04 15:37:24 -0400 | [diff] [blame] | 1435 | if self._coroutine_wrapper_set == enabled: |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1436 | return |
| 1437 | |
| 1438 | wrapper = coroutines.debug_wrapper |
| 1439 | current_wrapper = get_wrapper() |
| 1440 | |
| 1441 | if enabled: |
| 1442 | if current_wrapper not in (None, wrapper): |
| 1443 | warnings.warn( |
| 1444 | "loop.set_debug(True): cannot set debug coroutine " |
| 1445 | "wrapper; another wrapper is already set %r" % |
| 1446 | current_wrapper, RuntimeWarning) |
| 1447 | else: |
| 1448 | set_wrapper(wrapper) |
| 1449 | self._coroutine_wrapper_set = True |
| 1450 | else: |
| 1451 | if current_wrapper not in (None, wrapper): |
| 1452 | warnings.warn( |
| 1453 | "loop.set_debug(False): cannot unset debug coroutine " |
| 1454 | "wrapper; another wrapper was set %r" % |
| 1455 | current_wrapper, RuntimeWarning) |
| 1456 | else: |
| 1457 | set_wrapper(None) |
| 1458 | self._coroutine_wrapper_set = False |
| 1459 | |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1460 | def get_debug(self): |
| 1461 | return self._debug |
| 1462 | |
| 1463 | def set_debug(self, enabled): |
| 1464 | self._debug = enabled |
Yury Selivanov | 1af2bf7 | 2015-05-11 22:27:25 -0400 | [diff] [blame] | 1465 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1466 | if self.is_running(): |
| 1467 | self._set_coroutine_wrapper(enabled) |