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