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