blob: 77905344fb7129931851e33ebca3d42bb63e9add [file] [log] [blame]
Yury Selivanovdec1a452014-02-18 22:27:48 -05001"""Selector event loop for Unix with signal handling."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07002
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07003import errno
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07004import os
5import signal
6import socket
7import stat
8import subprocess
9import sys
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080010import threading
Victor Stinner978a9af2015-01-29 17:50:58 +010011import warnings
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070012
13
Yury Selivanovb057c522014-02-18 12:15:06 -050014from . import base_events
Guido van Rossum59691282013-10-30 14:52:03 -070015from . import base_subprocess
Yury Selivanov2a8911c2015-08-04 15:56:33 -040016from . import compat
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070017from . import constants
Guido van Rossume36fcde2014-11-14 11:45:47 -080018from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070019from . import events
Victor Stinner47cd10d2015-01-30 00:05:19 +010020from . import futures
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021from . import selector_events
Victor Stinnere912e652014-07-12 03:11:53 +020022from . import selectors
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023from . import transports
Victor Stinnerf951d282014-06-29 00:46:45 +020024from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070025from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026
27
Victor Stinner915bcb02014-02-01 22:49:59 +010028__all__ = ['SelectorEventLoop',
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080029 'AbstractChildWatcher', 'SafeChildWatcher',
30 'FastChildWatcher', 'DefaultEventLoopPolicy',
31 ]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070033if sys.platform == 'win32': # pragma: no cover
34 raise ImportError('Signals are not really supported on Windows')
35
36
Victor Stinnerfe5649c2014-07-17 22:43:40 +020037def _sighandler_noop(signum, frame):
38 """Dummy signal handler."""
39 pass
40
41
Yury Selivanovd7c15182016-11-15 15:26:34 -050042try:
43 _fspath = os.fspath
44except AttributeError:
45 # Python 3.5 or earlier
46 _fspath = lambda path: path
47
48
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -080049class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
Yury Selivanovb057c522014-02-18 12:15:06 -050050 """Unix event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051
Yury Selivanovb057c522014-02-18 12:15:06 -050052 Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070053 """
54
55 def __init__(self, selector=None):
56 super().__init__(selector)
57 self._signal_handlers = {}
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070058
59 def _socketpair(self):
60 return socket.socketpair()
61
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080062 def close(self):
Victor Stinnerf328c7d2014-06-23 01:02:37 +020063 super().close()
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080064 for sig in list(self._signal_handlers):
65 self.remove_signal_handler(sig)
Guido van Rossum0b69fbc2013-11-06 20:25:50 -080066
Victor Stinnerfe5649c2014-07-17 22:43:40 +020067 def _process_self_data(self, data):
68 for signum in data:
69 if not signum:
70 # ignore null bytes written by _write_to_self()
71 continue
72 self._handle_signal(signum)
73
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070074 def add_signal_handler(self, sig, callback, *args):
75 """Add a handler for a signal. UNIX only.
76
77 Raise ValueError if the signal number is invalid or uncatchable.
78 Raise RuntimeError if there is a problem setting up the handler.
79 """
Victor Stinner2d99d932014-11-20 15:03:52 +010080 if (coroutines.iscoroutine(callback)
81 or coroutines.iscoroutinefunction(callback)):
Victor Stinner15cc6782015-01-09 00:09:10 +010082 raise TypeError("coroutines cannot be used "
83 "with add_signal_handler()")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070084 self._check_signal(sig)
Victor Stinnere80bf0d2014-12-04 23:07:47 +010085 self._check_closed()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086 try:
87 # set_wakeup_fd() raises ValueError if this is not the
88 # main thread. By calling it early we ensure that an
89 # event loop running in another thread cannot add a signal
90 # handler.
91 signal.set_wakeup_fd(self._csock.fileno())
Victor Stinnerc4c46492014-07-23 18:21:45 +020092 except (ValueError, OSError) as exc:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070093 raise RuntimeError(str(exc))
94
Yury Selivanov569efa22014-02-18 18:02:19 -050095 handle = events.Handle(callback, args, self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070096 self._signal_handlers[sig] = handle
97
98 try:
Victor Stinnerfe5649c2014-07-17 22:43:40 +020099 # Register a dummy signal handler to ask Python to write the signal
100 # number in the wakup file descriptor. _process_self_data() will
101 # read signal numbers from this file descriptor to handle signals.
102 signal.signal(sig, _sighandler_noop)
103
Charles-François Natali74e7cf32013-12-05 22:47:19 +0100104 # Set SA_RESTART to limit EINTR occurrences.
105 signal.siginterrupt(sig, False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700106 except OSError as exc:
107 del self._signal_handlers[sig]
108 if not self._signal_handlers:
109 try:
110 signal.set_wakeup_fd(-1)
Victor Stinnerc4c46492014-07-23 18:21:45 +0200111 except (ValueError, OSError) as nexc:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700112 logger.info('set_wakeup_fd(-1) failed: %s', nexc)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700113
114 if exc.errno == errno.EINVAL:
115 raise RuntimeError('sig {} cannot be caught'.format(sig))
116 else:
117 raise
118
Victor Stinnerfe5649c2014-07-17 22:43:40 +0200119 def _handle_signal(self, sig):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700120 """Internal helper that is the actual signal handler."""
121 handle = self._signal_handlers.get(sig)
122 if handle is None:
123 return # Assume it's some race condition.
124 if handle._cancelled:
125 self.remove_signal_handler(sig) # Remove it properly.
126 else:
127 self._add_callback_signalsafe(handle)
128
129 def remove_signal_handler(self, sig):
130 """Remove a handler for a signal. UNIX only.
131
132 Return True if a signal handler was removed, False if not.
133 """
134 self._check_signal(sig)
135 try:
136 del self._signal_handlers[sig]
137 except KeyError:
138 return False
139
140 if sig == signal.SIGINT:
141 handler = signal.default_int_handler
142 else:
143 handler = signal.SIG_DFL
144
145 try:
146 signal.signal(sig, handler)
147 except OSError as exc:
148 if exc.errno == errno.EINVAL:
149 raise RuntimeError('sig {} cannot be caught'.format(sig))
150 else:
151 raise
152
153 if not self._signal_handlers:
154 try:
155 signal.set_wakeup_fd(-1)
Victor Stinnerc4c46492014-07-23 18:21:45 +0200156 except (ValueError, OSError) as exc:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700157 logger.info('set_wakeup_fd(-1) failed: %s', exc)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700158
159 return True
160
161 def _check_signal(self, sig):
162 """Internal helper to validate a signal.
163
164 Raise ValueError if the signal number is invalid or uncatchable.
165 Raise RuntimeError if there is a problem setting up the handler.
166 """
167 if not isinstance(sig, int):
168 raise TypeError('sig must be an int, not {!r}'.format(sig))
169
170 if not (1 <= sig < signal.NSIG):
171 raise ValueError(
172 'sig {} out of range(1, {})'.format(sig, signal.NSIG))
173
174 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
175 extra=None):
176 return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
177
178 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
179 extra=None):
180 return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
181
Victor Stinnerf951d282014-06-29 00:46:45 +0200182 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700183 def _make_subprocess_transport(self, protocol, args, shell,
184 stdin, stdout, stderr, bufsize,
185 extra=None, **kwargs):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800186 with events.get_child_watcher() as watcher:
Yury Selivanov7661db62016-05-16 15:38:39 -0400187 waiter = self.create_future()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800188 transp = _UnixSubprocessTransport(self, protocol, args, shell,
189 stdin, stdout, stderr, bufsize,
Victor Stinner47cd10d2015-01-30 00:05:19 +0100190 waiter=waiter, extra=extra,
191 **kwargs)
192
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800193 watcher.add_child_handler(transp.get_pid(),
194 self._child_watcher_callback, transp)
Victor Stinner47cd10d2015-01-30 00:05:19 +0100195 try:
196 yield from waiter
Victor Stinner5d44c082015-02-02 18:36:31 +0100197 except Exception as exc:
198 # Workaround CPython bug #23353: using yield/yield-from in an
199 # except block of a generator doesn't clear properly
200 # sys.exc_info()
201 err = exc
202 else:
203 err = None
204
205 if err is not None:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100206 transp.close()
Victor Stinner1241ecc2015-01-30 00:16:14 +0100207 yield from transp._wait()
Victor Stinner5d44c082015-02-02 18:36:31 +0100208 raise err
Guido van Rossum4835f172014-01-10 13:28:59 -0800209
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700210 return transp
211
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800212 def _child_watcher_callback(self, pid, returncode, transp):
213 self.call_soon_threadsafe(transp._process_exited, returncode)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700214
Victor Stinnerf951d282014-06-29 00:46:45 +0200215 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500216 def create_unix_connection(self, protocol_factory, path, *,
217 ssl=None, sock=None,
218 server_hostname=None):
219 assert server_hostname is None or isinstance(server_hostname, str)
220 if ssl:
221 if server_hostname is None:
222 raise ValueError(
223 'you have to pass server_hostname when using ssl')
224 else:
225 if server_hostname is not None:
226 raise ValueError('server_hostname is only meaningful with ssl')
227
228 if path is not None:
229 if sock is not None:
230 raise ValueError(
231 'path and sock can not be specified at the same time')
232
Victor Stinner79a29522014-02-19 01:45:59 +0100233 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
Yury Selivanovb057c522014-02-18 12:15:06 -0500234 try:
Yury Selivanovb057c522014-02-18 12:15:06 -0500235 sock.setblocking(False)
236 yield from self.sock_connect(sock, path)
Victor Stinner79a29522014-02-19 01:45:59 +0100237 except:
238 sock.close()
Yury Selivanovb057c522014-02-18 12:15:06 -0500239 raise
240
241 else:
242 if sock is None:
243 raise ValueError('no path and sock were specified')
Yury Selivanov36e7e972016-10-07 12:39:57 -0400244 if (sock.family != socket.AF_UNIX or
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500245 not base_events._is_stream_socket(sock)):
Yury Selivanov36e7e972016-10-07 12:39:57 -0400246 raise ValueError(
247 'A UNIX Domain Stream Socket was expected, got {!r}'
248 .format(sock))
Yury Selivanovb057c522014-02-18 12:15:06 -0500249 sock.setblocking(False)
250
251 transport, protocol = yield from self._create_connection_transport(
252 sock, protocol_factory, ssl, server_hostname)
253 return transport, protocol
254
Victor Stinnerf951d282014-06-29 00:46:45 +0200255 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500256 def create_unix_server(self, protocol_factory, path=None, *,
257 sock=None, backlog=100, ssl=None):
258 if isinstance(ssl, bool):
259 raise TypeError('ssl argument must be an SSLContext or None')
260
261 if path is not None:
Victor Stinner1fd03a42014-04-07 11:18:54 +0200262 if sock is not None:
263 raise ValueError(
264 'path and sock can not be specified at the same time')
265
Yury Selivanovd7c15182016-11-15 15:26:34 -0500266 path = _fspath(path)
Yury Selivanovb057c522014-02-18 12:15:06 -0500267 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
268
Yury Selivanov908d55d2016-10-09 12:15:08 -0400269 # Check for abstract socket. `str` and `bytes` paths are supported.
270 if path[0] not in (0, '\x00'):
271 try:
272 if stat.S_ISSOCK(os.stat(path).st_mode):
273 os.remove(path)
274 except FileNotFoundError:
275 pass
276 except OSError as err:
277 # Directory may have permissions only to create socket.
278 logger.error('Unable to check or remove stale UNIX socket %r: %r', path, err)
279
Yury Selivanovb057c522014-02-18 12:15:06 -0500280 try:
281 sock.bind(path)
282 except OSError as exc:
Victor Stinner79a29522014-02-19 01:45:59 +0100283 sock.close()
Yury Selivanovb057c522014-02-18 12:15:06 -0500284 if exc.errno == errno.EADDRINUSE:
285 # Let's improve the error message by adding
286 # with what exact address it occurs.
287 msg = 'Address {!r} is already in use'.format(path)
288 raise OSError(errno.EADDRINUSE, msg) from None
289 else:
290 raise
Victor Stinner223a6242014-06-04 00:11:52 +0200291 except:
292 sock.close()
293 raise
Yury Selivanovb057c522014-02-18 12:15:06 -0500294 else:
295 if sock is None:
296 raise ValueError(
297 'path was not specified, and no sock specified')
298
Yury Selivanov36e7e972016-10-07 12:39:57 -0400299 if (sock.family != socket.AF_UNIX or
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500300 not base_events._is_stream_socket(sock)):
Yury Selivanovb057c522014-02-18 12:15:06 -0500301 raise ValueError(
Yury Selivanov36e7e972016-10-07 12:39:57 -0400302 'A UNIX Domain Stream Socket was expected, got {!r}'
303 .format(sock))
Yury Selivanovb057c522014-02-18 12:15:06 -0500304
305 server = base_events.Server(self, [sock])
306 sock.listen(backlog)
307 sock.setblocking(False)
308 self._start_serving(protocol_factory, sock, ssl, server)
309 return server
310
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311
Victor Stinnerf2ed8892014-07-29 23:08:00 +0200312if hasattr(os, 'set_blocking'):
313 def _set_nonblocking(fd):
314 os.set_blocking(fd, False)
315else:
Yury Selivanov8c0e0ab2014-09-24 23:21:39 -0400316 import fcntl
317
Victor Stinnerf2ed8892014-07-29 23:08:00 +0200318 def _set_nonblocking(fd):
319 flags = fcntl.fcntl(fd, fcntl.F_GETFL)
320 flags = flags | os.O_NONBLOCK
321 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700322
323
324class _UnixReadPipeTransport(transports.ReadTransport):
325
Yury Selivanovdec1a452014-02-18 22:27:48 -0500326 max_size = 256 * 1024 # max bytes we read in one event loop iteration
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700327
328 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
329 super().__init__(extra)
330 self._extra['pipe'] = pipe
331 self._loop = loop
332 self._pipe = pipe
333 self._fileno = pipe.fileno()
Guido van Rossum47867872016-08-31 09:42:38 -0700334 self._protocol = protocol
335 self._closing = False
336
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700337 mode = os.fstat(self._fileno).st_mode
Guido van Rossum02757ea2014-01-10 13:30:04 -0800338 if not (stat.S_ISFIFO(mode) or
339 stat.S_ISSOCK(mode) or
340 stat.S_ISCHR(mode)):
Guido van Rossum47867872016-08-31 09:42:38 -0700341 self._pipe = None
342 self._fileno = None
343 self._protocol = None
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700344 raise ValueError("Pipe transport is for pipes/sockets only.")
Guido van Rossum47867872016-08-31 09:42:38 -0700345
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700346 _set_nonblocking(self._fileno)
Guido van Rossum47867872016-08-31 09:42:38 -0700347
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700348 self._loop.call_soon(self._protocol.connection_made, self)
Victor Stinner29342622015-01-29 14:15:19 +0100349 # only start reading when connection_made() has been called
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400350 self._loop.call_soon(self._loop._add_reader,
Victor Stinner29342622015-01-29 14:15:19 +0100351 self._fileno, self._read_ready)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700352 if waiter is not None:
Victor Stinnerf07801b2015-01-29 00:36:35 +0100353 # only wake up the waiter when connection_made() has been called
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500354 self._loop.call_soon(futures._set_result_unless_cancelled,
355 waiter, None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700356
Victor Stinnere912e652014-07-12 03:11:53 +0200357 def __repr__(self):
Victor Stinner29ad0112015-01-15 00:04:21 +0100358 info = [self.__class__.__name__]
359 if self._pipe is None:
360 info.append('closed')
361 elif self._closing:
362 info.append('closing')
363 info.append('fd=%s' % self._fileno)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400364 selector = getattr(self._loop, '_selector', None)
365 if self._pipe is not None and selector is not None:
Victor Stinnere912e652014-07-12 03:11:53 +0200366 polling = selector_events._test_selector_event(
Yury Selivanov5dc09332016-05-13 16:04:43 -0400367 selector,
Victor Stinnere912e652014-07-12 03:11:53 +0200368 self._fileno, selectors.EVENT_READ)
369 if polling:
370 info.append('polling')
371 else:
372 info.append('idle')
Yury Selivanov5dc09332016-05-13 16:04:43 -0400373 elif self._pipe is not None:
374 info.append('open')
Victor Stinnere912e652014-07-12 03:11:53 +0200375 else:
376 info.append('closed')
377 return '<%s>' % ' '.join(info)
378
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700379 def _read_ready(self):
380 try:
381 data = os.read(self._fileno, self.max_size)
382 except (BlockingIOError, InterruptedError):
383 pass
384 except OSError as exc:
Victor Stinner0ee29c22014-02-19 01:40:41 +0100385 self._fatal_error(exc, 'Fatal read error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700386 else:
387 if data:
388 self._protocol.data_received(data)
389 else:
Victor Stinnere912e652014-07-12 03:11:53 +0200390 if self._loop.get_debug():
391 logger.info("%r was closed by peer", self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700392 self._closing = True
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400393 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700394 self._loop.call_soon(self._protocol.eof_received)
395 self._loop.call_soon(self._call_connection_lost, None)
396
Guido van Rossum57497ad2013-10-18 07:58:20 -0700397 def pause_reading(self):
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400398 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700399
Guido van Rossum57497ad2013-10-18 07:58:20 -0700400 def resume_reading(self):
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400401 self._loop._add_reader(self._fileno, self._read_ready)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700402
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400403 def set_protocol(self, protocol):
404 self._protocol = protocol
405
406 def get_protocol(self):
407 return self._protocol
408
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500409 def is_closing(self):
410 return self._closing
411
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700412 def close(self):
413 if not self._closing:
414 self._close(None)
415
Victor Stinner978a9af2015-01-29 17:50:58 +0100416 # On Python 3.3 and older, objects with a destructor part of a reference
417 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
418 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400419 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100420 def __del__(self):
421 if self._pipe is not None:
422 warnings.warn("unclosed transport %r" % self, ResourceWarning)
423 self._pipe.close()
424
Victor Stinner0ee29c22014-02-19 01:40:41 +0100425 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700426 # should be called by exception handler only
Victor Stinnerb2614752014-08-25 23:20:52 +0200427 if (isinstance(exc, OSError) and exc.errno == errno.EIO):
428 if self._loop.get_debug():
429 logger.debug("%r: %s", self, message, exc_info=True)
430 else:
Yury Selivanov569efa22014-02-18 18:02:19 -0500431 self._loop.call_exception_handler({
Victor Stinner0ee29c22014-02-19 01:40:41 +0100432 'message': message,
Yury Selivanov569efa22014-02-18 18:02:19 -0500433 'exception': exc,
434 'transport': self,
435 'protocol': self._protocol,
436 })
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700437 self._close(exc)
438
439 def _close(self, exc):
440 self._closing = True
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400441 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700442 self._loop.call_soon(self._call_connection_lost, exc)
443
444 def _call_connection_lost(self, exc):
445 try:
446 self._protocol.connection_lost(exc)
447 finally:
448 self._pipe.close()
449 self._pipe = None
450 self._protocol = None
451 self._loop = None
452
453
Yury Selivanov3cb99142014-02-18 18:41:13 -0500454class _UnixWritePipeTransport(transports._FlowControlMixin,
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800455 transports.WriteTransport):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700456
457 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
Victor Stinner004adb92014-11-05 15:27:41 +0100458 super().__init__(extra, loop)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459 self._extra['pipe'] = pipe
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700460 self._pipe = pipe
461 self._fileno = pipe.fileno()
Guido van Rossum47867872016-08-31 09:42:38 -0700462 self._protocol = protocol
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400463 self._buffer = bytearray()
Guido van Rossum47867872016-08-31 09:42:38 -0700464 self._conn_lost = 0
465 self._closing = False # Set when close() or write_eof() called.
466
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700467 mode = os.fstat(self._fileno).st_mode
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700468 is_char = stat.S_ISCHR(mode)
469 is_fifo = stat.S_ISFIFO(mode)
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700470 is_socket = stat.S_ISSOCK(mode)
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700471 if not (is_char or is_fifo or is_socket):
Guido van Rossum47867872016-08-31 09:42:38 -0700472 self._pipe = None
473 self._fileno = None
474 self._protocol = None
Victor Stinner8dffc452014-01-25 15:32:06 +0100475 raise ValueError("Pipe transport is only for "
476 "pipes, sockets and character devices")
Guido van Rossum47867872016-08-31 09:42:38 -0700477
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700478 _set_nonblocking(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479 self._loop.call_soon(self._protocol.connection_made, self)
Victor Stinner29342622015-01-29 14:15:19 +0100480
481 # On AIX, the reader trick (to be notified when the read end of the
482 # socket is closed) only works for sockets. On other platforms it
483 # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
Guido van Rossum8b7918a2016-08-31 09:40:18 -0700484 if is_socket or (is_fifo and not sys.platform.startswith("aix")):
Victor Stinner29342622015-01-29 14:15:19 +0100485 # only start reading when connection_made() has been called
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400486 self._loop.call_soon(self._loop._add_reader,
Victor Stinner29342622015-01-29 14:15:19 +0100487 self._fileno, self._read_ready)
488
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700489 if waiter is not None:
Victor Stinnerf07801b2015-01-29 00:36:35 +0100490 # only wake up the waiter when connection_made() has been called
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500491 self._loop.call_soon(futures._set_result_unless_cancelled,
492 waiter, None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700493
Victor Stinnere912e652014-07-12 03:11:53 +0200494 def __repr__(self):
Victor Stinner29ad0112015-01-15 00:04:21 +0100495 info = [self.__class__.__name__]
496 if self._pipe is None:
497 info.append('closed')
498 elif self._closing:
499 info.append('closing')
500 info.append('fd=%s' % self._fileno)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400501 selector = getattr(self._loop, '_selector', None)
502 if self._pipe is not None and selector is not None:
Victor Stinnere912e652014-07-12 03:11:53 +0200503 polling = selector_events._test_selector_event(
Yury Selivanov5dc09332016-05-13 16:04:43 -0400504 selector,
Victor Stinnere912e652014-07-12 03:11:53 +0200505 self._fileno, selectors.EVENT_WRITE)
506 if polling:
507 info.append('polling')
508 else:
509 info.append('idle')
510
511 bufsize = self.get_write_buffer_size()
512 info.append('bufsize=%s' % bufsize)
Yury Selivanov5dc09332016-05-13 16:04:43 -0400513 elif self._pipe is not None:
514 info.append('open')
Victor Stinnere912e652014-07-12 03:11:53 +0200515 else:
516 info.append('closed')
517 return '<%s>' % ' '.join(info)
518
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800519 def get_write_buffer_size(self):
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400520 return len(self._buffer)
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800521
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700522 def _read_ready(self):
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700523 # Pipe was closed by peer.
Victor Stinnere912e652014-07-12 03:11:53 +0200524 if self._loop.get_debug():
525 logger.info("%r was closed by peer", self)
Victor Stinner61b3c9b2014-01-31 13:04:28 +0100526 if self._buffer:
527 self._close(BrokenPipeError())
528 else:
529 self._close()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530
531 def write(self, data):
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800532 assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
533 if isinstance(data, bytearray):
534 data = memoryview(data)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535 if not data:
536 return
537
538 if self._conn_lost or self._closing:
539 if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
Guido van Rossumfc29e0f2013-10-17 15:39:45 -0700540 logger.warning('pipe closed by peer or '
541 'os.write(pipe, data) raised exception.')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700542 self._conn_lost += 1
543 return
544
545 if not self._buffer:
546 # Attempt to send it right away first.
547 try:
548 n = os.write(self._fileno, data)
549 except (BlockingIOError, InterruptedError):
550 n = 0
551 except Exception as exc:
552 self._conn_lost += 1
Victor Stinner0ee29c22014-02-19 01:40:41 +0100553 self._fatal_error(exc, 'Fatal write error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554 return
555 if n == len(data):
556 return
557 elif n > 0:
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400558 data = memoryview(data)[n:]
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400559 self._loop._add_writer(self._fileno, self._write_ready)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400561 self._buffer += data
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800562 self._maybe_pause_protocol()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700563
564 def _write_ready(self):
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400565 assert self._buffer, 'Data should not be empty'
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700567 try:
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400568 n = os.write(self._fileno, self._buffer)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700569 except (BlockingIOError, InterruptedError):
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400570 pass
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700571 except Exception as exc:
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400572 self._buffer.clear()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573 self._conn_lost += 1
574 # Remove writer here, _fatal_error() doesn't it
575 # because _buffer is empty.
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400576 self._loop._remove_writer(self._fileno)
Victor Stinner0ee29c22014-02-19 01:40:41 +0100577 self._fatal_error(exc, 'Fatal write error on pipe transport')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700578 else:
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400579 if n == len(self._buffer):
580 self._buffer.clear()
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400581 self._loop._remove_writer(self._fileno)
Guido van Rossum47fb97e2014-01-29 13:20:39 -0800582 self._maybe_resume_protocol() # May append to buffer.
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400583 if self._closing:
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400584 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585 self._call_connection_lost(None)
586 return
587 elif n > 0:
Yury Selivanov4c5bf3b2016-09-15 16:51:48 -0400588 del self._buffer[:n]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700589
590 def can_write_eof(self):
591 return True
592
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700593 def write_eof(self):
594 if self._closing:
595 return
596 assert self._pipe
597 self._closing = True
598 if not self._buffer:
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400599 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600 self._loop.call_soon(self._call_connection_lost, None)
601
Yury Selivanova05a6ef2016-09-11 21:11:02 -0400602 def set_protocol(self, protocol):
603 self._protocol = protocol
604
605 def get_protocol(self):
606 return self._protocol
607
Yury Selivanov5bb1afb2015-11-16 12:43:21 -0500608 def is_closing(self):
609 return self._closing
610
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700611 def close(self):
Victor Stinner41ed9582015-01-15 13:16:50 +0100612 if self._pipe is not None and not self._closing:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700613 # write_eof is all what we needed to close the write pipe
614 self.write_eof()
615
Victor Stinner978a9af2015-01-29 17:50:58 +0100616 # On Python 3.3 and older, objects with a destructor part of a reference
617 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
618 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400619 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100620 def __del__(self):
621 if self._pipe is not None:
622 warnings.warn("unclosed transport %r" % self, ResourceWarning)
623 self._pipe.close()
624
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625 def abort(self):
626 self._close(None)
627
Victor Stinner0ee29c22014-02-19 01:40:41 +0100628 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700629 # should be called by exception handler only
Victor Stinnerc94a93a2016-04-01 21:43:39 +0200630 if isinstance(exc, base_events._FATAL_ERROR_IGNORE):
Victor Stinnerb2614752014-08-25 23:20:52 +0200631 if self._loop.get_debug():
632 logger.debug("%r: %s", self, message, exc_info=True)
633 else:
Yury Selivanov569efa22014-02-18 18:02:19 -0500634 self._loop.call_exception_handler({
Victor Stinner0ee29c22014-02-19 01:40:41 +0100635 'message': message,
Yury Selivanov569efa22014-02-18 18:02:19 -0500636 'exception': exc,
637 'transport': self,
638 'protocol': self._protocol,
639 })
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700640 self._close(exc)
641
642 def _close(self, exc=None):
643 self._closing = True
644 if self._buffer:
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400645 self._loop._remove_writer(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646 self._buffer.clear()
Yury Selivanov5b8d4f92016-10-05 17:48:59 -0400647 self._loop._remove_reader(self._fileno)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700648 self._loop.call_soon(self._call_connection_lost, exc)
649
650 def _call_connection_lost(self, exc):
651 try:
652 self._protocol.connection_lost(exc)
653 finally:
654 self._pipe.close()
655 self._pipe = None
656 self._protocol = None
657 self._loop = None
658
659
Victor Stinner1e40f102014-12-11 23:30:17 +0100660if hasattr(os, 'set_inheritable'):
661 # Python 3.4 and newer
662 _set_inheritable = os.set_inheritable
663else:
664 import fcntl
665
666 def _set_inheritable(fd, inheritable):
667 cloexec_flag = getattr(fcntl, 'FD_CLOEXEC', 1)
668
669 old = fcntl.fcntl(fd, fcntl.F_GETFD)
670 if not inheritable:
671 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
672 else:
673 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
674
675
Guido van Rossum59691282013-10-30 14:52:03 -0700676class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700677
Guido van Rossum59691282013-10-30 14:52:03 -0700678 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700679 stdin_w = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700680 if stdin == subprocess.PIPE:
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700681 # Use a socket pair for stdin, since not all platforms
682 # support selecting read events on the write end of a
683 # socket (which we use in order to detect closing of the
684 # other end). Notably this is needed on AIX, and works
685 # just fine on other platforms.
686 stdin, stdin_w = self._loop._socketpair()
Victor Stinner1e40f102014-12-11 23:30:17 +0100687
688 # Mark the write end of the stdin pipe as non-inheritable,
689 # needed by close_fds=False on Python 3.3 and older
690 # (Python 3.4 implements the PEP 446, socketpair returns
691 # non-inheritable sockets)
692 _set_inheritable(stdin_w.fileno(), False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700693 self._proc = subprocess.Popen(
694 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
695 universal_newlines=False, bufsize=bufsize, **kwargs)
Guido van Rossum934f6ea2013-10-21 20:37:14 -0700696 if stdin_w is not None:
697 stdin.close()
Victor Stinner2dba23a2014-07-03 00:59:00 +0200698 self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800699
700
701class AbstractChildWatcher:
702 """Abstract base class for monitoring child processes.
703
704 Objects derived from this class monitor a collection of subprocesses and
705 report their termination or interruption by a signal.
706
707 New callbacks are registered with .add_child_handler(). Starting a new
708 process must be done within a 'with' block to allow the watcher to suspend
709 its activity until the new process if fully registered (this is needed to
710 prevent a race condition in some implementations).
711
712 Example:
713 with watcher:
714 proc = subprocess.Popen("sleep 1")
715 watcher.add_child_handler(proc.pid, callback)
716
717 Notes:
718 Implementations of this class must be thread-safe.
719
720 Since child watcher objects may catch the SIGCHLD signal and call
721 waitpid(-1), there should be only one active object per process.
722 """
723
724 def add_child_handler(self, pid, callback, *args):
725 """Register a new child handler.
726
727 Arrange for callback(pid, returncode, *args) to be called when
728 process 'pid' terminates. Specifying another callback for the same
729 process replaces the previous handler.
730
Victor Stinneracdb7822014-07-14 18:33:40 +0200731 Note: callback() must be thread-safe.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800732 """
733 raise NotImplementedError()
734
735 def remove_child_handler(self, pid):
736 """Removes the handler for process 'pid'.
737
738 The function returns True if the handler was successfully removed,
739 False if there was nothing to remove."""
740
741 raise NotImplementedError()
742
Guido van Rossum2bcae702013-11-13 15:50:08 -0800743 def attach_loop(self, loop):
744 """Attach the watcher to an event loop.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800745
Guido van Rossum2bcae702013-11-13 15:50:08 -0800746 If the watcher was previously attached to an event loop, then it is
747 first detached before attaching to the new loop.
748
749 Note: loop may be None.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800750 """
751 raise NotImplementedError()
752
753 def close(self):
754 """Close the watcher.
755
756 This must be called to make sure that any underlying resource is freed.
757 """
758 raise NotImplementedError()
759
760 def __enter__(self):
761 """Enter the watcher's context and allow starting new processes
762
763 This function must return self"""
764 raise NotImplementedError()
765
766 def __exit__(self, a, b, c):
767 """Exit the watcher's context"""
768 raise NotImplementedError()
769
770
771class BaseChildWatcher(AbstractChildWatcher):
772
Guido van Rossum2bcae702013-11-13 15:50:08 -0800773 def __init__(self):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800774 self._loop = None
Yury Selivanov9eb6c672016-10-05 16:57:12 -0400775 self._callbacks = {}
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800776
777 def close(self):
Guido van Rossum2bcae702013-11-13 15:50:08 -0800778 self.attach_loop(None)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800779
780 def _do_waitpid(self, expected_pid):
781 raise NotImplementedError()
782
783 def _do_waitpid_all(self):
784 raise NotImplementedError()
785
Guido van Rossum2bcae702013-11-13 15:50:08 -0800786 def attach_loop(self, loop):
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800787 assert loop is None or isinstance(loop, events.AbstractEventLoop)
788
Yury Selivanov9eb6c672016-10-05 16:57:12 -0400789 if self._loop is not None and loop is None and self._callbacks:
790 warnings.warn(
791 'A loop is being detached '
792 'from a child watcher with pending handlers',
793 RuntimeWarning)
794
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800795 if self._loop is not None:
796 self._loop.remove_signal_handler(signal.SIGCHLD)
797
798 self._loop = loop
799 if loop is not None:
800 loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
801
802 # Prevent a race condition in case a child terminated
803 # during the switch.
804 self._do_waitpid_all()
805
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800806 def _sig_chld(self):
807 try:
808 self._do_waitpid_all()
Yury Selivanov569efa22014-02-18 18:02:19 -0500809 except Exception as exc:
810 # self._loop should always be available here
811 # as '_sig_chld' is added as a signal handler
812 # in 'attach_loop'
813 self._loop.call_exception_handler({
814 'message': 'Unknown exception in SIGCHLD handler',
815 'exception': exc,
816 })
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800817
818 def _compute_returncode(self, status):
819 if os.WIFSIGNALED(status):
820 # The child process died because of a signal.
821 return -os.WTERMSIG(status)
822 elif os.WIFEXITED(status):
823 # The child process exited (e.g sys.exit()).
824 return os.WEXITSTATUS(status)
825 else:
826 # The child exited, but we don't understand its status.
827 # This shouldn't happen, but if it does, let's just
828 # return that status; perhaps that helps debug it.
829 return status
830
831
832class SafeChildWatcher(BaseChildWatcher):
833 """'Safe' child watcher implementation.
834
835 This implementation avoids disrupting other code spawning processes by
836 polling explicitly each process in the SIGCHLD handler instead of calling
837 os.waitpid(-1).
838
839 This is a safe solution but it has a significant overhead when handling a
840 big number of children (O(n) each time SIGCHLD is raised)
841 """
842
Guido van Rossum2bcae702013-11-13 15:50:08 -0800843 def close(self):
844 self._callbacks.clear()
845 super().close()
846
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800847 def __enter__(self):
848 return self
849
850 def __exit__(self, a, b, c):
851 pass
852
853 def add_child_handler(self, pid, callback, *args):
Yury Selivanov9eb6c672016-10-05 16:57:12 -0400854 if self._loop is None:
855 raise RuntimeError(
856 "Cannot add child handler, "
857 "the child watcher does not have a loop attached")
858
Victor Stinner47cd10d2015-01-30 00:05:19 +0100859 self._callbacks[pid] = (callback, args)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800860
861 # Prevent a race condition in case the child is already terminated.
862 self._do_waitpid(pid)
863
Guido van Rossum2bcae702013-11-13 15:50:08 -0800864 def remove_child_handler(self, pid):
865 try:
866 del self._callbacks[pid]
867 return True
868 except KeyError:
869 return False
870
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800871 def _do_waitpid_all(self):
872
873 for pid in list(self._callbacks):
874 self._do_waitpid(pid)
875
876 def _do_waitpid(self, expected_pid):
877 assert expected_pid > 0
878
879 try:
880 pid, status = os.waitpid(expected_pid, os.WNOHANG)
881 except ChildProcessError:
882 # The child process is already reaped
883 # (may happen if waitpid() is called elsewhere).
884 pid = expected_pid
885 returncode = 255
886 logger.warning(
887 "Unknown child process pid %d, will report returncode 255",
888 pid)
889 else:
890 if pid == 0:
891 # The child process is still alive.
892 return
893
894 returncode = self._compute_returncode(status)
Victor Stinneracdb7822014-07-14 18:33:40 +0200895 if self._loop.get_debug():
896 logger.debug('process %s exited with returncode %s',
897 expected_pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800898
899 try:
900 callback, args = self._callbacks.pop(pid)
901 except KeyError: # pragma: no cover
902 # May happen if .remove_child_handler() is called
903 # after os.waitpid() returns.
Victor Stinnerb2614752014-08-25 23:20:52 +0200904 if self._loop.get_debug():
905 logger.warning("Child watcher got an unexpected pid: %r",
906 pid, exc_info=True)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800907 else:
908 callback(pid, returncode, *args)
909
910
911class FastChildWatcher(BaseChildWatcher):
912 """'Fast' child watcher implementation.
913
914 This implementation reaps every terminated processes by calling
915 os.waitpid(-1) directly, possibly breaking other code spawning processes
916 and waiting for their termination.
917
918 There is no noticeable overhead when handling a big number of children
919 (O(1) each time a child terminates).
920 """
Guido van Rossum2bcae702013-11-13 15:50:08 -0800921 def __init__(self):
922 super().__init__()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800923 self._lock = threading.Lock()
924 self._zombies = {}
925 self._forks = 0
926
927 def close(self):
Guido van Rossum2bcae702013-11-13 15:50:08 -0800928 self._callbacks.clear()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800929 self._zombies.clear()
Guido van Rossum2bcae702013-11-13 15:50:08 -0800930 super().close()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800931
932 def __enter__(self):
933 with self._lock:
934 self._forks += 1
935
936 return self
937
938 def __exit__(self, a, b, c):
939 with self._lock:
940 self._forks -= 1
941
942 if self._forks or not self._zombies:
943 return
944
945 collateral_victims = str(self._zombies)
946 self._zombies.clear()
947
948 logger.warning(
949 "Caught subprocesses termination from unknown pids: %s",
950 collateral_victims)
951
952 def add_child_handler(self, pid, callback, *args):
953 assert self._forks, "Must use the context manager"
Yury Selivanov9eb6c672016-10-05 16:57:12 -0400954
955 if self._loop is None:
956 raise RuntimeError(
957 "Cannot add child handler, "
958 "the child watcher does not have a loop attached")
959
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800960 with self._lock:
961 try:
962 returncode = self._zombies.pop(pid)
963 except KeyError:
964 # The child is running.
965 self._callbacks[pid] = callback, args
966 return
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800967
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800968 # The child is dead already. We can fire the callback.
969 callback(pid, returncode, *args)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800970
Guido van Rossum2bcae702013-11-13 15:50:08 -0800971 def remove_child_handler(self, pid):
972 try:
973 del self._callbacks[pid]
974 return True
975 except KeyError:
976 return False
977
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800978 def _do_waitpid_all(self):
979 # Because of signal coalescing, we must keep calling waitpid() as
980 # long as we're able to reap a child.
981 while True:
982 try:
983 pid, status = os.waitpid(-1, os.WNOHANG)
984 except ChildProcessError:
985 # No more child processes exist.
986 return
987 else:
988 if pid == 0:
989 # A child process is still alive.
990 return
991
992 returncode = self._compute_returncode(status)
993
Guido van Rossumab27a9f2014-01-25 16:32:17 -0800994 with self._lock:
995 try:
996 callback, args = self._callbacks.pop(pid)
997 except KeyError:
998 # unknown child
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800999 if self._forks:
1000 # It may not be registered yet.
1001 self._zombies[pid] = returncode
Victor Stinneracdb7822014-07-14 18:33:40 +02001002 if self._loop.get_debug():
1003 logger.debug('unknown process %s exited '
1004 'with returncode %s',
1005 pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001006 continue
Guido van Rossumab27a9f2014-01-25 16:32:17 -08001007 callback = None
Victor Stinneracdb7822014-07-14 18:33:40 +02001008 else:
1009 if self._loop.get_debug():
1010 logger.debug('process %s exited with returncode %s',
1011 pid, returncode)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001012
Guido van Rossumab27a9f2014-01-25 16:32:17 -08001013 if callback is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001014 logger.warning(
1015 "Caught subprocess termination from unknown pid: "
1016 "%d -> %d", pid, returncode)
1017 else:
1018 callback(pid, returncode, *args)
1019
1020
1021class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
Victor Stinner70db9e42015-01-09 21:32:05 +01001022 """UNIX event loop policy with a watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001023 _loop_factory = _UnixSelectorEventLoop
1024
1025 def __init__(self):
1026 super().__init__()
1027 self._watcher = None
1028
1029 def _init_watcher(self):
1030 with events._lock:
1031 if self._watcher is None: # pragma: no branch
Guido van Rossum2bcae702013-11-13 15:50:08 -08001032 self._watcher = SafeChildWatcher()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001033 if isinstance(threading.current_thread(),
1034 threading._MainThread):
Guido van Rossum2bcae702013-11-13 15:50:08 -08001035 self._watcher.attach_loop(self._local._loop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001036
1037 def set_event_loop(self, loop):
1038 """Set the event loop.
1039
1040 As a side effect, if a child watcher was set before, then calling
Guido van Rossum2bcae702013-11-13 15:50:08 -08001041 .set_event_loop() from the main thread will call .attach_loop(loop) on
1042 the child watcher.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001043 """
1044
1045 super().set_event_loop(loop)
1046
1047 if self._watcher is not None and \
1048 isinstance(threading.current_thread(), threading._MainThread):
Guido van Rossum2bcae702013-11-13 15:50:08 -08001049 self._watcher.attach_loop(loop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001050
1051 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +02001052 """Get the watcher for child processes.
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001053
1054 If not yet set, a SafeChildWatcher object is automatically created.
1055 """
1056 if self._watcher is None:
1057 self._init_watcher()
1058
1059 return self._watcher
1060
1061 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +02001062 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08001063
1064 assert watcher is None or isinstance(watcher, AbstractChildWatcher)
1065
1066 if self._watcher is not None:
1067 self._watcher.close()
1068
1069 self._watcher = watcher
1070
1071SelectorEventLoop = _UnixSelectorEventLoop
1072DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy