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 |
Serhiy Storchaka | 2e576f5 | 2017-04-24 09:05:00 +0300 | [diff] [blame] | 17 | import collections.abc |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 18 | import concurrent.futures |
| 19 | import heapq |
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 | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 30 | import weakref |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 31 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 32 | from . import coroutines |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 33 | from . import events |
| 34 | from . import futures |
| 35 | from . import tasks |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 36 | from .coroutines import coroutine |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 37 | from .log import logger |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 38 | |
| 39 | |
Victor Stinner | 8c1a4a2 | 2015-01-06 01:03:58 +0100 | [diff] [blame] | 40 | __all__ = ['BaseEventLoop'] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 41 | |
| 42 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 43 | # Minimum number of _scheduled timer handles before cleanup of |
| 44 | # cancelled handles is performed. |
| 45 | _MIN_SCHEDULED_TIMER_HANDLES = 100 |
| 46 | |
| 47 | # Minimum fraction of _scheduled timer handles that are cancelled |
| 48 | # before cleanup of cancelled handles is performed. |
| 49 | _MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5 |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 50 | |
Victor Stinner | c94a93a | 2016-04-01 21:43:39 +0200 | [diff] [blame] | 51 | # Exceptions which must not call the exception handler in fatal error |
| 52 | # methods (_fatal_error()) |
| 53 | _FATAL_ERROR_IGNORE = (BrokenPipeError, |
| 54 | ConnectionResetError, ConnectionAbortedError) |
| 55 | |
| 56 | |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 57 | def _format_handle(handle): |
| 58 | cb = handle._callback |
Yury Selivanov | a0c1ba6 | 2016-10-28 12:52:37 -0400 | [diff] [blame] | 59 | if isinstance(getattr(cb, '__self__', None), tasks.Task): |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 60 | # format the task |
| 61 | return repr(cb.__self__) |
| 62 | else: |
| 63 | return str(handle) |
| 64 | |
| 65 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 66 | def _format_pipe(fd): |
| 67 | if fd == subprocess.PIPE: |
| 68 | return '<pipe>' |
| 69 | elif fd == subprocess.STDOUT: |
| 70 | return '<stdout>' |
| 71 | else: |
| 72 | return repr(fd) |
| 73 | |
| 74 | |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 75 | def _set_reuseport(sock): |
| 76 | if not hasattr(socket, 'SO_REUSEPORT'): |
| 77 | raise ValueError('reuse_port not supported by socket module') |
| 78 | else: |
| 79 | try: |
| 80 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) |
| 81 | except OSError: |
| 82 | raise ValueError('reuse_port not supported by socket module, ' |
| 83 | 'SO_REUSEPORT defined but not implemented.') |
| 84 | |
| 85 | |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 86 | def _is_stream_socket(sock): |
| 87 | # Linux's socket.type is a bitmask that can include extra info |
| 88 | # about socket, therefore we can't do simple |
| 89 | # `sock_type == socket.SOCK_STREAM`. |
| 90 | return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM |
| 91 | |
| 92 | |
| 93 | def _is_dgram_socket(sock): |
| 94 | # Linux's socket.type is a bitmask that can include extra info |
| 95 | # about socket, therefore we can't do simple |
| 96 | # `sock_type == socket.SOCK_DGRAM`. |
| 97 | return (sock.type & socket.SOCK_DGRAM) == socket.SOCK_DGRAM |
| 98 | |
| 99 | |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 100 | def _ipaddr_info(host, port, family, type, proto): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 101 | # Try to skip getaddrinfo if "host" is already an IP. Users might have |
| 102 | # handled name resolution in their own code and pass in resolved IPs. |
| 103 | if not hasattr(socket, 'inet_pton'): |
| 104 | return |
| 105 | |
| 106 | if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \ |
| 107 | host is None: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 108 | return None |
| 109 | |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 110 | if type == socket.SOCK_STREAM: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 111 | # Linux only: |
| 112 | # getaddrinfo() can raise when socket.type is a bit mask. |
| 113 | # So if socket.type is a bit mask of SOCK_STREAM, and say |
| 114 | # SOCK_NONBLOCK, we simply return None, which will trigger |
| 115 | # a call to getaddrinfo() letting it process this request. |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 116 | proto = socket.IPPROTO_TCP |
| 117 | elif type == socket.SOCK_DGRAM: |
| 118 | proto = socket.IPPROTO_UDP |
| 119 | else: |
| 120 | return None |
| 121 | |
Yury Selivanov | a714616 | 2016-06-02 16:51:07 -0400 | [diff] [blame] | 122 | if port is None: |
Yury Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 123 | port = 0 |
Guido van Rossum | e3c65a7 | 2016-09-30 08:17:15 -0700 | [diff] [blame] | 124 | elif isinstance(port, bytes) and port == b'': |
| 125 | port = 0 |
| 126 | elif isinstance(port, str) and port == '': |
| 127 | port = 0 |
| 128 | else: |
| 129 | # If port's a service name like "http", don't skip getaddrinfo. |
| 130 | try: |
| 131 | port = int(port) |
| 132 | except (TypeError, ValueError): |
| 133 | return None |
Yury Selivanov | eaaaee8 | 2016-05-20 17:44:19 -0400 | [diff] [blame] | 134 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 135 | if family == socket.AF_UNSPEC: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 136 | afs = [socket.AF_INET] |
| 137 | if hasattr(socket, 'AF_INET6'): |
| 138 | afs.append(socket.AF_INET6) |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 139 | else: |
| 140 | afs = [family] |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 141 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 142 | if isinstance(host, bytes): |
| 143 | host = host.decode('idna') |
| 144 | if '%' in host: |
| 145 | # Linux's inet_pton doesn't accept an IPv6 zone index after host, |
| 146 | # like '::1%lo0'. |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 147 | return None |
| 148 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 149 | for af in afs: |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 150 | try: |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 151 | socket.inet_pton(af, host) |
| 152 | # The host has already been resolved. |
| 153 | return af, type, proto, '', (host, port) |
| 154 | except OSError: |
| 155 | pass |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 156 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 157 | # "host" is not an IP address. |
| 158 | return None |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 159 | |
| 160 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 161 | def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0, |
| 162 | flags=0, loop): |
Yury Selivanov | d5c2a62 | 2015-12-16 19:31:17 -0500 | [diff] [blame] | 163 | host, port = address[:2] |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 164 | info = _ipaddr_info(host, port, family, type, proto) |
| 165 | if info is not None: |
| 166 | # "host" is already a resolved IP. |
| 167 | fut = loop.create_future() |
| 168 | fut.set_result([info]) |
| 169 | return fut |
| 170 | else: |
| 171 | return loop.getaddrinfo(host, port, family=family, type=type, |
| 172 | proto=proto, flags=flags) |
Victor Stinner | 1b0580b | 2014-02-13 09:24:37 +0100 | [diff] [blame] | 173 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 174 | |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 175 | def _run_until_complete_cb(fut): |
| 176 | exc = fut._exception |
| 177 | if (isinstance(exc, BaseException) |
| 178 | and not isinstance(exc, Exception)): |
| 179 | # Issue #22429: run_forever() already finished, no need to |
| 180 | # stop it. |
| 181 | return |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 182 | fut._loop.stop() |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 183 | |
| 184 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 185 | class Server(events.AbstractServer): |
| 186 | |
| 187 | def __init__(self, loop, sockets): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 188 | self._loop = loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 189 | self.sockets = sockets |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 190 | self._active_count = 0 |
| 191 | self._waiters = [] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 192 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 193 | def __repr__(self): |
| 194 | return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets) |
| 195 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 196 | def _attach(self): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 197 | assert self.sockets is not None |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 198 | self._active_count += 1 |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 199 | |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 200 | def _detach(self): |
| 201 | assert self._active_count > 0 |
| 202 | self._active_count -= 1 |
| 203 | if self._active_count == 0 and self.sockets is None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 204 | self._wakeup() |
| 205 | |
| 206 | def close(self): |
| 207 | sockets = self.sockets |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 208 | if sockets is None: |
| 209 | return |
| 210 | self.sockets = None |
| 211 | for sock in sockets: |
| 212 | self._loop._stop_serving(sock) |
| 213 | if self._active_count == 0: |
| 214 | self._wakeup() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 215 | |
| 216 | def _wakeup(self): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 217 | waiters = self._waiters |
| 218 | self._waiters = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 219 | for waiter in waiters: |
| 220 | if not waiter.done(): |
| 221 | waiter.set_result(waiter) |
| 222 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 223 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 224 | def wait_closed(self): |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 225 | if self.sockets is None or self._waiters is None: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 226 | return |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 227 | waiter = self._loop.create_future() |
Victor Stinner | b28dbac | 2014-07-11 22:52:21 +0200 | [diff] [blame] | 228 | self._waiters.append(waiter) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 229 | yield from waiter |
| 230 | |
| 231 | |
| 232 | class BaseEventLoop(events.AbstractEventLoop): |
| 233 | |
| 234 | def __init__(self): |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 235 | self._timer_cancelled_count = 0 |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 236 | self._closed = False |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 237 | self._stopping = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 238 | self._ready = collections.deque() |
| 239 | self._scheduled = [] |
| 240 | self._default_executor = None |
| 241 | self._internal_fds = 0 |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 242 | # Identifier of the thread running the event loop, or None if the |
| 243 | # event loop is not running |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 244 | self._thread_id = None |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 245 | self._clock_resolution = time.get_clock_info('monotonic').resolution |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 246 | self._exception_handler = None |
Yury Selivanov | 1af2bf7 | 2015-05-11 22:27:25 -0400 | [diff] [blame] | 247 | self.set_debug((not sys.flags.ignore_environment |
| 248 | and bool(os.environ.get('PYTHONASYNCIODEBUG')))) |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 249 | # In debug mode, if the execution of a callback or a step of a task |
| 250 | # exceed this duration in seconds, the slow callback/task is logged. |
| 251 | self.slow_callback_duration = 0.1 |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 252 | self._current_handle = None |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 253 | self._task_factory = None |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 254 | self._coroutine_wrapper_set = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 255 | |
Yury Selivanov | 0a91d48 | 2016-09-15 13:24:03 -0400 | [diff] [blame] | 256 | if hasattr(sys, 'get_asyncgen_hooks'): |
| 257 | # Python >= 3.6 |
| 258 | # A weak set of all asynchronous generators that are |
| 259 | # being iterated by the loop. |
| 260 | self._asyncgens = weakref.WeakSet() |
| 261 | else: |
| 262 | self._asyncgens = None |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 263 | |
| 264 | # Set to True when `loop.shutdown_asyncgens` is called. |
| 265 | self._asyncgens_shutdown_called = False |
| 266 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 267 | def __repr__(self): |
| 268 | return ('<%s running=%s closed=%s debug=%s>' |
| 269 | % (self.__class__.__name__, self.is_running(), |
| 270 | self.is_closed(), self.get_debug())) |
| 271 | |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 272 | def create_future(self): |
| 273 | """Create a Future object attached to the loop.""" |
| 274 | return futures.Future(loop=self) |
| 275 | |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 276 | def create_task(self, coro): |
| 277 | """Schedule a coroutine object. |
| 278 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 279 | Return a task object. |
| 280 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 281 | self._check_closed() |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 282 | if self._task_factory is None: |
| 283 | task = tasks.Task(coro, loop=self) |
| 284 | if task._source_traceback: |
| 285 | del task._source_traceback[-1] |
| 286 | else: |
| 287 | task = self._task_factory(self, coro) |
Victor Stinner | c39ba7d | 2014-07-11 00:21:27 +0200 | [diff] [blame] | 288 | return task |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 289 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 290 | def set_task_factory(self, factory): |
| 291 | """Set a task factory that will be used by loop.create_task(). |
| 292 | |
| 293 | If factory is None the default task factory will be set. |
| 294 | |
| 295 | If factory is a callable, it should have a signature matching |
| 296 | '(loop, coro)', where 'loop' will be a reference to the active |
| 297 | event loop, 'coro' will be a coroutine object. The callable |
| 298 | must return a Future. |
| 299 | """ |
| 300 | if factory is not None and not callable(factory): |
| 301 | raise TypeError('task factory must be a callable or None') |
| 302 | self._task_factory = factory |
| 303 | |
| 304 | def get_task_factory(self): |
| 305 | """Return a task factory, or None if the default one is in use.""" |
| 306 | return self._task_factory |
| 307 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 308 | def _make_socket_transport(self, sock, protocol, waiter=None, *, |
| 309 | extra=None, server=None): |
| 310 | """Create socket transport.""" |
| 311 | raise NotImplementedError |
| 312 | |
Victor Stinner | 15cc678 | 2015-01-09 00:09:10 +0100 | [diff] [blame] | 313 | def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None, |
| 314 | *, server_side=False, server_hostname=None, |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 315 | extra=None, server=None): |
| 316 | """Create SSL transport.""" |
| 317 | raise NotImplementedError |
| 318 | |
| 319 | def _make_datagram_transport(self, sock, protocol, |
Victor Stinner | bfff45d | 2014-07-08 23:57:31 +0200 | [diff] [blame] | 320 | address=None, waiter=None, extra=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 321 | """Create datagram transport.""" |
| 322 | raise NotImplementedError |
| 323 | |
| 324 | def _make_read_pipe_transport(self, pipe, protocol, waiter=None, |
| 325 | extra=None): |
| 326 | """Create read pipe transport.""" |
| 327 | raise NotImplementedError |
| 328 | |
| 329 | def _make_write_pipe_transport(self, pipe, protocol, waiter=None, |
| 330 | extra=None): |
| 331 | """Create write pipe transport.""" |
| 332 | raise NotImplementedError |
| 333 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 334 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 335 | def _make_subprocess_transport(self, protocol, args, shell, |
| 336 | stdin, stdout, stderr, bufsize, |
| 337 | extra=None, **kwargs): |
| 338 | """Create subprocess transport.""" |
| 339 | raise NotImplementedError |
| 340 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 341 | def _write_to_self(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 342 | """Write a byte to self-pipe, to wake up the event loop. |
| 343 | |
| 344 | This may be called from a different thread. |
| 345 | |
| 346 | The subclass is responsible for implementing the self-pipe. |
| 347 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 348 | raise NotImplementedError |
| 349 | |
| 350 | def _process_events(self, event_list): |
| 351 | """Process selector events.""" |
| 352 | raise NotImplementedError |
| 353 | |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 354 | def _check_closed(self): |
| 355 | if self._closed: |
| 356 | raise RuntimeError('Event loop is closed') |
| 357 | |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 358 | def _asyncgen_finalizer_hook(self, agen): |
| 359 | self._asyncgens.discard(agen) |
| 360 | if not self.is_closed(): |
| 361 | self.create_task(agen.aclose()) |
Yury Selivanov | ed05406 | 2016-10-21 17:13:40 -0400 | [diff] [blame] | 362 | # Wake up the loop if the finalizer was called from |
| 363 | # a different thread. |
| 364 | self._write_to_self() |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 365 | |
| 366 | def _asyncgen_firstiter_hook(self, agen): |
| 367 | if self._asyncgens_shutdown_called: |
| 368 | warnings.warn( |
| 369 | "asynchronous generator {!r} was scheduled after " |
| 370 | "loop.shutdown_asyncgens() call".format(agen), |
| 371 | ResourceWarning, source=self) |
| 372 | |
| 373 | self._asyncgens.add(agen) |
| 374 | |
| 375 | @coroutine |
| 376 | def shutdown_asyncgens(self): |
| 377 | """Shutdown all active asynchronous generators.""" |
| 378 | self._asyncgens_shutdown_called = True |
| 379 | |
Yury Selivanov | 0a91d48 | 2016-09-15 13:24:03 -0400 | [diff] [blame] | 380 | if self._asyncgens is None or not len(self._asyncgens): |
| 381 | # If Python version is <3.6 or we don't have any asynchronous |
| 382 | # generators alive. |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 383 | return |
| 384 | |
| 385 | closing_agens = list(self._asyncgens) |
| 386 | self._asyncgens.clear() |
| 387 | |
| 388 | shutdown_coro = tasks.gather( |
| 389 | *[ag.aclose() for ag in closing_agens], |
| 390 | return_exceptions=True, |
| 391 | loop=self) |
| 392 | |
| 393 | results = yield from shutdown_coro |
| 394 | for result, agen in zip(results, closing_agens): |
| 395 | if isinstance(result, Exception): |
| 396 | self.call_exception_handler({ |
| 397 | 'message': 'an error occurred during closing of ' |
| 398 | 'asynchronous generator {!r}'.format(agen), |
| 399 | 'exception': result, |
| 400 | 'asyncgen': agen |
| 401 | }) |
| 402 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 403 | def run_forever(self): |
| 404 | """Run until stop() is called.""" |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 405 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 406 | if self.is_running(): |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 407 | raise RuntimeError('This event loop is already running') |
| 408 | if events._get_running_loop() is not None: |
| 409 | raise RuntimeError( |
| 410 | 'Cannot run the event loop while another loop is running') |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 411 | self._set_coroutine_wrapper(self._debug) |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 412 | self._thread_id = threading.get_ident() |
Yury Selivanov | 0a91d48 | 2016-09-15 13:24:03 -0400 | [diff] [blame] | 413 | if self._asyncgens is not None: |
| 414 | old_agen_hooks = sys.get_asyncgen_hooks() |
| 415 | sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, |
| 416 | finalizer=self._asyncgen_finalizer_hook) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 417 | try: |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 418 | events._set_running_loop(self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 419 | while True: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 420 | self._run_once() |
| 421 | if self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 422 | break |
| 423 | finally: |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 424 | self._stopping = False |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 425 | self._thread_id = None |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 426 | events._set_running_loop(None) |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 427 | self._set_coroutine_wrapper(False) |
Yury Selivanov | 0a91d48 | 2016-09-15 13:24:03 -0400 | [diff] [blame] | 428 | if self._asyncgens is not None: |
| 429 | sys.set_asyncgen_hooks(*old_agen_hooks) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 430 | |
| 431 | def run_until_complete(self, future): |
| 432 | """Run until the Future is done. |
| 433 | |
| 434 | If the argument is a coroutine, it is wrapped in a Task. |
| 435 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 436 | WARNING: It would be disastrous to call run_until_complete() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 437 | with the same coroutine twice -- it would wrap it in two |
| 438 | different Tasks and that can't be good. |
| 439 | |
| 440 | Return the Future's result, or raise its exception. |
| 441 | """ |
Victor Stinner | bb2fc5b | 2014-06-10 10:23:10 +0200 | [diff] [blame] | 442 | self._check_closed() |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 443 | |
Guido van Rossum | 7b3b3dc | 2016-09-09 14:26:31 -0700 | [diff] [blame] | 444 | new_task = not futures.isfuture(future) |
Yury Selivanov | 59eb9a4 | 2015-05-11 14:48:38 -0400 | [diff] [blame] | 445 | future = tasks.ensure_future(future, loop=self) |
Victor Stinner | 98b6391 | 2014-06-30 14:51:04 +0200 | [diff] [blame] | 446 | if new_task: |
| 447 | # An exception is raised if the future didn't complete, so there |
| 448 | # is no need to log the "destroy pending task" message |
| 449 | future._log_destroy_pending = False |
| 450 | |
Victor Stinner | f3e2e09 | 2014-12-05 01:44:10 +0100 | [diff] [blame] | 451 | future.add_done_callback(_run_until_complete_cb) |
Victor Stinner | c8bd53f | 2014-10-11 14:30:18 +0200 | [diff] [blame] | 452 | try: |
| 453 | self.run_forever() |
| 454 | except: |
| 455 | if new_task and future.done() and not future.cancelled(): |
| 456 | # The coroutine raised a BaseException. Consume the exception |
| 457 | # to not log a warning, the caller doesn't have access to the |
| 458 | # local task. |
| 459 | future.exception() |
| 460 | raise |
jimmylai | 21b3e04 | 2017-05-22 22:32:46 -0700 | [diff] [blame^] | 461 | finally: |
| 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 | |
INADA Naoki | 3e2ad8e | 2017-04-25 10:57:18 +0900 | [diff] [blame] | 502 | def __del__(self): |
| 503 | if not self.is_closed(): |
| 504 | warnings.warn("unclosed event loop %r" % self, ResourceWarning, |
| 505 | source=self) |
| 506 | if not self.is_running(): |
| 507 | self.close() |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 508 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 509 | def is_running(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 510 | """Returns True if the event loop is running.""" |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 511 | return (self._thread_id is not None) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 512 | |
| 513 | def time(self): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 514 | """Return the time according to the event loop's clock. |
| 515 | |
| 516 | This is a float expressed in seconds since an epoch, but the |
| 517 | epoch, precision, accuracy and drift are unspecified and may |
| 518 | differ per event loop. |
| 519 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 520 | return time.monotonic() |
| 521 | |
| 522 | def call_later(self, delay, callback, *args): |
| 523 | """Arrange for a callback to be called at a given time. |
| 524 | |
| 525 | Return a Handle: an opaque object with a cancel() method that |
| 526 | can be used to cancel the call. |
| 527 | |
| 528 | 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] | 529 | always relative to the current time. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 530 | |
| 531 | Each callback will be called exactly once. If two callbacks |
| 532 | are scheduled for exactly the same time, it undefined which |
| 533 | will be called first. |
| 534 | |
| 535 | Any positional arguments after the callback will be passed to |
| 536 | the callback when it is called. |
| 537 | """ |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 538 | timer = self.call_at(self.time() + delay, callback, *args) |
| 539 | if timer._source_traceback: |
| 540 | del timer._source_traceback[-1] |
| 541 | return timer |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 542 | |
| 543 | def call_at(self, when, callback, *args): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 544 | """Like call_later(), but uses an absolute time. |
| 545 | |
| 546 | Absolute time corresponds to the event loop's time() method. |
| 547 | """ |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 548 | self._check_closed() |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 549 | if self._debug: |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 550 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 551 | self._check_callback(callback, 'call_at') |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 552 | timer = events.TimerHandle(when, callback, args, self) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 553 | if timer._source_traceback: |
| 554 | del timer._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 555 | heapq.heappush(self._scheduled, timer) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 556 | timer._scheduled = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 557 | return timer |
| 558 | |
| 559 | def call_soon(self, callback, *args): |
| 560 | """Arrange for a callback to be called as soon as possible. |
| 561 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 562 | This operates as a FIFO queue: callbacks are called in the |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 563 | order in which they are registered. Each callback will be |
| 564 | called exactly once. |
| 565 | |
| 566 | Any positional arguments after the callback will be passed to |
| 567 | the callback when it is called. |
| 568 | """ |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 569 | self._check_closed() |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 570 | if self._debug: |
| 571 | self._check_thread() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 572 | self._check_callback(callback, 'call_soon') |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 573 | handle = self._call_soon(callback, args) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 574 | if handle._source_traceback: |
| 575 | del handle._source_traceback[-1] |
| 576 | return handle |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 577 | |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 578 | def _check_callback(self, callback, method): |
| 579 | if (coroutines.iscoroutine(callback) or |
| 580 | coroutines.iscoroutinefunction(callback)): |
| 581 | raise TypeError( |
| 582 | "coroutines cannot be used with {}()".format(method)) |
| 583 | if not callable(callback): |
| 584 | raise TypeError( |
| 585 | 'a callable object was expected by {}(), got {!r}'.format( |
| 586 | method, callback)) |
| 587 | |
| 588 | |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 589 | def _call_soon(self, callback, args): |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 590 | handle = events.Handle(callback, args, self) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 591 | if handle._source_traceback: |
| 592 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 593 | self._ready.append(handle) |
| 594 | return handle |
| 595 | |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 596 | def _check_thread(self): |
| 597 | """Check that the current thread is the thread running the event loop. |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 598 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 599 | Non-thread-safe methods of this class make this assumption and will |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 600 | likely behave incorrectly when the assumption is violated. |
| 601 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 602 | Should only be called when (self._debug == True). The caller is |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 603 | responsible for checking this condition for performance reasons. |
| 604 | """ |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 605 | if self._thread_id is None: |
Victor Stinner | 751c7c0 | 2014-06-23 15:14:13 +0200 | [diff] [blame] | 606 | return |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 607 | thread_id = threading.get_ident() |
Victor Stinner | a87501f | 2015-02-05 11:45:33 +0100 | [diff] [blame] | 608 | if thread_id != self._thread_id: |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 609 | raise RuntimeError( |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 610 | "Non-thread-safe operation invoked on an event loop other " |
Victor Stinner | 93569c2 | 2014-03-21 10:00:52 +0100 | [diff] [blame] | 611 | "than the current one") |
| 612 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 613 | def call_soon_threadsafe(self, callback, *args): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 614 | """Like call_soon(), but thread-safe.""" |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 615 | self._check_closed() |
| 616 | if self._debug: |
| 617 | self._check_callback(callback, 'call_soon_threadsafe') |
Victor Stinner | 956de69 | 2014-12-26 21:07:52 +0100 | [diff] [blame] | 618 | handle = self._call_soon(callback, args) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 619 | if handle._source_traceback: |
| 620 | del handle._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 621 | self._write_to_self() |
| 622 | return handle |
| 623 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 624 | def run_in_executor(self, executor, func, *args): |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 625 | self._check_closed() |
Yury Selivanov | 491a912 | 2016-11-03 15:09:24 -0700 | [diff] [blame] | 626 | if self._debug: |
| 627 | self._check_callback(func, 'run_in_executor') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 628 | if executor is None: |
| 629 | executor = self._default_executor |
| 630 | if executor is None: |
Yury Selivanov | e8a6045 | 2016-10-21 17:40:42 -0400 | [diff] [blame] | 631 | executor = concurrent.futures.ThreadPoolExecutor() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 632 | self._default_executor = executor |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 633 | return futures.wrap_future(executor.submit(func, *args), loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 634 | |
| 635 | def set_default_executor(self, executor): |
| 636 | self._default_executor = executor |
| 637 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 638 | def _getaddrinfo_debug(self, host, port, family, type, proto, flags): |
| 639 | msg = ["%s:%r" % (host, port)] |
| 640 | if family: |
| 641 | msg.append('family=%r' % family) |
| 642 | if type: |
| 643 | msg.append('type=%r' % type) |
| 644 | if proto: |
| 645 | msg.append('proto=%r' % proto) |
| 646 | if flags: |
| 647 | msg.append('flags=%r' % flags) |
| 648 | msg = ', '.join(msg) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 649 | logger.debug('Get address info %s', msg) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 650 | |
| 651 | t0 = self.time() |
| 652 | addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags) |
| 653 | dt = self.time() - t0 |
| 654 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 655 | msg = ('Getting address info %s took %.3f ms: %r' |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 656 | % (msg, dt * 1e3, addrinfo)) |
| 657 | if dt >= self.slow_callback_duration: |
| 658 | logger.info(msg) |
| 659 | else: |
| 660 | logger.debug(msg) |
| 661 | return addrinfo |
| 662 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 663 | def getaddrinfo(self, host, port, *, |
| 664 | family=0, type=0, proto=0, flags=0): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 665 | if self._debug: |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 666 | return self.run_in_executor(None, self._getaddrinfo_debug, |
| 667 | host, port, family, type, proto, flags) |
| 668 | else: |
| 669 | return self.run_in_executor(None, socket.getaddrinfo, |
| 670 | host, port, family, type, proto, flags) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 671 | |
| 672 | def getnameinfo(self, sockaddr, flags=0): |
| 673 | return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags) |
| 674 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 675 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 676 | def create_connection(self, protocol_factory, host=None, port=None, *, |
| 677 | ssl=None, family=0, proto=0, flags=0, sock=None, |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 678 | local_addr=None, server_hostname=None): |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 679 | """Connect to a TCP server. |
| 680 | |
| 681 | Create a streaming transport connection to a given Internet host and |
| 682 | port: socket family AF_INET or socket.AF_INET6 depending on host (or |
| 683 | family if specified), socket type SOCK_STREAM. protocol_factory must be |
| 684 | a callable returning a protocol instance. |
| 685 | |
| 686 | This method is a coroutine which will try to establish the connection |
| 687 | in the background. When successful, the coroutine returns a |
| 688 | (transport, protocol) pair. |
| 689 | """ |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 690 | if server_hostname is not None and not ssl: |
| 691 | raise ValueError('server_hostname is only meaningful with ssl') |
| 692 | |
| 693 | if server_hostname is None and ssl: |
| 694 | # Use host as default for server_hostname. It is an error |
| 695 | # if host is empty or not set, e.g. when an |
| 696 | # already-connected socket was passed or when only a port |
| 697 | # is given. To avoid this error, you can pass |
| 698 | # server_hostname='' -- this will bypass the hostname |
| 699 | # check. (This also means that if host is a numeric |
| 700 | # IP/IPv6 address, we will attempt to verify that exact |
| 701 | # address; this will probably fail, but it is possible to |
| 702 | # create a certificate for a specific IP address, so we |
| 703 | # don't judge it here.) |
| 704 | if not host: |
| 705 | raise ValueError('You must set server_hostname ' |
| 706 | 'when using ssl without a host') |
| 707 | server_hostname = host |
Guido van Rossum | a8d630a | 2013-11-01 14:20:55 -0700 | [diff] [blame] | 708 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 709 | if host is not None or port is not None: |
| 710 | if sock is not None: |
| 711 | raise ValueError( |
| 712 | 'host/port and sock can not be specified at the same time') |
| 713 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 714 | f1 = _ensure_resolved((host, port), family=family, |
| 715 | type=socket.SOCK_STREAM, proto=proto, |
| 716 | flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 717 | fs = [f1] |
| 718 | if local_addr is not None: |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 719 | f2 = _ensure_resolved(local_addr, family=family, |
| 720 | type=socket.SOCK_STREAM, proto=proto, |
| 721 | flags=flags, loop=self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 722 | fs.append(f2) |
| 723 | else: |
| 724 | f2 = None |
| 725 | |
| 726 | yield from tasks.wait(fs, loop=self) |
| 727 | |
| 728 | infos = f1.result() |
| 729 | if not infos: |
| 730 | raise OSError('getaddrinfo() returned empty list') |
| 731 | if f2 is not None: |
| 732 | laddr_infos = f2.result() |
| 733 | if not laddr_infos: |
| 734 | raise OSError('getaddrinfo() returned empty list') |
| 735 | |
| 736 | exceptions = [] |
| 737 | for family, type, proto, cname, address in infos: |
| 738 | try: |
| 739 | sock = socket.socket(family=family, type=type, proto=proto) |
| 740 | sock.setblocking(False) |
| 741 | if f2 is not None: |
| 742 | for _, _, _, _, laddr in laddr_infos: |
| 743 | try: |
| 744 | sock.bind(laddr) |
| 745 | break |
| 746 | except OSError as exc: |
| 747 | exc = OSError( |
| 748 | exc.errno, 'error while ' |
| 749 | 'attempting to bind on address ' |
| 750 | '{!r}: {}'.format( |
| 751 | laddr, exc.strerror.lower())) |
| 752 | exceptions.append(exc) |
| 753 | else: |
| 754 | sock.close() |
| 755 | sock = None |
| 756 | continue |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 757 | if self._debug: |
| 758 | logger.debug("connect %r to %r", sock, address) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 759 | yield from self.sock_connect(sock, address) |
| 760 | except OSError as exc: |
| 761 | if sock is not None: |
| 762 | sock.close() |
| 763 | exceptions.append(exc) |
Victor Stinner | 223a624 | 2014-06-04 00:11:52 +0200 | [diff] [blame] | 764 | except: |
| 765 | if sock is not None: |
| 766 | sock.close() |
| 767 | raise |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 768 | else: |
| 769 | break |
| 770 | else: |
| 771 | if len(exceptions) == 1: |
| 772 | raise exceptions[0] |
| 773 | else: |
| 774 | # If they all have the same str(), raise one. |
| 775 | model = str(exceptions[0]) |
| 776 | if all(str(exc) == model for exc in exceptions): |
| 777 | raise exceptions[0] |
| 778 | # Raise a combined exception so the user can see all |
| 779 | # the various error messages. |
| 780 | raise OSError('Multiple exceptions: {}'.format( |
| 781 | ', '.join(str(exc) for exc in exceptions))) |
| 782 | |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 783 | else: |
| 784 | if sock is None: |
| 785 | raise ValueError( |
| 786 | 'host and port was not specified and no sock specified') |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 787 | if not _is_stream_socket(sock): |
| 788 | # We allow AF_INET, AF_INET6, AF_UNIX as long as they |
| 789 | # are SOCK_STREAM. |
| 790 | # We support passing AF_UNIX sockets even though we have |
| 791 | # a dedicated API for that: create_unix_connection. |
| 792 | # Disallowing AF_UNIX in this method, breaks backwards |
| 793 | # compatibility. |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 794 | raise ValueError( |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 795 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 796 | |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 797 | transport, protocol = yield from self._create_connection_transport( |
| 798 | sock, protocol_factory, ssl, server_hostname) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 799 | if self._debug: |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 800 | # Get the socket from the transport because SSL transport closes |
| 801 | # the old socket and creates a new SSL socket |
| 802 | sock = transport.get_extra_info('socket') |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 803 | logger.debug("%r connected to %s:%r: (%r, %r)", |
| 804 | sock, host, port, transport, protocol) |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 805 | return transport, protocol |
| 806 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 807 | @coroutine |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 808 | def _create_connection_transport(self, sock, protocol_factory, ssl, |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 809 | server_hostname, server_side=False): |
| 810 | |
| 811 | sock.setblocking(False) |
| 812 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 813 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 814 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 815 | if ssl: |
| 816 | sslcontext = None if isinstance(ssl, bool) else ssl |
| 817 | transport = self._make_ssl_transport( |
| 818 | sock, protocol, sslcontext, waiter, |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 819 | server_side=server_side, server_hostname=server_hostname) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 820 | else: |
| 821 | transport = self._make_socket_transport(sock, protocol, waiter) |
| 822 | |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 823 | try: |
| 824 | yield from waiter |
Victor Stinner | 0c2e408 | 2015-01-22 00:17:41 +0100 | [diff] [blame] | 825 | except: |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 826 | transport.close() |
| 827 | raise |
| 828 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 829 | return transport, protocol |
| 830 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 831 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 832 | def create_datagram_endpoint(self, protocol_factory, |
| 833 | local_addr=None, remote_addr=None, *, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 834 | family=0, proto=0, flags=0, |
| 835 | reuse_address=None, reuse_port=None, |
| 836 | allow_broadcast=None, sock=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 837 | """Create datagram connection.""" |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 838 | if sock is not None: |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 839 | if not _is_dgram_socket(sock): |
| 840 | raise ValueError( |
| 841 | 'A UDP Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 842 | if (local_addr or remote_addr or |
| 843 | family or proto or flags or |
| 844 | reuse_address or reuse_port or allow_broadcast): |
| 845 | # show the problematic kwargs in exception msg |
| 846 | opts = dict(local_addr=local_addr, remote_addr=remote_addr, |
| 847 | family=family, proto=proto, flags=flags, |
| 848 | reuse_address=reuse_address, reuse_port=reuse_port, |
| 849 | allow_broadcast=allow_broadcast) |
| 850 | problems = ', '.join( |
| 851 | '{}={}'.format(k, v) for k, v in opts.items() if v) |
| 852 | raise ValueError( |
| 853 | 'socket modifier keyword arguments can not be used ' |
| 854 | 'when sock is specified. ({})'.format(problems)) |
| 855 | sock.setblocking(False) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 856 | r_addr = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 857 | else: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 858 | if not (local_addr or remote_addr): |
| 859 | if family == 0: |
| 860 | raise ValueError('unexpected address family') |
| 861 | addr_pairs_info = (((family, proto), (None, None)),) |
| 862 | else: |
| 863 | # join address by (family, protocol) |
| 864 | addr_infos = collections.OrderedDict() |
| 865 | for idx, addr in ((0, local_addr), (1, remote_addr)): |
| 866 | if addr is not None: |
| 867 | assert isinstance(addr, tuple) and len(addr) == 2, ( |
| 868 | '2-tuple is expected') |
| 869 | |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 870 | infos = yield from _ensure_resolved( |
| 871 | addr, family=family, type=socket.SOCK_DGRAM, |
| 872 | proto=proto, flags=flags, loop=self) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 873 | if not infos: |
| 874 | raise OSError('getaddrinfo() returned empty list') |
| 875 | |
| 876 | for fam, _, pro, _, address in infos: |
| 877 | key = (fam, pro) |
| 878 | if key not in addr_infos: |
| 879 | addr_infos[key] = [None, None] |
| 880 | addr_infos[key][idx] = address |
| 881 | |
| 882 | # each addr has to have info for each (family, proto) pair |
| 883 | addr_pairs_info = [ |
| 884 | (key, addr_pair) for key, addr_pair in addr_infos.items() |
| 885 | if not ((local_addr and addr_pair[0] is None) or |
| 886 | (remote_addr and addr_pair[1] is None))] |
| 887 | |
| 888 | if not addr_pairs_info: |
| 889 | raise ValueError('can not get address information') |
| 890 | |
| 891 | exceptions = [] |
| 892 | |
| 893 | if reuse_address is None: |
| 894 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 895 | |
| 896 | for ((family, proto), |
| 897 | (local_address, remote_address)) in addr_pairs_info: |
| 898 | sock = None |
| 899 | r_addr = None |
| 900 | try: |
| 901 | sock = socket.socket( |
| 902 | family=family, type=socket.SOCK_DGRAM, proto=proto) |
| 903 | if reuse_address: |
| 904 | sock.setsockopt( |
| 905 | socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 906 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 907 | _set_reuseport(sock) |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 908 | if allow_broadcast: |
| 909 | sock.setsockopt( |
| 910 | socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 911 | sock.setblocking(False) |
| 912 | |
| 913 | if local_addr: |
| 914 | sock.bind(local_address) |
| 915 | if remote_addr: |
| 916 | yield from self.sock_connect(sock, remote_address) |
| 917 | r_addr = remote_address |
| 918 | except OSError as exc: |
| 919 | if sock is not None: |
| 920 | sock.close() |
| 921 | exceptions.append(exc) |
| 922 | except: |
| 923 | if sock is not None: |
| 924 | sock.close() |
| 925 | raise |
| 926 | else: |
| 927 | break |
| 928 | else: |
| 929 | raise exceptions[0] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 930 | |
| 931 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 932 | waiter = self.create_future() |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 933 | transport = self._make_datagram_transport( |
| 934 | sock, protocol, r_addr, waiter) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 935 | if self._debug: |
| 936 | if local_addr: |
| 937 | logger.info("Datagram endpoint local_addr=%r remote_addr=%r " |
| 938 | "created: (%r, %r)", |
| 939 | local_addr, remote_addr, transport, protocol) |
| 940 | else: |
| 941 | logger.debug("Datagram endpoint remote_addr=%r created: " |
| 942 | "(%r, %r)", |
| 943 | remote_addr, transport, protocol) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 944 | |
| 945 | try: |
| 946 | yield from waiter |
| 947 | except: |
| 948 | transport.close() |
| 949 | raise |
| 950 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 951 | return transport, protocol |
| 952 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 953 | @coroutine |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 954 | def _create_server_getaddrinfo(self, host, port, family, flags): |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 955 | infos = yield from _ensure_resolved((host, port), family=family, |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 956 | type=socket.SOCK_STREAM, |
Yury Selivanov | f1c6fa9 | 2016-06-08 12:33:31 -0400 | [diff] [blame] | 957 | flags=flags, loop=self) |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 958 | if not infos: |
| 959 | raise OSError('getaddrinfo({!r}) returned empty list'.format(host)) |
| 960 | return infos |
| 961 | |
| 962 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 963 | def create_server(self, protocol_factory, host=None, port=None, |
| 964 | *, |
| 965 | family=socket.AF_UNSPEC, |
| 966 | flags=socket.AI_PASSIVE, |
| 967 | sock=None, |
| 968 | backlog=100, |
| 969 | ssl=None, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 970 | reuse_address=None, |
| 971 | reuse_port=None): |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 972 | """Create a TCP server. |
| 973 | |
| 974 | The host parameter can be a string, in that case the TCP server is bound |
| 975 | to host and port. |
| 976 | |
| 977 | 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] | 978 | the TCP server is bound to all hosts of the sequence. If a host |
| 979 | appears multiple times (possibly indirectly e.g. when hostnames |
| 980 | resolve to the same IP address), the server is only bound once to that |
| 981 | host. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 982 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 983 | Return a Server object which can be used to stop the service. |
Victor Stinner | d143209 | 2014-06-19 17:11:49 +0200 | [diff] [blame] | 984 | |
| 985 | This method is a coroutine. |
| 986 | """ |
Guido van Rossum | 28dff0d | 2013-11-01 14:22:30 -0700 | [diff] [blame] | 987 | if isinstance(ssl, bool): |
| 988 | raise TypeError('ssl argument must be an SSLContext or None') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 989 | if host is not None or port is not None: |
| 990 | if sock is not None: |
| 991 | raise ValueError( |
| 992 | 'host/port and sock can not be specified at the same time') |
| 993 | |
| 994 | AF_INET6 = getattr(socket, 'AF_INET6', 0) |
| 995 | if reuse_address is None: |
| 996 | reuse_address = os.name == 'posix' and sys.platform != 'cygwin' |
| 997 | sockets = [] |
| 998 | if host == '': |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 999 | hosts = [None] |
| 1000 | elif (isinstance(host, str) or |
Serhiy Storchaka | 2e576f5 | 2017-04-24 09:05:00 +0300 | [diff] [blame] | 1001 | not isinstance(host, collections.abc.Iterable)): |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1002 | hosts = [host] |
| 1003 | else: |
| 1004 | hosts = host |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1005 | |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 1006 | fs = [self._create_server_getaddrinfo(host, port, family=family, |
| 1007 | flags=flags) |
| 1008 | for host in hosts] |
| 1009 | infos = yield from tasks.gather(*fs, loop=self) |
Yury Selivanov | e076ffb | 2016-03-02 11:17:01 -0500 | [diff] [blame] | 1010 | infos = set(itertools.chain.from_iterable(infos)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1011 | |
| 1012 | completed = False |
| 1013 | try: |
| 1014 | for res in infos: |
| 1015 | af, socktype, proto, canonname, sa = res |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1016 | try: |
| 1017 | sock = socket.socket(af, socktype, proto) |
| 1018 | except socket.error: |
| 1019 | # Assume it's a bad family/type/protocol combination. |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 1020 | if self._debug: |
| 1021 | logger.warning('create_server() failed to create ' |
| 1022 | 'socket.socket(%r, %r, %r)', |
| 1023 | af, socktype, proto, exc_info=True) |
Guido van Rossum | 32e4685 | 2013-10-19 17:04:25 -0700 | [diff] [blame] | 1024 | continue |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1025 | sockets.append(sock) |
| 1026 | if reuse_address: |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 1027 | sock.setsockopt( |
| 1028 | socket.SOL_SOCKET, socket.SO_REUSEADDR, True) |
| 1029 | if reuse_port: |
Yury Selivanov | 5587d7c | 2016-09-15 15:45:07 -0400 | [diff] [blame] | 1030 | _set_reuseport(sock) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1031 | # Disable IPv4/IPv6 dual stack support (enabled by |
| 1032 | # default on Linux) which makes a single socket |
| 1033 | # listen on both address families. |
| 1034 | if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'): |
| 1035 | sock.setsockopt(socket.IPPROTO_IPV6, |
| 1036 | socket.IPV6_V6ONLY, |
| 1037 | True) |
| 1038 | try: |
| 1039 | sock.bind(sa) |
| 1040 | except OSError as err: |
| 1041 | raise OSError(err.errno, 'error while attempting ' |
| 1042 | 'to bind on address %r: %s' |
Serhiy Storchaka | 5affd23 | 2017-04-05 09:37:24 +0300 | [diff] [blame] | 1043 | % (sa, err.strerror.lower())) from None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1044 | completed = True |
| 1045 | finally: |
| 1046 | if not completed: |
| 1047 | for sock in sockets: |
| 1048 | sock.close() |
| 1049 | else: |
| 1050 | if sock is None: |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1051 | raise ValueError('Neither host/port nor sock were specified') |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 1052 | if not _is_stream_socket(sock): |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1053 | raise ValueError( |
Yury Selivanov | dab0584 | 2016-11-21 17:47:27 -0500 | [diff] [blame] | 1054 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1055 | sockets = [sock] |
| 1056 | |
| 1057 | server = Server(self, sockets) |
| 1058 | for sock in sockets: |
| 1059 | sock.listen(backlog) |
| 1060 | sock.setblocking(False) |
Yury Selivanov | a1b0e7d | 2016-09-15 14:13:15 -0400 | [diff] [blame] | 1061 | self._start_serving(protocol_factory, sock, ssl, server, backlog) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 1062 | if self._debug: |
| 1063 | logger.info("%r is serving", server) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1064 | return server |
| 1065 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1066 | @coroutine |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1067 | def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None): |
| 1068 | """Handle an accepted connection. |
| 1069 | |
| 1070 | This is used by servers that accept connections outside of |
| 1071 | asyncio but that use asyncio to handle connections. |
| 1072 | |
| 1073 | This method is a coroutine. When completed, the coroutine |
| 1074 | returns a (transport, protocol) pair. |
| 1075 | """ |
Yury Selivanov | a1a8b7d | 2016-11-09 15:47:00 -0500 | [diff] [blame] | 1076 | if not _is_stream_socket(sock): |
| 1077 | raise ValueError( |
| 1078 | 'A Stream Socket was expected, got {!r}'.format(sock)) |
| 1079 | |
Yury Selivanov | 252e9ed | 2016-07-12 18:23:10 -0400 | [diff] [blame] | 1080 | transport, protocol = yield from self._create_connection_transport( |
| 1081 | sock, protocol_factory, ssl, '', server_side=True) |
| 1082 | if self._debug: |
| 1083 | # Get the socket from the transport because SSL transport closes |
| 1084 | # the old socket and creates a new SSL socket |
| 1085 | sock = transport.get_extra_info('socket') |
| 1086 | logger.debug("%r handled: (%r, %r)", sock, transport, protocol) |
| 1087 | return transport, protocol |
| 1088 | |
| 1089 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1090 | def connect_read_pipe(self, protocol_factory, pipe): |
| 1091 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1092 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1093 | transport = self._make_read_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1094 | |
| 1095 | try: |
| 1096 | yield from waiter |
| 1097 | except: |
| 1098 | transport.close() |
| 1099 | raise |
| 1100 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1101 | if self._debug: |
| 1102 | logger.debug('Read pipe %r connected: (%r, %r)', |
| 1103 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1104 | return transport, protocol |
| 1105 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1106 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1107 | def connect_write_pipe(self, protocol_factory, pipe): |
| 1108 | protocol = protocol_factory() |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 1109 | waiter = self.create_future() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1110 | transport = self._make_write_pipe_transport(pipe, protocol, waiter) |
Victor Stinner | 2596dd0 | 2015-01-26 11:02:18 +0100 | [diff] [blame] | 1111 | |
| 1112 | try: |
| 1113 | yield from waiter |
| 1114 | except: |
| 1115 | transport.close() |
| 1116 | raise |
| 1117 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1118 | if self._debug: |
| 1119 | logger.debug('Write pipe %r connected: (%r, %r)', |
| 1120 | pipe.fileno(), transport, protocol) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1121 | return transport, protocol |
| 1122 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1123 | def _log_subprocess(self, msg, stdin, stdout, stderr): |
| 1124 | info = [msg] |
| 1125 | if stdin is not None: |
| 1126 | info.append('stdin=%s' % _format_pipe(stdin)) |
| 1127 | if stdout is not None and stderr == subprocess.STDOUT: |
| 1128 | info.append('stdout=stderr=%s' % _format_pipe(stdout)) |
| 1129 | else: |
| 1130 | if stdout is not None: |
| 1131 | info.append('stdout=%s' % _format_pipe(stdout)) |
| 1132 | if stderr is not None: |
| 1133 | info.append('stderr=%s' % _format_pipe(stderr)) |
| 1134 | logger.debug(' '.join(info)) |
| 1135 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1136 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1137 | def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE, |
| 1138 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 1139 | universal_newlines=False, shell=True, bufsize=0, |
| 1140 | **kwargs): |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1141 | if not isinstance(cmd, (bytes, str)): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1142 | raise ValueError("cmd must be a string") |
| 1143 | if universal_newlines: |
| 1144 | raise ValueError("universal_newlines must be False") |
| 1145 | if not shell: |
Victor Stinner | 323748e | 2014-01-31 12:28:30 +0100 | [diff] [blame] | 1146 | raise ValueError("shell must be True") |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1147 | if bufsize != 0: |
| 1148 | raise ValueError("bufsize must be 0") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1149 | protocol = protocol_factory() |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1150 | if self._debug: |
| 1151 | # don't log parameters: they may contain sensitive information |
| 1152 | # (password) and may be too long |
| 1153 | debug_log = 'run shell command %r' % cmd |
| 1154 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1155 | transport = yield from self._make_subprocess_transport( |
| 1156 | protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1157 | if self._debug: |
Vinay Sajip | dd917f8 | 2016-08-31 08:22:29 +0100 | [diff] [blame] | 1158 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1159 | return transport, protocol |
| 1160 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 1161 | @coroutine |
Yury Selivanov | 5779752 | 2014-02-18 22:56:15 -0500 | [diff] [blame] | 1162 | def subprocess_exec(self, protocol_factory, program, *args, |
| 1163 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 1164 | stderr=subprocess.PIPE, universal_newlines=False, |
| 1165 | shell=False, bufsize=0, **kwargs): |
Victor Stinner | e623a12 | 2014-01-29 14:35:15 -0800 | [diff] [blame] | 1166 | if universal_newlines: |
| 1167 | raise ValueError("universal_newlines must be False") |
| 1168 | if shell: |
| 1169 | raise ValueError("shell must be False") |
| 1170 | if bufsize != 0: |
| 1171 | raise ValueError("bufsize must be 0") |
Victor Stinner | 20e0743 | 2014-02-11 11:44:56 +0100 | [diff] [blame] | 1172 | popen_args = (program,) + args |
| 1173 | for arg in popen_args: |
| 1174 | if not isinstance(arg, (str, bytes)): |
| 1175 | raise TypeError("program arguments must be " |
| 1176 | "a bytes or text string, not %s" |
| 1177 | % type(arg).__name__) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1178 | protocol = protocol_factory() |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1179 | if self._debug: |
| 1180 | # don't log parameters: they may contain sensitive information |
| 1181 | # (password) and may be too long |
| 1182 | debug_log = 'execute program %r' % program |
| 1183 | self._log_subprocess(debug_log, stdin, stdout, stderr) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1184 | transport = yield from self._make_subprocess_transport( |
Yury Selivanov | 5779752 | 2014-02-18 22:56:15 -0500 | [diff] [blame] | 1185 | protocol, popen_args, False, stdin, stdout, stderr, |
| 1186 | bufsize, **kwargs) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1187 | if self._debug: |
Vinay Sajip | dd917f8 | 2016-08-31 08:22:29 +0100 | [diff] [blame] | 1188 | logger.info('%s: %r', debug_log, transport) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1189 | return transport, protocol |
| 1190 | |
Yury Selivanov | 7ed7ce6 | 2016-05-16 15:20:38 -0400 | [diff] [blame] | 1191 | def get_exception_handler(self): |
| 1192 | """Return an exception handler, or None if the default one is in use. |
| 1193 | """ |
| 1194 | return self._exception_handler |
| 1195 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1196 | def set_exception_handler(self, handler): |
| 1197 | """Set handler as the new event loop exception handler. |
| 1198 | |
| 1199 | If handler is None, the default exception handler will |
| 1200 | be set. |
| 1201 | |
| 1202 | If handler is a callable object, it should have a |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1203 | signature matching '(loop, context)', where 'loop' |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1204 | will be a reference to the active event loop, 'context' |
| 1205 | will be a dict object (see `call_exception_handler()` |
| 1206 | documentation for details about context). |
| 1207 | """ |
| 1208 | if handler is not None and not callable(handler): |
| 1209 | raise TypeError('A callable object or None is expected, ' |
| 1210 | 'got {!r}'.format(handler)) |
| 1211 | self._exception_handler = handler |
| 1212 | |
| 1213 | def default_exception_handler(self, context): |
| 1214 | """Default exception handler. |
| 1215 | |
| 1216 | This is called when an exception occurs and no exception |
| 1217 | handler is set, and can be called by a custom exception |
| 1218 | handler that wants to defer to the default behavior. |
| 1219 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1220 | The context parameter has the same meaning as in |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1221 | `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 Stinner | ff018e4 | 2015-01-28 00:30:40 +0100 | [diff] [blame] | 1233 | if ('source_traceback' not in context |
| 1234 | and self._current_handle is not None |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1235 | and self._current_handle._source_traceback): |
| 1236 | context['handle_traceback'] = self._current_handle._source_traceback |
| 1237 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1238 | log_lines = [message] |
| 1239 | for key in sorted(context): |
| 1240 | if key in {'message', 'exception'}: |
| 1241 | continue |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1242 | 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 Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1247 | 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 Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 1251 | else: |
| 1252 | value = repr(value) |
| 1253 | log_lines.append('{}: {}'.format(key, value)) |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1254 | |
| 1255 | logger.error('\n'.join(log_lines), exc_info=exc_info) |
| 1256 | |
| 1257 | def call_exception_handler(self, context): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1258 | """Call the current event loop's exception handler. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1259 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1260 | The context argument is a dict containing the following keys: |
| 1261 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1262 | - '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 Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 1268 | - 'socket' (optional): Socket instance; |
| 1269 | - 'asyncgen' (optional): Asynchronous generator that caused |
| 1270 | the exception. |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1271 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1272 | 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 Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1276 | `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 Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1300 | # Guard 'default_exception_handler' in case it is |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 1301 | # 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1307 | def _add_callback(self, handle): |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1308 | """Add a Handle to _scheduled (TimerHandle) or _ready.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1309 | assert isinstance(handle, events.Handle), 'A Handle is required here' |
| 1310 | if handle._cancelled: |
| 1311 | return |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1312 | assert not isinstance(handle, events.TimerHandle) |
| 1313 | self._ready.append(handle) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1314 | |
| 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 Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1320 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1325 | 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 Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1332 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1333 | 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 Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1337 | # Remove delayed calls that were cancelled if their number |
| 1338 | # is too high |
| 1339 | new_scheduled = [] |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1340 | for handle in self._scheduled: |
| 1341 | if handle._cancelled: |
| 1342 | handle._scheduled = False |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1343 | else: |
| 1344 | new_scheduled.append(handle) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1345 | |
Victor Stinner | 68da8fc | 2014-09-30 18:08:36 +0200 | [diff] [blame] | 1346 | heapq.heapify(new_scheduled) |
| 1347 | self._scheduled = new_scheduled |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1348 | self._timer_cancelled_count = 0 |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1349 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1355 | |
| 1356 | timeout = None |
Guido van Rossum | 41f69f4 | 2015-11-19 13:28:47 -0800 | [diff] [blame] | 1357 | if self._ready or self._stopping: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1358 | timeout = 0 |
| 1359 | elif self._scheduled: |
| 1360 | # Compute the desired timeout. |
| 1361 | when = self._scheduled[0]._when |
Guido van Rossum | 3d1bc60 | 2014-05-10 15:47:15 -0700 | [diff] [blame] | 1362 | timeout = max(0, when - self.time()) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1363 | |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1364 | if self._debug and timeout != 0: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1365 | t0 = self.time() |
| 1366 | event_list = self._selector.select(timeout) |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1367 | dt = self.time() - t0 |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1368 | if dt >= 1.0: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1369 | level = logging.INFO |
| 1370 | else: |
| 1371 | level = logging.DEBUG |
Victor Stinner | 770e48d | 2014-07-11 11:58:33 +0200 | [diff] [blame] | 1372 | 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 Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1384 | else: |
Victor Stinner | 22463aa | 2014-01-20 23:56:40 +0100 | [diff] [blame] | 1385 | event_list = self._selector.select(timeout) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1386 | self._process_events(event_list) |
| 1387 | |
| 1388 | # Handle 'later' callbacks that are ready. |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1389 | end_time = self.time() + self._clock_resolution |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1390 | while self._scheduled: |
| 1391 | handle = self._scheduled[0] |
Victor Stinner | ed1654f | 2014-02-10 23:42:32 +0100 | [diff] [blame] | 1392 | if handle._when >= end_time: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1393 | break |
| 1394 | handle = heapq.heappop(self._scheduled) |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 1395 | handle._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1396 | 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 Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 1403 | # Use an idiom that is thread-safe without using locks. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1404 | ntodo = len(self._ready) |
| 1405 | for i in range(ntodo): |
| 1406 | handle = self._ready.popleft() |
Victor Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1407 | if handle._cancelled: |
| 1408 | continue |
| 1409 | if self._debug: |
Victor Stinner | 9b524d5 | 2015-01-26 11:05:12 +0100 | [diff] [blame] | 1410 | 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 Stinner | 0e6f52a | 2014-06-20 17:34:15 +0200 | [diff] [blame] | 1420 | else: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1421 | handle._run() |
| 1422 | handle = None # Needed to break cycles when an exception occurs. |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1423 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1424 | 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 Selivanov | 996083d | 2015-08-04 15:37:24 -0400 | [diff] [blame] | 1432 | if self._coroutine_wrapper_set == enabled: |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1433 | 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 Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 1457 | def get_debug(self): |
| 1458 | return self._debug |
| 1459 | |
| 1460 | def set_debug(self, enabled): |
| 1461 | self._debug = enabled |
Yury Selivanov | 1af2bf7 | 2015-05-11 22:27:25 -0400 | [diff] [blame] | 1462 | |
Yury Selivanov | e8944cb | 2015-05-12 11:43:04 -0400 | [diff] [blame] | 1463 | if self.is_running(): |
| 1464 | self._set_coroutine_wrapper(enabled) |