Yury Selivanov | dec1a45 | 2014-02-18 22:27:48 -0500 | [diff] [blame] | 1 | """Selector event loop for Unix with signal handling.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 2 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 3 | import errno |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 4 | import os |
| 5 | import signal |
| 6 | import socket |
| 7 | import stat |
| 8 | import subprocess |
| 9 | import sys |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 10 | import threading |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 11 | import warnings |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 12 | |
| 13 | |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 14 | from . import base_events |
Guido van Rossum | 5969128 | 2013-10-30 14:52:03 -0700 | [diff] [blame] | 15 | from . import base_subprocess |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 16 | from . import constants |
Guido van Rossum | e36fcde | 2014-11-14 11:45:47 -0800 | [diff] [blame] | 17 | from . import coroutines |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 18 | from . import events |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 19 | from . import futures |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 20 | from . import selector_events |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 21 | from . import selectors |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 22 | from . import transports |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 23 | from .coroutines import coroutine |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 24 | from .log import logger |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 25 | |
| 26 | |
Victor Stinner | 915bcb0 | 2014-02-01 22:49:59 +0100 | [diff] [blame] | 27 | __all__ = ['SelectorEventLoop', |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 28 | 'AbstractChildWatcher', 'SafeChildWatcher', |
| 29 | 'FastChildWatcher', 'DefaultEventLoopPolicy', |
| 30 | ] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 31 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 32 | if sys.platform == 'win32': # pragma: no cover |
| 33 | raise ImportError('Signals are not really supported on Windows') |
| 34 | |
| 35 | |
Victor Stinner | fe5649c | 2014-07-17 22:43:40 +0200 | [diff] [blame] | 36 | def _sighandler_noop(signum, frame): |
| 37 | """Dummy signal handler.""" |
| 38 | pass |
| 39 | |
| 40 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 41 | class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop): |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 42 | """Unix event loop. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 43 | |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 44 | Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 45 | """ |
| 46 | |
| 47 | def __init__(self, selector=None): |
| 48 | super().__init__(selector) |
| 49 | self._signal_handlers = {} |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 50 | |
| 51 | def _socketpair(self): |
| 52 | return socket.socketpair() |
| 53 | |
Guido van Rossum | 0b69fbc | 2013-11-06 20:25:50 -0800 | [diff] [blame] | 54 | def close(self): |
Victor Stinner | f328c7d | 2014-06-23 01:02:37 +0200 | [diff] [blame] | 55 | super().close() |
Guido van Rossum | 0b69fbc | 2013-11-06 20:25:50 -0800 | [diff] [blame] | 56 | for sig in list(self._signal_handlers): |
| 57 | self.remove_signal_handler(sig) |
Guido van Rossum | 0b69fbc | 2013-11-06 20:25:50 -0800 | [diff] [blame] | 58 | |
Victor Stinner | fe5649c | 2014-07-17 22:43:40 +0200 | [diff] [blame] | 59 | def _process_self_data(self, data): |
| 60 | for signum in data: |
| 61 | if not signum: |
| 62 | # ignore null bytes written by _write_to_self() |
| 63 | continue |
| 64 | self._handle_signal(signum) |
| 65 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 66 | def add_signal_handler(self, sig, callback, *args): |
| 67 | """Add a handler for a signal. UNIX only. |
| 68 | |
| 69 | Raise ValueError if the signal number is invalid or uncatchable. |
| 70 | Raise RuntimeError if there is a problem setting up the handler. |
| 71 | """ |
Victor Stinner | 2d99d93 | 2014-11-20 15:03:52 +0100 | [diff] [blame] | 72 | if (coroutines.iscoroutine(callback) |
| 73 | or coroutines.iscoroutinefunction(callback)): |
Victor Stinner | 15cc678 | 2015-01-09 00:09:10 +0100 | [diff] [blame] | 74 | raise TypeError("coroutines cannot be used " |
| 75 | "with add_signal_handler()") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 76 | self._check_signal(sig) |
Victor Stinner | e80bf0d | 2014-12-04 23:07:47 +0100 | [diff] [blame] | 77 | self._check_closed() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 78 | try: |
| 79 | # set_wakeup_fd() raises ValueError if this is not the |
| 80 | # main thread. By calling it early we ensure that an |
| 81 | # event loop running in another thread cannot add a signal |
| 82 | # handler. |
| 83 | signal.set_wakeup_fd(self._csock.fileno()) |
Victor Stinner | c4c4649 | 2014-07-23 18:21:45 +0200 | [diff] [blame] | 84 | except (ValueError, OSError) as exc: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 85 | raise RuntimeError(str(exc)) |
| 86 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 87 | handle = events.Handle(callback, args, self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 88 | self._signal_handlers[sig] = handle |
| 89 | |
| 90 | try: |
Victor Stinner | fe5649c | 2014-07-17 22:43:40 +0200 | [diff] [blame] | 91 | # Register a dummy signal handler to ask Python to write the signal |
| 92 | # number in the wakup file descriptor. _process_self_data() will |
| 93 | # read signal numbers from this file descriptor to handle signals. |
| 94 | signal.signal(sig, _sighandler_noop) |
| 95 | |
Charles-François Natali | 74e7cf3 | 2013-12-05 22:47:19 +0100 | [diff] [blame] | 96 | # Set SA_RESTART to limit EINTR occurrences. |
| 97 | signal.siginterrupt(sig, False) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 98 | except OSError as exc: |
| 99 | del self._signal_handlers[sig] |
| 100 | if not self._signal_handlers: |
| 101 | try: |
| 102 | signal.set_wakeup_fd(-1) |
Victor Stinner | c4c4649 | 2014-07-23 18:21:45 +0200 | [diff] [blame] | 103 | except (ValueError, OSError) as nexc: |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 104 | logger.info('set_wakeup_fd(-1) failed: %s', nexc) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 105 | |
| 106 | if exc.errno == errno.EINVAL: |
| 107 | raise RuntimeError('sig {} cannot be caught'.format(sig)) |
| 108 | else: |
| 109 | raise |
| 110 | |
Victor Stinner | fe5649c | 2014-07-17 22:43:40 +0200 | [diff] [blame] | 111 | def _handle_signal(self, sig): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 112 | """Internal helper that is the actual signal handler.""" |
| 113 | handle = self._signal_handlers.get(sig) |
| 114 | if handle is None: |
| 115 | return # Assume it's some race condition. |
| 116 | if handle._cancelled: |
| 117 | self.remove_signal_handler(sig) # Remove it properly. |
| 118 | else: |
| 119 | self._add_callback_signalsafe(handle) |
| 120 | |
| 121 | def remove_signal_handler(self, sig): |
| 122 | """Remove a handler for a signal. UNIX only. |
| 123 | |
| 124 | Return True if a signal handler was removed, False if not. |
| 125 | """ |
| 126 | self._check_signal(sig) |
| 127 | try: |
| 128 | del self._signal_handlers[sig] |
| 129 | except KeyError: |
| 130 | return False |
| 131 | |
| 132 | if sig == signal.SIGINT: |
| 133 | handler = signal.default_int_handler |
| 134 | else: |
| 135 | handler = signal.SIG_DFL |
| 136 | |
| 137 | try: |
| 138 | signal.signal(sig, handler) |
| 139 | except OSError as exc: |
| 140 | if exc.errno == errno.EINVAL: |
| 141 | raise RuntimeError('sig {} cannot be caught'.format(sig)) |
| 142 | else: |
| 143 | raise |
| 144 | |
| 145 | if not self._signal_handlers: |
| 146 | try: |
| 147 | signal.set_wakeup_fd(-1) |
Victor Stinner | c4c4649 | 2014-07-23 18:21:45 +0200 | [diff] [blame] | 148 | except (ValueError, OSError) as exc: |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 149 | logger.info('set_wakeup_fd(-1) failed: %s', exc) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 150 | |
| 151 | return True |
| 152 | |
| 153 | def _check_signal(self, sig): |
| 154 | """Internal helper to validate a signal. |
| 155 | |
| 156 | Raise ValueError if the signal number is invalid or uncatchable. |
| 157 | Raise RuntimeError if there is a problem setting up the handler. |
| 158 | """ |
| 159 | if not isinstance(sig, int): |
| 160 | raise TypeError('sig must be an int, not {!r}'.format(sig)) |
| 161 | |
| 162 | if not (1 <= sig < signal.NSIG): |
| 163 | raise ValueError( |
| 164 | 'sig {} out of range(1, {})'.format(sig, signal.NSIG)) |
| 165 | |
| 166 | def _make_read_pipe_transport(self, pipe, protocol, waiter=None, |
| 167 | extra=None): |
| 168 | return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra) |
| 169 | |
| 170 | def _make_write_pipe_transport(self, pipe, protocol, waiter=None, |
| 171 | extra=None): |
| 172 | return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra) |
| 173 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 174 | @coroutine |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 175 | def _make_subprocess_transport(self, protocol, args, shell, |
| 176 | stdin, stdout, stderr, bufsize, |
| 177 | extra=None, **kwargs): |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 178 | with events.get_child_watcher() as watcher: |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 179 | waiter = futures.Future(loop=self) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 180 | transp = _UnixSubprocessTransport(self, protocol, args, shell, |
| 181 | stdin, stdout, stderr, bufsize, |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 182 | waiter=waiter, extra=extra, |
| 183 | **kwargs) |
| 184 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 185 | watcher.add_child_handler(transp.get_pid(), |
| 186 | self._child_watcher_callback, transp) |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 187 | try: |
| 188 | yield from waiter |
Victor Stinner | 5d44c08 | 2015-02-02 18:36:31 +0100 | [diff] [blame^] | 189 | except Exception as exc: |
| 190 | # Workaround CPython bug #23353: using yield/yield-from in an |
| 191 | # except block of a generator doesn't clear properly |
| 192 | # sys.exc_info() |
| 193 | err = exc |
| 194 | else: |
| 195 | err = None |
| 196 | |
| 197 | if err is not None: |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 198 | transp.close() |
Victor Stinner | 1241ecc | 2015-01-30 00:16:14 +0100 | [diff] [blame] | 199 | yield from transp._wait() |
Victor Stinner | 5d44c08 | 2015-02-02 18:36:31 +0100 | [diff] [blame^] | 200 | raise err |
Guido van Rossum | 4835f17 | 2014-01-10 13:28:59 -0800 | [diff] [blame] | 201 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 202 | return transp |
| 203 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 204 | def _child_watcher_callback(self, pid, returncode, transp): |
| 205 | self.call_soon_threadsafe(transp._process_exited, returncode) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 206 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 207 | @coroutine |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 208 | def create_unix_connection(self, protocol_factory, path, *, |
| 209 | ssl=None, sock=None, |
| 210 | server_hostname=None): |
| 211 | assert server_hostname is None or isinstance(server_hostname, str) |
| 212 | if ssl: |
| 213 | if server_hostname is None: |
| 214 | raise ValueError( |
| 215 | 'you have to pass server_hostname when using ssl') |
| 216 | else: |
| 217 | if server_hostname is not None: |
| 218 | raise ValueError('server_hostname is only meaningful with ssl') |
| 219 | |
| 220 | if path is not None: |
| 221 | if sock is not None: |
| 222 | raise ValueError( |
| 223 | 'path and sock can not be specified at the same time') |
| 224 | |
Victor Stinner | 79a2952 | 2014-02-19 01:45:59 +0100 | [diff] [blame] | 225 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 226 | try: |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 227 | sock.setblocking(False) |
| 228 | yield from self.sock_connect(sock, path) |
Victor Stinner | 79a2952 | 2014-02-19 01:45:59 +0100 | [diff] [blame] | 229 | except: |
| 230 | sock.close() |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 231 | raise |
| 232 | |
| 233 | else: |
| 234 | if sock is None: |
| 235 | raise ValueError('no path and sock were specified') |
| 236 | sock.setblocking(False) |
| 237 | |
| 238 | transport, protocol = yield from self._create_connection_transport( |
| 239 | sock, protocol_factory, ssl, server_hostname) |
| 240 | return transport, protocol |
| 241 | |
Victor Stinner | f951d28 | 2014-06-29 00:46:45 +0200 | [diff] [blame] | 242 | @coroutine |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 243 | def create_unix_server(self, protocol_factory, path=None, *, |
| 244 | sock=None, backlog=100, ssl=None): |
| 245 | if isinstance(ssl, bool): |
| 246 | raise TypeError('ssl argument must be an SSLContext or None') |
| 247 | |
| 248 | if path is not None: |
Victor Stinner | 1fd03a4 | 2014-04-07 11:18:54 +0200 | [diff] [blame] | 249 | if sock is not None: |
| 250 | raise ValueError( |
| 251 | 'path and sock can not be specified at the same time') |
| 252 | |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 253 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 254 | |
| 255 | try: |
| 256 | sock.bind(path) |
| 257 | except OSError as exc: |
Victor Stinner | 79a2952 | 2014-02-19 01:45:59 +0100 | [diff] [blame] | 258 | sock.close() |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 259 | if exc.errno == errno.EADDRINUSE: |
| 260 | # Let's improve the error message by adding |
| 261 | # with what exact address it occurs. |
| 262 | msg = 'Address {!r} is already in use'.format(path) |
| 263 | raise OSError(errno.EADDRINUSE, msg) from None |
| 264 | else: |
| 265 | raise |
Victor Stinner | 223a624 | 2014-06-04 00:11:52 +0200 | [diff] [blame] | 266 | except: |
| 267 | sock.close() |
| 268 | raise |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 269 | else: |
| 270 | if sock is None: |
| 271 | raise ValueError( |
| 272 | 'path was not specified, and no sock specified') |
| 273 | |
| 274 | if sock.family != socket.AF_UNIX: |
| 275 | raise ValueError( |
| 276 | 'A UNIX Domain Socket was expected, got {!r}'.format(sock)) |
| 277 | |
| 278 | server = base_events.Server(self, [sock]) |
| 279 | sock.listen(backlog) |
| 280 | sock.setblocking(False) |
| 281 | self._start_serving(protocol_factory, sock, ssl, server) |
| 282 | return server |
| 283 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 284 | |
Victor Stinner | f2ed889 | 2014-07-29 23:08:00 +0200 | [diff] [blame] | 285 | if hasattr(os, 'set_blocking'): |
| 286 | def _set_nonblocking(fd): |
| 287 | os.set_blocking(fd, False) |
| 288 | else: |
Yury Selivanov | 8c0e0ab | 2014-09-24 23:21:39 -0400 | [diff] [blame] | 289 | import fcntl |
| 290 | |
Victor Stinner | f2ed889 | 2014-07-29 23:08:00 +0200 | [diff] [blame] | 291 | def _set_nonblocking(fd): |
| 292 | flags = fcntl.fcntl(fd, fcntl.F_GETFL) |
| 293 | flags = flags | os.O_NONBLOCK |
| 294 | fcntl.fcntl(fd, fcntl.F_SETFL, flags) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 295 | |
| 296 | |
| 297 | class _UnixReadPipeTransport(transports.ReadTransport): |
| 298 | |
Yury Selivanov | dec1a45 | 2014-02-18 22:27:48 -0500 | [diff] [blame] | 299 | max_size = 256 * 1024 # max bytes we read in one event loop iteration |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 300 | |
| 301 | def __init__(self, loop, pipe, protocol, waiter=None, extra=None): |
| 302 | super().__init__(extra) |
| 303 | self._extra['pipe'] = pipe |
| 304 | self._loop = loop |
| 305 | self._pipe = pipe |
| 306 | self._fileno = pipe.fileno() |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 307 | mode = os.fstat(self._fileno).st_mode |
Guido van Rossum | 02757ea | 2014-01-10 13:30:04 -0800 | [diff] [blame] | 308 | if not (stat.S_ISFIFO(mode) or |
| 309 | stat.S_ISSOCK(mode) or |
| 310 | stat.S_ISCHR(mode)): |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 311 | raise ValueError("Pipe transport is for pipes/sockets only.") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 312 | _set_nonblocking(self._fileno) |
| 313 | self._protocol = protocol |
| 314 | self._closing = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 315 | self._loop.call_soon(self._protocol.connection_made, self) |
Victor Stinner | 2934262 | 2015-01-29 14:15:19 +0100 | [diff] [blame] | 316 | # only start reading when connection_made() has been called |
| 317 | self._loop.call_soon(self._loop.add_reader, |
| 318 | self._fileno, self._read_ready) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 319 | if waiter is not None: |
Victor Stinner | f07801b | 2015-01-29 00:36:35 +0100 | [diff] [blame] | 320 | # only wake up the waiter when connection_made() has been called |
Victor Stinner | a9acbe8 | 2014-07-05 15:29:41 +0200 | [diff] [blame] | 321 | self._loop.call_soon(waiter._set_result_unless_cancelled, None) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 322 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 323 | def __repr__(self): |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 324 | info = [self.__class__.__name__] |
| 325 | if self._pipe is None: |
| 326 | info.append('closed') |
| 327 | elif self._closing: |
| 328 | info.append('closing') |
| 329 | info.append('fd=%s' % self._fileno) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 330 | if self._pipe is not None: |
| 331 | polling = selector_events._test_selector_event( |
| 332 | self._loop._selector, |
| 333 | self._fileno, selectors.EVENT_READ) |
| 334 | if polling: |
| 335 | info.append('polling') |
| 336 | else: |
| 337 | info.append('idle') |
| 338 | else: |
| 339 | info.append('closed') |
| 340 | return '<%s>' % ' '.join(info) |
| 341 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 342 | def _read_ready(self): |
| 343 | try: |
| 344 | data = os.read(self._fileno, self.max_size) |
| 345 | except (BlockingIOError, InterruptedError): |
| 346 | pass |
| 347 | except OSError as exc: |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 348 | self._fatal_error(exc, 'Fatal read error on pipe transport') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 349 | else: |
| 350 | if data: |
| 351 | self._protocol.data_received(data) |
| 352 | else: |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 353 | if self._loop.get_debug(): |
| 354 | logger.info("%r was closed by peer", self) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 355 | self._closing = True |
| 356 | self._loop.remove_reader(self._fileno) |
| 357 | self._loop.call_soon(self._protocol.eof_received) |
| 358 | self._loop.call_soon(self._call_connection_lost, None) |
| 359 | |
Guido van Rossum | 57497ad | 2013-10-18 07:58:20 -0700 | [diff] [blame] | 360 | def pause_reading(self): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 361 | self._loop.remove_reader(self._fileno) |
| 362 | |
Guido van Rossum | 57497ad | 2013-10-18 07:58:20 -0700 | [diff] [blame] | 363 | def resume_reading(self): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 364 | self._loop.add_reader(self._fileno, self._read_ready) |
| 365 | |
| 366 | def close(self): |
| 367 | if not self._closing: |
| 368 | self._close(None) |
| 369 | |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 370 | # On Python 3.3 and older, objects with a destructor part of a reference |
| 371 | # cycle are never destroyed. It's not more the case on Python 3.4 thanks |
| 372 | # to the PEP 442. |
| 373 | if sys.version_info >= (3, 4): |
| 374 | def __del__(self): |
| 375 | if self._pipe is not None: |
| 376 | warnings.warn("unclosed transport %r" % self, ResourceWarning) |
| 377 | self._pipe.close() |
| 378 | |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 379 | def _fatal_error(self, exc, message='Fatal error on pipe transport'): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 380 | # should be called by exception handler only |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 381 | if (isinstance(exc, OSError) and exc.errno == errno.EIO): |
| 382 | if self._loop.get_debug(): |
| 383 | logger.debug("%r: %s", self, message, exc_info=True) |
| 384 | else: |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 385 | self._loop.call_exception_handler({ |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 386 | 'message': message, |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 387 | 'exception': exc, |
| 388 | 'transport': self, |
| 389 | 'protocol': self._protocol, |
| 390 | }) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 391 | self._close(exc) |
| 392 | |
| 393 | def _close(self, exc): |
| 394 | self._closing = True |
| 395 | self._loop.remove_reader(self._fileno) |
| 396 | self._loop.call_soon(self._call_connection_lost, exc) |
| 397 | |
| 398 | def _call_connection_lost(self, exc): |
| 399 | try: |
| 400 | self._protocol.connection_lost(exc) |
| 401 | finally: |
| 402 | self._pipe.close() |
| 403 | self._pipe = None |
| 404 | self._protocol = None |
| 405 | self._loop = None |
| 406 | |
| 407 | |
Yury Selivanov | 3cb9914 | 2014-02-18 18:41:13 -0500 | [diff] [blame] | 408 | class _UnixWritePipeTransport(transports._FlowControlMixin, |
Guido van Rossum | 47fb97e | 2014-01-29 13:20:39 -0800 | [diff] [blame] | 409 | transports.WriteTransport): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 410 | |
| 411 | def __init__(self, loop, pipe, protocol, waiter=None, extra=None): |
Victor Stinner | 004adb9 | 2014-11-05 15:27:41 +0100 | [diff] [blame] | 412 | super().__init__(extra, loop) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 413 | self._extra['pipe'] = pipe |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 414 | self._pipe = pipe |
| 415 | self._fileno = pipe.fileno() |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 416 | mode = os.fstat(self._fileno).st_mode |
| 417 | is_socket = stat.S_ISSOCK(mode) |
Victor Stinner | 8dffc45 | 2014-01-25 15:32:06 +0100 | [diff] [blame] | 418 | if not (is_socket or |
| 419 | stat.S_ISFIFO(mode) or |
| 420 | stat.S_ISCHR(mode)): |
| 421 | raise ValueError("Pipe transport is only for " |
| 422 | "pipes, sockets and character devices") |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 423 | _set_nonblocking(self._fileno) |
| 424 | self._protocol = protocol |
| 425 | self._buffer = [] |
| 426 | self._conn_lost = 0 |
| 427 | self._closing = False # Set when close() or write_eof() called. |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 428 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 429 | self._loop.call_soon(self._protocol.connection_made, self) |
Victor Stinner | 2934262 | 2015-01-29 14:15:19 +0100 | [diff] [blame] | 430 | |
| 431 | # On AIX, the reader trick (to be notified when the read end of the |
| 432 | # socket is closed) only works for sockets. On other platforms it |
| 433 | # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.) |
| 434 | if is_socket or not sys.platform.startswith("aix"): |
| 435 | # only start reading when connection_made() has been called |
| 436 | self._loop.call_soon(self._loop.add_reader, |
| 437 | self._fileno, self._read_ready) |
| 438 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 439 | if waiter is not None: |
Victor Stinner | f07801b | 2015-01-29 00:36:35 +0100 | [diff] [blame] | 440 | # only wake up the waiter when connection_made() has been called |
Victor Stinner | a9acbe8 | 2014-07-05 15:29:41 +0200 | [diff] [blame] | 441 | self._loop.call_soon(waiter._set_result_unless_cancelled, None) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 442 | |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 443 | def __repr__(self): |
Victor Stinner | 29ad011 | 2015-01-15 00:04:21 +0100 | [diff] [blame] | 444 | info = [self.__class__.__name__] |
| 445 | if self._pipe is None: |
| 446 | info.append('closed') |
| 447 | elif self._closing: |
| 448 | info.append('closing') |
| 449 | info.append('fd=%s' % self._fileno) |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 450 | if self._pipe is not None: |
| 451 | polling = selector_events._test_selector_event( |
| 452 | self._loop._selector, |
| 453 | self._fileno, selectors.EVENT_WRITE) |
| 454 | if polling: |
| 455 | info.append('polling') |
| 456 | else: |
| 457 | info.append('idle') |
| 458 | |
| 459 | bufsize = self.get_write_buffer_size() |
| 460 | info.append('bufsize=%s' % bufsize) |
| 461 | else: |
| 462 | info.append('closed') |
| 463 | return '<%s>' % ' '.join(info) |
| 464 | |
Guido van Rossum | 47fb97e | 2014-01-29 13:20:39 -0800 | [diff] [blame] | 465 | def get_write_buffer_size(self): |
| 466 | return sum(len(data) for data in self._buffer) |
| 467 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 468 | def _read_ready(self): |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 469 | # Pipe was closed by peer. |
Victor Stinner | e912e65 | 2014-07-12 03:11:53 +0200 | [diff] [blame] | 470 | if self._loop.get_debug(): |
| 471 | logger.info("%r was closed by peer", self) |
Victor Stinner | 61b3c9b | 2014-01-31 13:04:28 +0100 | [diff] [blame] | 472 | if self._buffer: |
| 473 | self._close(BrokenPipeError()) |
| 474 | else: |
| 475 | self._close() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 476 | |
| 477 | def write(self, data): |
Guido van Rossum | 47fb97e | 2014-01-29 13:20:39 -0800 | [diff] [blame] | 478 | assert isinstance(data, (bytes, bytearray, memoryview)), repr(data) |
| 479 | if isinstance(data, bytearray): |
| 480 | data = memoryview(data) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 481 | if not data: |
| 482 | return |
| 483 | |
| 484 | if self._conn_lost or self._closing: |
| 485 | if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES: |
Guido van Rossum | fc29e0f | 2013-10-17 15:39:45 -0700 | [diff] [blame] | 486 | logger.warning('pipe closed by peer or ' |
| 487 | 'os.write(pipe, data) raised exception.') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 488 | self._conn_lost += 1 |
| 489 | return |
| 490 | |
| 491 | if not self._buffer: |
| 492 | # Attempt to send it right away first. |
| 493 | try: |
| 494 | n = os.write(self._fileno, data) |
| 495 | except (BlockingIOError, InterruptedError): |
| 496 | n = 0 |
| 497 | except Exception as exc: |
| 498 | self._conn_lost += 1 |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 499 | self._fatal_error(exc, 'Fatal write error on pipe transport') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 500 | return |
| 501 | if n == len(data): |
| 502 | return |
| 503 | elif n > 0: |
| 504 | data = data[n:] |
| 505 | self._loop.add_writer(self._fileno, self._write_ready) |
| 506 | |
| 507 | self._buffer.append(data) |
Guido van Rossum | 47fb97e | 2014-01-29 13:20:39 -0800 | [diff] [blame] | 508 | self._maybe_pause_protocol() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 509 | |
| 510 | def _write_ready(self): |
| 511 | data = b''.join(self._buffer) |
| 512 | assert data, 'Data should not be empty' |
| 513 | |
| 514 | self._buffer.clear() |
| 515 | try: |
| 516 | n = os.write(self._fileno, data) |
| 517 | except (BlockingIOError, InterruptedError): |
| 518 | self._buffer.append(data) |
| 519 | except Exception as exc: |
| 520 | self._conn_lost += 1 |
| 521 | # Remove writer here, _fatal_error() doesn't it |
| 522 | # because _buffer is empty. |
| 523 | self._loop.remove_writer(self._fileno) |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 524 | self._fatal_error(exc, 'Fatal write error on pipe transport') |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 525 | else: |
| 526 | if n == len(data): |
| 527 | self._loop.remove_writer(self._fileno) |
Guido van Rossum | 47fb97e | 2014-01-29 13:20:39 -0800 | [diff] [blame] | 528 | self._maybe_resume_protocol() # May append to buffer. |
| 529 | if not self._buffer and self._closing: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 530 | self._loop.remove_reader(self._fileno) |
| 531 | self._call_connection_lost(None) |
| 532 | return |
| 533 | elif n > 0: |
| 534 | data = data[n:] |
| 535 | |
| 536 | self._buffer.append(data) # Try again later. |
| 537 | |
| 538 | def can_write_eof(self): |
| 539 | return True |
| 540 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 541 | def write_eof(self): |
| 542 | if self._closing: |
| 543 | return |
| 544 | assert self._pipe |
| 545 | self._closing = True |
| 546 | if not self._buffer: |
| 547 | self._loop.remove_reader(self._fileno) |
| 548 | self._loop.call_soon(self._call_connection_lost, None) |
| 549 | |
| 550 | def close(self): |
Victor Stinner | 41ed958 | 2015-01-15 13:16:50 +0100 | [diff] [blame] | 551 | if self._pipe is not None and not self._closing: |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 552 | # write_eof is all what we needed to close the write pipe |
| 553 | self.write_eof() |
| 554 | |
Victor Stinner | 978a9af | 2015-01-29 17:50:58 +0100 | [diff] [blame] | 555 | # On Python 3.3 and older, objects with a destructor part of a reference |
| 556 | # cycle are never destroyed. It's not more the case on Python 3.4 thanks |
| 557 | # to the PEP 442. |
| 558 | if sys.version_info >= (3, 4): |
| 559 | def __del__(self): |
| 560 | if self._pipe is not None: |
| 561 | warnings.warn("unclosed transport %r" % self, ResourceWarning) |
| 562 | self._pipe.close() |
| 563 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 564 | def abort(self): |
| 565 | self._close(None) |
| 566 | |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 567 | def _fatal_error(self, exc, message='Fatal error on pipe transport'): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 568 | # should be called by exception handler only |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 569 | if isinstance(exc, (BrokenPipeError, ConnectionResetError)): |
| 570 | if self._loop.get_debug(): |
| 571 | logger.debug("%r: %s", self, message, exc_info=True) |
| 572 | else: |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 573 | self._loop.call_exception_handler({ |
Victor Stinner | 0ee29c2 | 2014-02-19 01:40:41 +0100 | [diff] [blame] | 574 | 'message': message, |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 575 | 'exception': exc, |
| 576 | 'transport': self, |
| 577 | 'protocol': self._protocol, |
| 578 | }) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 579 | self._close(exc) |
| 580 | |
| 581 | def _close(self, exc=None): |
| 582 | self._closing = True |
| 583 | if self._buffer: |
| 584 | self._loop.remove_writer(self._fileno) |
| 585 | self._buffer.clear() |
| 586 | self._loop.remove_reader(self._fileno) |
| 587 | self._loop.call_soon(self._call_connection_lost, exc) |
| 588 | |
| 589 | def _call_connection_lost(self, exc): |
| 590 | try: |
| 591 | self._protocol.connection_lost(exc) |
| 592 | finally: |
| 593 | self._pipe.close() |
| 594 | self._pipe = None |
| 595 | self._protocol = None |
| 596 | self._loop = None |
| 597 | |
| 598 | |
Victor Stinner | 1e40f10 | 2014-12-11 23:30:17 +0100 | [diff] [blame] | 599 | if hasattr(os, 'set_inheritable'): |
| 600 | # Python 3.4 and newer |
| 601 | _set_inheritable = os.set_inheritable |
| 602 | else: |
| 603 | import fcntl |
| 604 | |
| 605 | def _set_inheritable(fd, inheritable): |
| 606 | cloexec_flag = getattr(fcntl, 'FD_CLOEXEC', 1) |
| 607 | |
| 608 | old = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 609 | if not inheritable: |
| 610 | fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) |
| 611 | else: |
| 612 | fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) |
| 613 | |
| 614 | |
Guido van Rossum | 5969128 | 2013-10-30 14:52:03 -0700 | [diff] [blame] | 615 | class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 616 | |
Guido van Rossum | 5969128 | 2013-10-30 14:52:03 -0700 | [diff] [blame] | 617 | def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs): |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 618 | stdin_w = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 619 | if stdin == subprocess.PIPE: |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 620 | # Use a socket pair for stdin, since not all platforms |
| 621 | # support selecting read events on the write end of a |
| 622 | # socket (which we use in order to detect closing of the |
| 623 | # other end). Notably this is needed on AIX, and works |
| 624 | # just fine on other platforms. |
| 625 | stdin, stdin_w = self._loop._socketpair() |
Victor Stinner | 1e40f10 | 2014-12-11 23:30:17 +0100 | [diff] [blame] | 626 | |
| 627 | # Mark the write end of the stdin pipe as non-inheritable, |
| 628 | # needed by close_fds=False on Python 3.3 and older |
| 629 | # (Python 3.4 implements the PEP 446, socketpair returns |
| 630 | # non-inheritable sockets) |
| 631 | _set_inheritable(stdin_w.fileno(), False) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 632 | self._proc = subprocess.Popen( |
| 633 | args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr, |
| 634 | universal_newlines=False, bufsize=bufsize, **kwargs) |
Guido van Rossum | 934f6ea | 2013-10-21 20:37:14 -0700 | [diff] [blame] | 635 | if stdin_w is not None: |
| 636 | stdin.close() |
Victor Stinner | 2dba23a | 2014-07-03 00:59:00 +0200 | [diff] [blame] | 637 | self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 638 | |
| 639 | |
| 640 | class AbstractChildWatcher: |
| 641 | """Abstract base class for monitoring child processes. |
| 642 | |
| 643 | Objects derived from this class monitor a collection of subprocesses and |
| 644 | report their termination or interruption by a signal. |
| 645 | |
| 646 | New callbacks are registered with .add_child_handler(). Starting a new |
| 647 | process must be done within a 'with' block to allow the watcher to suspend |
| 648 | its activity until the new process if fully registered (this is needed to |
| 649 | prevent a race condition in some implementations). |
| 650 | |
| 651 | Example: |
| 652 | with watcher: |
| 653 | proc = subprocess.Popen("sleep 1") |
| 654 | watcher.add_child_handler(proc.pid, callback) |
| 655 | |
| 656 | Notes: |
| 657 | Implementations of this class must be thread-safe. |
| 658 | |
| 659 | Since child watcher objects may catch the SIGCHLD signal and call |
| 660 | waitpid(-1), there should be only one active object per process. |
| 661 | """ |
| 662 | |
| 663 | def add_child_handler(self, pid, callback, *args): |
| 664 | """Register a new child handler. |
| 665 | |
| 666 | Arrange for callback(pid, returncode, *args) to be called when |
| 667 | process 'pid' terminates. Specifying another callback for the same |
| 668 | process replaces the previous handler. |
| 669 | |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 670 | Note: callback() must be thread-safe. |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 671 | """ |
| 672 | raise NotImplementedError() |
| 673 | |
| 674 | def remove_child_handler(self, pid): |
| 675 | """Removes the handler for process 'pid'. |
| 676 | |
| 677 | The function returns True if the handler was successfully removed, |
| 678 | False if there was nothing to remove.""" |
| 679 | |
| 680 | raise NotImplementedError() |
| 681 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 682 | def attach_loop(self, loop): |
| 683 | """Attach the watcher to an event loop. |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 684 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 685 | If the watcher was previously attached to an event loop, then it is |
| 686 | first detached before attaching to the new loop. |
| 687 | |
| 688 | Note: loop may be None. |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 689 | """ |
| 690 | raise NotImplementedError() |
| 691 | |
| 692 | def close(self): |
| 693 | """Close the watcher. |
| 694 | |
| 695 | This must be called to make sure that any underlying resource is freed. |
| 696 | """ |
| 697 | raise NotImplementedError() |
| 698 | |
| 699 | def __enter__(self): |
| 700 | """Enter the watcher's context and allow starting new processes |
| 701 | |
| 702 | This function must return self""" |
| 703 | raise NotImplementedError() |
| 704 | |
| 705 | def __exit__(self, a, b, c): |
| 706 | """Exit the watcher's context""" |
| 707 | raise NotImplementedError() |
| 708 | |
| 709 | |
| 710 | class BaseChildWatcher(AbstractChildWatcher): |
| 711 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 712 | def __init__(self): |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 713 | self._loop = None |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 714 | |
| 715 | def close(self): |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 716 | self.attach_loop(None) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 717 | |
| 718 | def _do_waitpid(self, expected_pid): |
| 719 | raise NotImplementedError() |
| 720 | |
| 721 | def _do_waitpid_all(self): |
| 722 | raise NotImplementedError() |
| 723 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 724 | def attach_loop(self, loop): |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 725 | assert loop is None or isinstance(loop, events.AbstractEventLoop) |
| 726 | |
| 727 | if self._loop is not None: |
| 728 | self._loop.remove_signal_handler(signal.SIGCHLD) |
| 729 | |
| 730 | self._loop = loop |
| 731 | if loop is not None: |
| 732 | loop.add_signal_handler(signal.SIGCHLD, self._sig_chld) |
| 733 | |
| 734 | # Prevent a race condition in case a child terminated |
| 735 | # during the switch. |
| 736 | self._do_waitpid_all() |
| 737 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 738 | def _sig_chld(self): |
| 739 | try: |
| 740 | self._do_waitpid_all() |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 741 | except Exception as exc: |
| 742 | # self._loop should always be available here |
| 743 | # as '_sig_chld' is added as a signal handler |
| 744 | # in 'attach_loop' |
| 745 | self._loop.call_exception_handler({ |
| 746 | 'message': 'Unknown exception in SIGCHLD handler', |
| 747 | 'exception': exc, |
| 748 | }) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 749 | |
| 750 | def _compute_returncode(self, status): |
| 751 | if os.WIFSIGNALED(status): |
| 752 | # The child process died because of a signal. |
| 753 | return -os.WTERMSIG(status) |
| 754 | elif os.WIFEXITED(status): |
| 755 | # The child process exited (e.g sys.exit()). |
| 756 | return os.WEXITSTATUS(status) |
| 757 | else: |
| 758 | # The child exited, but we don't understand its status. |
| 759 | # This shouldn't happen, but if it does, let's just |
| 760 | # return that status; perhaps that helps debug it. |
| 761 | return status |
| 762 | |
| 763 | |
| 764 | class SafeChildWatcher(BaseChildWatcher): |
| 765 | """'Safe' child watcher implementation. |
| 766 | |
| 767 | This implementation avoids disrupting other code spawning processes by |
| 768 | polling explicitly each process in the SIGCHLD handler instead of calling |
| 769 | os.waitpid(-1). |
| 770 | |
| 771 | This is a safe solution but it has a significant overhead when handling a |
| 772 | big number of children (O(n) each time SIGCHLD is raised) |
| 773 | """ |
| 774 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 775 | def __init__(self): |
| 776 | super().__init__() |
| 777 | self._callbacks = {} |
| 778 | |
| 779 | def close(self): |
| 780 | self._callbacks.clear() |
| 781 | super().close() |
| 782 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 783 | def __enter__(self): |
| 784 | return self |
| 785 | |
| 786 | def __exit__(self, a, b, c): |
| 787 | pass |
| 788 | |
| 789 | def add_child_handler(self, pid, callback, *args): |
Victor Stinner | 47cd10d | 2015-01-30 00:05:19 +0100 | [diff] [blame] | 790 | self._callbacks[pid] = (callback, args) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 791 | |
| 792 | # Prevent a race condition in case the child is already terminated. |
| 793 | self._do_waitpid(pid) |
| 794 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 795 | def remove_child_handler(self, pid): |
| 796 | try: |
| 797 | del self._callbacks[pid] |
| 798 | return True |
| 799 | except KeyError: |
| 800 | return False |
| 801 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 802 | def _do_waitpid_all(self): |
| 803 | |
| 804 | for pid in list(self._callbacks): |
| 805 | self._do_waitpid(pid) |
| 806 | |
| 807 | def _do_waitpid(self, expected_pid): |
| 808 | assert expected_pid > 0 |
| 809 | |
| 810 | try: |
| 811 | pid, status = os.waitpid(expected_pid, os.WNOHANG) |
| 812 | except ChildProcessError: |
| 813 | # The child process is already reaped |
| 814 | # (may happen if waitpid() is called elsewhere). |
| 815 | pid = expected_pid |
| 816 | returncode = 255 |
| 817 | logger.warning( |
| 818 | "Unknown child process pid %d, will report returncode 255", |
| 819 | pid) |
| 820 | else: |
| 821 | if pid == 0: |
| 822 | # The child process is still alive. |
| 823 | return |
| 824 | |
| 825 | returncode = self._compute_returncode(status) |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 826 | if self._loop.get_debug(): |
| 827 | logger.debug('process %s exited with returncode %s', |
| 828 | expected_pid, returncode) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 829 | |
| 830 | try: |
| 831 | callback, args = self._callbacks.pop(pid) |
| 832 | except KeyError: # pragma: no cover |
| 833 | # May happen if .remove_child_handler() is called |
| 834 | # after os.waitpid() returns. |
Victor Stinner | b261475 | 2014-08-25 23:20:52 +0200 | [diff] [blame] | 835 | if self._loop.get_debug(): |
| 836 | logger.warning("Child watcher got an unexpected pid: %r", |
| 837 | pid, exc_info=True) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 838 | else: |
| 839 | callback(pid, returncode, *args) |
| 840 | |
| 841 | |
| 842 | class FastChildWatcher(BaseChildWatcher): |
| 843 | """'Fast' child watcher implementation. |
| 844 | |
| 845 | This implementation reaps every terminated processes by calling |
| 846 | os.waitpid(-1) directly, possibly breaking other code spawning processes |
| 847 | and waiting for their termination. |
| 848 | |
| 849 | There is no noticeable overhead when handling a big number of children |
| 850 | (O(1) each time a child terminates). |
| 851 | """ |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 852 | def __init__(self): |
| 853 | super().__init__() |
| 854 | self._callbacks = {} |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 855 | self._lock = threading.Lock() |
| 856 | self._zombies = {} |
| 857 | self._forks = 0 |
| 858 | |
| 859 | def close(self): |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 860 | self._callbacks.clear() |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 861 | self._zombies.clear() |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 862 | super().close() |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 863 | |
| 864 | def __enter__(self): |
| 865 | with self._lock: |
| 866 | self._forks += 1 |
| 867 | |
| 868 | return self |
| 869 | |
| 870 | def __exit__(self, a, b, c): |
| 871 | with self._lock: |
| 872 | self._forks -= 1 |
| 873 | |
| 874 | if self._forks or not self._zombies: |
| 875 | return |
| 876 | |
| 877 | collateral_victims = str(self._zombies) |
| 878 | self._zombies.clear() |
| 879 | |
| 880 | logger.warning( |
| 881 | "Caught subprocesses termination from unknown pids: %s", |
| 882 | collateral_victims) |
| 883 | |
| 884 | def add_child_handler(self, pid, callback, *args): |
| 885 | assert self._forks, "Must use the context manager" |
Guido van Rossum | ab27a9f | 2014-01-25 16:32:17 -0800 | [diff] [blame] | 886 | with self._lock: |
| 887 | try: |
| 888 | returncode = self._zombies.pop(pid) |
| 889 | except KeyError: |
| 890 | # The child is running. |
| 891 | self._callbacks[pid] = callback, args |
| 892 | return |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 893 | |
Guido van Rossum | ab27a9f | 2014-01-25 16:32:17 -0800 | [diff] [blame] | 894 | # The child is dead already. We can fire the callback. |
| 895 | callback(pid, returncode, *args) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 896 | |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 897 | def remove_child_handler(self, pid): |
| 898 | try: |
| 899 | del self._callbacks[pid] |
| 900 | return True |
| 901 | except KeyError: |
| 902 | return False |
| 903 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 904 | def _do_waitpid_all(self): |
| 905 | # Because of signal coalescing, we must keep calling waitpid() as |
| 906 | # long as we're able to reap a child. |
| 907 | while True: |
| 908 | try: |
| 909 | pid, status = os.waitpid(-1, os.WNOHANG) |
| 910 | except ChildProcessError: |
| 911 | # No more child processes exist. |
| 912 | return |
| 913 | else: |
| 914 | if pid == 0: |
| 915 | # A child process is still alive. |
| 916 | return |
| 917 | |
| 918 | returncode = self._compute_returncode(status) |
| 919 | |
Guido van Rossum | ab27a9f | 2014-01-25 16:32:17 -0800 | [diff] [blame] | 920 | with self._lock: |
| 921 | try: |
| 922 | callback, args = self._callbacks.pop(pid) |
| 923 | except KeyError: |
| 924 | # unknown child |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 925 | if self._forks: |
| 926 | # It may not be registered yet. |
| 927 | self._zombies[pid] = returncode |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 928 | if self._loop.get_debug(): |
| 929 | logger.debug('unknown process %s exited ' |
| 930 | 'with returncode %s', |
| 931 | pid, returncode) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 932 | continue |
Guido van Rossum | ab27a9f | 2014-01-25 16:32:17 -0800 | [diff] [blame] | 933 | callback = None |
Victor Stinner | acdb782 | 2014-07-14 18:33:40 +0200 | [diff] [blame] | 934 | else: |
| 935 | if self._loop.get_debug(): |
| 936 | logger.debug('process %s exited with returncode %s', |
| 937 | pid, returncode) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 938 | |
Guido van Rossum | ab27a9f | 2014-01-25 16:32:17 -0800 | [diff] [blame] | 939 | if callback is None: |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 940 | logger.warning( |
| 941 | "Caught subprocess termination from unknown pid: " |
| 942 | "%d -> %d", pid, returncode) |
| 943 | else: |
| 944 | callback(pid, returncode, *args) |
| 945 | |
| 946 | |
| 947 | class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): |
Victor Stinner | 70db9e4 | 2015-01-09 21:32:05 +0100 | [diff] [blame] | 948 | """UNIX event loop policy with a watcher for child processes.""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 949 | _loop_factory = _UnixSelectorEventLoop |
| 950 | |
| 951 | def __init__(self): |
| 952 | super().__init__() |
| 953 | self._watcher = None |
| 954 | |
| 955 | def _init_watcher(self): |
| 956 | with events._lock: |
| 957 | if self._watcher is None: # pragma: no branch |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 958 | self._watcher = SafeChildWatcher() |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 959 | if isinstance(threading.current_thread(), |
| 960 | threading._MainThread): |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 961 | self._watcher.attach_loop(self._local._loop) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 962 | |
| 963 | def set_event_loop(self, loop): |
| 964 | """Set the event loop. |
| 965 | |
| 966 | As a side effect, if a child watcher was set before, then calling |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 967 | .set_event_loop() from the main thread will call .attach_loop(loop) on |
| 968 | the child watcher. |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 969 | """ |
| 970 | |
| 971 | super().set_event_loop(loop) |
| 972 | |
| 973 | if self._watcher is not None and \ |
| 974 | isinstance(threading.current_thread(), threading._MainThread): |
Guido van Rossum | 2bcae70 | 2013-11-13 15:50:08 -0800 | [diff] [blame] | 975 | self._watcher.attach_loop(loop) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 976 | |
| 977 | def get_child_watcher(self): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 978 | """Get the watcher for child processes. |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 979 | |
| 980 | If not yet set, a SafeChildWatcher object is automatically created. |
| 981 | """ |
| 982 | if self._watcher is None: |
| 983 | self._init_watcher() |
| 984 | |
| 985 | return self._watcher |
| 986 | |
| 987 | def set_child_watcher(self, watcher): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 988 | """Set the watcher for child processes.""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 989 | |
| 990 | assert watcher is None or isinstance(watcher, AbstractChildWatcher) |
| 991 | |
| 992 | if self._watcher is not None: |
| 993 | self._watcher.close() |
| 994 | |
| 995 | self._watcher = watcher |
| 996 | |
| 997 | SelectorEventLoop = _UnixSelectorEventLoop |
| 998 | DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy |