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