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