Debian Codegraph @

Lib/asyncio/unix_events.py

raw
1 """Selector event loop for Unix with signal handling."""
2
3 import errno
4 import io
5 import itertools
6 import os
7 import selectors
8 import signal
9 import socket
10 import stat
11 import subprocess
12 import sys
13 import threading
14 import warnings
15
16 from . import base_events
17 from . import base_subprocess
18 from . import constants
19 from . import coroutines
20 from . import events
21 from . import exceptions
22 from . import futures
23 from . import selector_events
24 from . import tasks
25 from . import transports
26 from .log import logger
27
28
29 __all__ = (
30 'SelectorEventLoop',
31 'AbstractChildWatcher', 'SafeChildWatcher',
32 'FastChildWatcher', 'PidfdChildWatcher',
33 'MultiLoopChildWatcher', 'ThreadedChildWatcher',
34 'DefaultEventLoopPolicy',
35 'EventLoop',
36 )
37
38
39 if sys.platform == 'win32': # pragma: no cover
40 raise ImportError('Signals are not really supported on Windows')
41
42
43 def _sighandler_noop(signum, frame):
44 """Dummy signal handler."""
45 pass
46
47
48 def waitstatus_to_exitcode(status):
49 try:
50 return os.waitstatus_to_exitcode(status)
51 except ValueError:
52 # The child exited, but we don't understand its status.
53 # This shouldn't happen, but if it does, let's just
54 # return that status; perhaps that helps debug it.
55 return status
56
57
58 class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
59 """Unix event loop.
60
61 Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
62 """
63
64 def __init__(self, selector=None):
65 super().__init__(selector)
66 self._signal_handlers = {}
67 self._unix_server_sockets = {}
68
69 def close(self):
70 super().close()
71 if not sys.is_finalizing():
72 for sig in list(self._signal_handlers):
73 self.remove_signal_handler(sig)
74 else:
75 if self._signal_handlers:
76 warnings.warn(f"Closing the loop {self!r} "
77 f"on interpreter shutdown "
78 f"stage, skipping signal handlers removal",
79 ResourceWarning,
80 source=self)
81 self._signal_handlers.clear()
82
83 def _process_self_data(self, data):
84 for signum in data:
85 if not signum:
86 # ignore null bytes written by _write_to_self()
87 continue
88 self._handle_signal(signum)
89
90 def add_signal_handler(self, sig, callback, *args):
91 """Add a handler for a signal. UNIX only.
92
93 Raise ValueError if the signal number is invalid or uncatchable.
94 Raise RuntimeError if there is a problem setting up the handler.
95 """
96 if (coroutines.iscoroutine(callback) or
97 coroutines.iscoroutinefunction(callback)):
98 raise TypeError("coroutines cannot be used "
99 "with add_signal_handler()")
100 self._check_signal(sig)
101 self._check_closed()
102 try:
103 # set_wakeup_fd() raises ValueError if this is not the
104 # main thread. By calling it early we ensure that an
105 # event loop running in another thread cannot add a signal
106 # handler.
107 signal.set_wakeup_fd(self._csock.fileno())
108 except (ValueError, OSError) as exc:
109 raise RuntimeError(str(exc))
110
111 handle = events.Handle(callback, args, self, None)
112 self._signal_handlers[sig] = handle
113
114 try:
115 # Register a dummy signal handler to ask Python to write the signal
116 # number in the wakeup file descriptor. _process_self_data() will
117 # read signal numbers from this file descriptor to handle signals.
118 signal.signal(sig, _sighandler_noop)
119
120 # Set SA_RESTART to limit EINTR occurrences.
121 signal.siginterrupt(sig, False)
122 except OSError as exc:
123 del self._signal_handlers[sig]
124 if not self._signal_handlers:
125 try:
126 signal.set_wakeup_fd(-1)
127 except (ValueError, OSError) as nexc:
128 logger.info('set_wakeup_fd(-1) failed: %s', nexc)
129
130 if exc.errno == errno.EINVAL:
131 raise RuntimeError(f'sig {sig} cannot be caught')
132 else:
133 raise
134
135 def _handle_signal(self, sig):
136 """Internal helper that is the actual signal handler."""
137 handle = self._signal_handlers.get(sig)
138 if handle is None:
139 return # Assume it's some race condition.
140 if handle._cancelled:
141 self.remove_signal_handler(sig) # Remove it properly.
142 else:
143 self._add_callback_signalsafe(handle)
144
145 def remove_signal_handler(self, sig):
146 """Remove a handler for a signal. UNIX only.
147
148 Return True if a signal handler was removed, False if not.
149 """
150 self._check_signal(sig)
151 try:
152 del self._signal_handlers[sig]
153 except KeyError:
154 return False
155
156 if sig == signal.SIGINT:
157 handler = signal.default_int_handler
158 else:
159 handler = signal.SIG_DFL
160
161 try:
162 signal.signal(sig, handler)
163 except OSError as exc:
164 if exc.errno == errno.EINVAL:
165 raise RuntimeError(f'sig {sig} cannot be caught')
166 else:
167 raise
168
169 if not self._signal_handlers:
170 try:
171 signal.set_wakeup_fd(-1)
172 except (ValueError, OSError) as exc:
173 logger.info('set_wakeup_fd(-1) failed: %s', exc)
174
175 return True
176
177 def _check_signal(self, sig):
178 """Internal helper to validate a signal.
179
180 Raise ValueError if the signal number is invalid or uncatchable.
181 Raise RuntimeError if there is a problem setting up the handler.
182 """
183 if not isinstance(sig, int):
184 raise TypeError(f'sig must be an int, not {sig!r}')
185
186 if sig not in signal.valid_signals():
187 raise ValueError(f'invalid signal number {sig}')
188
189 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
190 extra=None):
191 return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
192
193 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
194 extra=None):
195 return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
196
197 async def _make_subprocess_transport(self, protocol, args, shell,
198 stdin, stdout, stderr, bufsize,
199 extra=None, **kwargs):
200 with warnings.catch_warnings():
201 warnings.simplefilter('ignore', DeprecationWarning)
202 watcher = events.get_child_watcher()
203
204 with watcher:
205 if not watcher.is_active():
206 # Check early.
207 # Raising exception before process creation
208 # prevents subprocess execution if the watcher
209 # is not ready to handle it.
210 raise RuntimeError("asyncio.get_child_watcher() is not activated, "
211 "subprocess support is not installed.")
212 waiter = self.create_future()
213 transp = _UnixSubprocessTransport(self, protocol, args, shell,
214 stdin, stdout, stderr, bufsize,
215 waiter=waiter, extra=extra,
216 **kwargs)
217 watcher.add_child_handler(transp.get_pid(),
218 self._child_watcher_callback, transp)
219 try:
220 await waiter
221 except (SystemExit, KeyboardInterrupt):
222 raise
223 except BaseException:
224 transp.close()
225 await transp._wait()
226 raise
227
228 return transp
229
230 def _child_watcher_callback(self, pid, returncode, transp):
231 self.call_soon_threadsafe(transp._process_exited, returncode)
232
233 async def create_unix_connection(
234 self, protocol_factory, path=None, *,
235 ssl=None, sock=None,
236 server_hostname=None,
237 ssl_handshake_timeout=None,
238 ssl_shutdown_timeout=None):
239 assert server_hostname is None or isinstance(server_hostname, str)
240 if ssl:
241 if server_hostname is None:
242 raise ValueError(
243 'you have to pass server_hostname when using ssl')
244 else:
245 if server_hostname is not None:
246 raise ValueError('server_hostname is only meaningful with ssl')
247 if ssl_handshake_timeout is not None:
248 raise ValueError(
249 'ssl_handshake_timeout is only meaningful with ssl')
250 if ssl_shutdown_timeout is not None:
251 raise ValueError(
252 'ssl_shutdown_timeout is only meaningful with ssl')
253
254 if path is not None:
255 if sock is not None:
256 raise ValueError(
257 'path and sock can not be specified at the same time')
258
259 path = os.fspath(path)
260 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
261 try:
262 sock.setblocking(False)
263 await self.sock_connect(sock, path)
264 except:
265 sock.close()
266 raise
267
268 else:
269 if sock is None:
270 raise ValueError('no path and sock were specified')
271 if (sock.family != socket.AF_UNIX or
272 sock.type != socket.SOCK_STREAM):
273 raise ValueError(
274 f'A UNIX Domain Stream Socket was expected, got {sock!r}')
275 sock.setblocking(False)
276
277 transport, protocol = await self._create_connection_transport(
278 sock, protocol_factory, ssl, server_hostname,
279 ssl_handshake_timeout=ssl_handshake_timeout,
280 ssl_shutdown_timeout=ssl_shutdown_timeout)
281 return transport, protocol
282
283 async def create_unix_server(
284 self, protocol_factory, path=None, *,
285 sock=None, backlog=100, ssl=None,
286 ssl_handshake_timeout=None,
287 ssl_shutdown_timeout=None,
288 start_serving=True, cleanup_socket=True):
289 if isinstance(ssl, bool):
290 raise TypeError('ssl argument must be an SSLContext or None')
291
292 if ssl_handshake_timeout is not None and not ssl:
293 raise ValueError(
294 'ssl_handshake_timeout is only meaningful with ssl')
295
296 if ssl_shutdown_timeout is not None and not ssl:
297 raise ValueError(
298 'ssl_shutdown_timeout is only meaningful with ssl')
299
300 if path is not None:
301 if sock is not None:
302 raise ValueError(
303 'path and sock can not be specified at the same time')
304
305 path = os.fspath(path)
306 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
307
308 # Check for abstract socket. `str` and `bytes` paths are supported.
309 if path[0] not in (0, '\x00'):
310 try:
311 if stat.S_ISSOCK(os.stat(path).st_mode):
312 os.remove(path)
313 except FileNotFoundError:
314 pass
315 except OSError as err:
316 # Directory may have permissions only to create socket.
317 logger.error('Unable to check or remove stale UNIX socket '
318 '%r: %r', path, err)
319
320 try:
321 sock.bind(path)
322 except OSError as exc:
323 sock.close()
324 if exc.errno == errno.EADDRINUSE:
325 # Let's improve the error message by adding
326 # with what exact address it occurs.
327 msg = f'Address {path!r} is already in use'
328 raise OSError(errno.EADDRINUSE, msg) from None
329 else:
330 raise
331 except:
332 sock.close()
333 raise
334 else:
335 if sock is None:
336 raise ValueError(
337 'path was not specified, and no sock specified')
338
339 if (sock.family != socket.AF_UNIX or
340 sock.type != socket.SOCK_STREAM):
341 raise ValueError(
342 f'A UNIX Domain Stream Socket was expected, got {sock!r}')
343
344 if cleanup_socket:
345 path = sock.getsockname()
346 # Check for abstract socket. `str` and `bytes` paths are supported.
347 if path[0] not in (0, '\x00'):
348 try:
349 self._unix_server_sockets[sock] = os.stat(path).st_ino
350 except FileNotFoundError:
351 pass
352
353 sock.setblocking(False)
354 server = base_events.Server(self, [sock], protocol_factory,
355 ssl, backlog, ssl_handshake_timeout,
356 ssl_shutdown_timeout)
357 if start_serving:
358 server._start_serving()
359 # Skip one loop iteration so that all 'loop.add_reader'
360 # go through.
361 await tasks.sleep(0)
362
363 return server
364
365 async def _sock_sendfile_native(self, sock, file, offset, count):
366 try:
367 os.sendfile
368 except AttributeError:
369 raise exceptions.SendfileNotAvailableError(
370 "os.sendfile() is not available")
371 try:
372 fileno = file.fileno()
373 except (AttributeError, io.UnsupportedOperation) as err:
374 raise exceptions.SendfileNotAvailableError("not a regular file")
375 try:
376 fsize = os.fstat(fileno).st_size
377 except OSError:
378 raise exceptions.SendfileNotAvailableError("not a regular file")
379 blocksize = count if count else fsize
380 if not blocksize:
381 return 0 # empty file
382
383 fut = self.create_future()
384 self._sock_sendfile_native_impl(fut, None, sock, fileno,
385 offset, count, blocksize, 0)
386 return await fut
387
388 def _sock_sendfile_native_impl(self, fut, registered_fd, sock, fileno,
389 offset, count, blocksize, total_sent):
390 fd = sock.fileno()
391 if registered_fd is not None:
392 # Remove the callback early. It should be rare that the
393 # selector says the fd is ready but the call still returns
394 # EAGAIN, and I am willing to take a hit in that case in
395 # order to simplify the common case.
396 self.remove_writer(registered_fd)
397 if fut.cancelled():
398 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
399 return
400 if count:
401 blocksize = count - total_sent
402 if blocksize <= 0:
403 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
404 fut.set_result(total_sent)
405 return
406
407 # On 32-bit architectures truncate to 1GiB to avoid OverflowError
408 blocksize = min(blocksize, sys.maxsize//2 + 1)
409
410 try:
411 sent = os.sendfile(fd, fileno, offset, blocksize)
412 except (BlockingIOError, InterruptedError):
413 if registered_fd is None:
414 self._sock_add_cancellation_callback(fut, sock)
415 self.add_writer(fd, self._sock_sendfile_native_impl, fut,
416 fd, sock, fileno,
417 offset, count, blocksize, total_sent)
418 except OSError as exc:
419 if (registered_fd is not None and
420 exc.errno == errno.ENOTCONN and
421 type(exc) is not ConnectionError):
422 # If we have an ENOTCONN and this isn't a first call to
423 # sendfile(), i.e. the connection was closed in the middle
424 # of the operation, normalize the error to ConnectionError
425 # to make it consistent across all Posix systems.
426 new_exc = ConnectionError(
427 "socket is not connected", errno.ENOTCONN)
428 new_exc.__cause__ = exc
429 exc = new_exc
430 if total_sent == 0:
431 # We can get here for different reasons, the main
432 # one being 'file' is not a regular mmap(2)-like
433 # file, in which case we'll fall back on using
434 # plain send().
435 err = exceptions.SendfileNotAvailableError(
436 "os.sendfile call failed")
437 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
438 fut.set_exception(err)
439 else:
440 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
441 fut.set_exception(exc)
442 except (SystemExit, KeyboardInterrupt):
443 raise
444 except BaseException as exc:
445 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
446 fut.set_exception(exc)
447 else:
448 if sent == 0:
449 # EOF
450 self._sock_sendfile_update_filepos(fileno, offset, total_sent)
451 fut.set_result(total_sent)
452 else:
453 offset += sent
454 total_sent += sent
455 if registered_fd is None:
456 self._sock_add_cancellation_callback(fut, sock)
457 self.add_writer(fd, self._sock_sendfile_native_impl, fut,
458 fd, sock, fileno,
459 offset, count, blocksize, total_sent)
460
461 def _sock_sendfile_update_filepos(self, fileno, offset, total_sent):
462 if total_sent > 0:
463 os.lseek(fileno, offset, os.SEEK_SET)
464
465 def _sock_add_cancellation_callback(self, fut, sock):
466 def cb(fut):
467 if fut.cancelled():
468 fd = sock.fileno()
469 if fd != -1:
470 self.remove_writer(fd)
471 fut.add_done_callback(cb)
472
473 def _stop_serving(self, sock):
474 # Is this a unix socket that needs cleanup?
475 if sock in self._unix_server_sockets:
476 path = sock.getsockname()
477 else:
478 path = None
479
480 super()._stop_serving(sock)
481
482 if path is not None:
483 prev_ino = self._unix_server_sockets[sock]
484 del self._unix_server_sockets[sock]
485 try:
486 if os.stat(path).st_ino == prev_ino:
487 os.unlink(path)
488 except FileNotFoundError:
489 pass
490 except OSError as err:
491 logger.error('Unable to clean up listening UNIX socket '
492 '%r: %r', path, err)
493
494
495 class _UnixReadPipeTransport(transports.ReadTransport):
496
497 max_size = 256 * 1024 # max bytes we read in one event loop iteration
498
499 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
500 super().__init__(extra)
501 self._extra['pipe'] = pipe
502 self._loop = loop
503 self._pipe = pipe
504 self._fileno = pipe.fileno()
505 self._protocol = protocol
506 self._closing = False
507 self._paused = False
508
509 mode = os.fstat(self._fileno).st_mode
510 if not (stat.S_ISFIFO(mode) or
511 stat.S_ISSOCK(mode) or
512 stat.S_ISCHR(mode)):
513 self._pipe = None
514 self._fileno = None
515 self._protocol = None
516 raise ValueError("Pipe transport is for pipes/sockets only.")
517
518 os.set_blocking(self._fileno, False)
519
520 self._loop.call_soon(self._protocol.connection_made, self)
521 # only start reading when connection_made() has been called
522 self._loop.call_soon(self._add_reader,
523 self._fileno, self._read_ready)
524 if waiter is not None:
525 # only wake up the waiter when connection_made() has been called
526 self._loop.call_soon(futures._set_result_unless_cancelled,
527 waiter, None)
528
529 def _add_reader(self, fd, callback):
530 if not self.is_reading():
531 return
532 self._loop._add_reader(fd, callback)
533
534 def is_reading(self):
535 return not self._paused and not self._closing
536
537 def __repr__(self):
538 info = [self.__class__.__name__]
539 if self._pipe is None:
540 info.append('closed')
541 elif self._closing:
542 info.append('closing')
543 info.append(f'fd={self._fileno}')
544 selector = getattr(self._loop, '_selector', None)
545 if self._pipe is not None and selector is not None:
546 polling = selector_events._test_selector_event(
547 selector, self._fileno, selectors.EVENT_READ)
548 if polling:
549 info.append('polling')
550 else:
551 info.append('idle')
552 elif self._pipe is not None:
553 info.append('open')
554 else:
555 info.append('closed')
556 return '<{}>'.format(' '.join(info))
557
558 def _read_ready(self):
559 try:
560 data = os.read(self._fileno, self.max_size)
561 except (BlockingIOError, InterruptedError):
562 pass
563 except OSError as exc:
564 self._fatal_error(exc, 'Fatal read error on pipe transport')
565 else:
566 if data:
567 self._protocol.data_received(data)
568 else:
569 if self._loop.get_debug():
570 logger.info("%r was closed by peer", self)
571 self._closing = True
572 self._loop._remove_reader(self._fileno)
573 self._loop.call_soon(self._protocol.eof_received)
574 self._loop.call_soon(self._call_connection_lost, None)
575
576 def pause_reading(self):
577 if not self.is_reading():
578 return
579 self._paused = True
580 self._loop._remove_reader(self._fileno)
581 if self._loop.get_debug():
582 logger.debug("%r pauses reading", self)
583
584 def resume_reading(self):
585 if self._closing or not self._paused:
586 return
587 self._paused = False
588 self._loop._add_reader(self._fileno, self._read_ready)
589 if self._loop.get_debug():
590 logger.debug("%r resumes reading", self)
591
592 def set_protocol(self, protocol):
593 self._protocol = protocol
594
595 def get_protocol(self):
596 return self._protocol
597
598 def is_closing(self):
599 return self._closing
600
601 def close(self):
602 if not self._closing:
603 self._close(None)
604
605 def __del__(self, _warn=warnings.warn):
606 if self._pipe is not None:
607 _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
608 self._pipe.close()
609
610 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
611 # should be called by exception handler only
612 if (isinstance(exc, OSError) and exc.errno == errno.EIO):
613 if self._loop.get_debug():
614 logger.debug("%r: %s", self, message, exc_info=True)
615 else:
616 self._loop.call_exception_handler({
617 'message': message,
618 'exception': exc,
619 'transport': self,
620 'protocol': self._protocol,
621 })
622 self._close(exc)
623
624 def _close(self, exc):
625 self._closing = True
626 self._loop._remove_reader(self._fileno)
627 self._loop.call_soon(self._call_connection_lost, exc)
628
629 def _call_connection_lost(self, exc):
630 try:
631 self._protocol.connection_lost(exc)
632 finally:
633 self._pipe.close()
634 self._pipe = None
635 self._protocol = None
636 self._loop = None
637
638
639 class _UnixWritePipeTransport(transports._FlowControlMixin,
640 transports.WriteTransport):
641
642 def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
643 super().__init__(extra, loop)
644 self._extra['pipe'] = pipe
645 self._pipe = pipe
646 self._fileno = pipe.fileno()
647 self._protocol = protocol
648 self._buffer = bytearray()
649 self._conn_lost = 0
650 self._closing = False # Set when close() or write_eof() called.
651
652 mode = os.fstat(self._fileno).st_mode
653 is_char = stat.S_ISCHR(mode)
654 is_fifo = stat.S_ISFIFO(mode)
655 is_socket = stat.S_ISSOCK(mode)
656 if not (is_char or is_fifo or is_socket):
657 self._pipe = None
658 self._fileno = None
659 self._protocol = None
660 raise ValueError("Pipe transport is only for "
661 "pipes, sockets and character devices")
662
663 os.set_blocking(self._fileno, False)
664 self._loop.call_soon(self._protocol.connection_made, self)
665
666 # On AIX, the reader trick (to be notified when the read end of the
667 # socket is closed) only works for sockets. On other platforms it
668 # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
669 if is_socket or (is_fifo and not sys.platform.startswith("aix")):
670 # only start reading when connection_made() has been called
671 self._loop.call_soon(self._loop._add_reader,
672 self._fileno, self._read_ready)
673
674 if waiter is not None:
675 # only wake up the waiter when connection_made() has been called
676 self._loop.call_soon(futures._set_result_unless_cancelled,
677 waiter, None)
678
679 def __repr__(self):
680 info = [self.__class__.__name__]
681 if self._pipe is None:
682 info.append('closed')
683 elif self._closing:
684 info.append('closing')
685 info.append(f'fd={self._fileno}')
686 selector = getattr(self._loop, '_selector', None)
687 if self._pipe is not None and selector is not None:
688 polling = selector_events._test_selector_event(
689 selector, self._fileno, selectors.EVENT_WRITE)
690 if polling:
691 info.append('polling')
692 else:
693 info.append('idle')
694
695 bufsize = self.get_write_buffer_size()
696 info.append(f'bufsize={bufsize}')
697 elif self._pipe is not None:
698 info.append('open')
699 else:
700 info.append('closed')
701 return '<{}>'.format(' '.join(info))
702
703 def get_write_buffer_size(self):
704 return len(self._buffer)
705
706 def _read_ready(self):
707 # Pipe was closed by peer.
708 if self._loop.get_debug():
709 logger.info("%r was closed by peer", self)
710 if self._buffer:
711 self._close(BrokenPipeError())
712 else:
713 self._close()
714
715 def write(self, data):
716 assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
717 if isinstance(data, bytearray):
718 data = memoryview(data)
719 if not data:
720 return
721
722 if self._conn_lost or self._closing:
723 if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
724 logger.warning('pipe closed by peer or '
725 'os.write(pipe, data) raised exception.')
726 self._conn_lost += 1
727 return
728
729 if not self._buffer:
730 # Attempt to send it right away first.
731 try:
732 n = os.write(self._fileno, data)
733 except (BlockingIOError, InterruptedError):
734 n = 0
735 except (SystemExit, KeyboardInterrupt):
736 raise
737 except BaseException as exc:
738 self._conn_lost += 1
739 self._fatal_error(exc, 'Fatal write error on pipe transport')
740 return
741 if n == len(data):
742 return
743 elif n > 0:
744 data = memoryview(data)[n:]
745 self._loop._add_writer(self._fileno, self._write_ready)
746
747 self._buffer += data
748 self._maybe_pause_protocol()
749
750 def _write_ready(self):
751 assert self._buffer, 'Data should not be empty'
752
753 try:
754 n = os.write(self._fileno, self._buffer)
755 except (BlockingIOError, InterruptedError):
756 pass
757 except (SystemExit, KeyboardInterrupt):
758 raise
759 except BaseException as exc:
760 self._buffer.clear()
761 self._conn_lost += 1
762 # Remove writer here, _fatal_error() doesn't it
763 # because _buffer is empty.
764 self._loop._remove_writer(self._fileno)
765 self._fatal_error(exc, 'Fatal write error on pipe transport')
766 else:
767 if n == len(self._buffer):
768 self._buffer.clear()
769 self._loop._remove_writer(self._fileno)
770 self._maybe_resume_protocol() # May append to buffer.
771 if self._closing:
772 self._loop._remove_reader(self._fileno)
773 self._call_connection_lost(None)
774 return
775 elif n > 0:
776 del self._buffer[:n]
777
778 def can_write_eof(self):
779 return True
780
781 def write_eof(self):
782 if self._closing:
783 return
784 assert self._pipe
785 self._closing = True
786 if not self._buffer:
787 self._loop._remove_reader(self._fileno)
788 self._loop.call_soon(self._call_connection_lost, None)
789
790 def set_protocol(self, protocol):
791 self._protocol = protocol
792
793 def get_protocol(self):
794 return self._protocol
795
796 def is_closing(self):
797 return self._closing
798
799 def close(self):
800 if self._pipe is not None and not self._closing:
801 # write_eof is all what we needed to close the write pipe
802 self.write_eof()
803
804 def __del__(self, _warn=warnings.warn):
805 if self._pipe is not None:
806 _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
807 self._pipe.close()
808
809 def abort(self):
810 self._close(None)
811
812 def _fatal_error(self, exc, message='Fatal error on pipe transport'):
813 # should be called by exception handler only
814 if isinstance(exc, OSError):
815 if self._loop.get_debug():
816 logger.debug("%r: %s", self, message, exc_info=True)
817 else:
818 self._loop.call_exception_handler({
819 'message': message,
820 'exception': exc,
821 'transport': self,
822 'protocol': self._protocol,
823 })
824 self._close(exc)
825
826 def _close(self, exc=None):
827 self._closing = True
828 if self._buffer:
829 self._loop._remove_writer(self._fileno)
830 self._buffer.clear()
831 self._loop._remove_reader(self._fileno)
832 self._loop.call_soon(self._call_connection_lost, exc)
833
834 def _call_connection_lost(self, exc):
835 try:
836 self._protocol.connection_lost(exc)
837 finally:
838 self._pipe.close()
839 self._pipe = None
840 self._protocol = None
841 self._loop = None
842
843
844 class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
845
846 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
847 stdin_w = None
848 if stdin == subprocess.PIPE and sys.platform.startswith('aix'):
849 # Use a socket pair for stdin on AIX, since it does not
850 # support selecting read events on the write end of a
851 # socket (which we use in order to detect closing of the
852 # other end).
853 stdin, stdin_w = socket.socketpair()
854 try:
855 self._proc = subprocess.Popen(
856 args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
857 universal_newlines=False, bufsize=bufsize, **kwargs)
858 if stdin_w is not None:
859 stdin.close()
860 self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
861 stdin_w = None
862 finally:
863 if stdin_w is not None:
864 stdin.close()
865 stdin_w.close()
866
867
868 class AbstractChildWatcher:
869 """Abstract base class for monitoring child processes.
870
871 Objects derived from this class monitor a collection of subprocesses and
872 report their termination or interruption by a signal.
873
874 New callbacks are registered with .add_child_handler(). Starting a new
875 process must be done within a 'with' block to allow the watcher to suspend
876 its activity until the new process if fully registered (this is needed to
877 prevent a race condition in some implementations).
878
879 Example:
880 with watcher:
881 proc = subprocess.Popen("sleep 1")
882 watcher.add_child_handler(proc.pid, callback)
883
884 Notes:
885 Implementations of this class must be thread-safe.
886
887 Since child watcher objects may catch the SIGCHLD signal and call
888 waitpid(-1), there should be only one active object per process.
889 """
890
891 def __init_subclass__(cls) -> None:
892 if cls.__module__ != __name__:
893 warnings._deprecated("AbstractChildWatcher",
894 "{name!r} is deprecated as of Python 3.12 and will be "
895 "removed in Python {remove}.",
896 remove=(3, 14))
897
898 def add_child_handler(self, pid, callback, *args):
899 """Register a new child handler.
900
901 Arrange for callback(pid, returncode, *args) to be called when
902 process 'pid' terminates. Specifying another callback for the same
903 process replaces the previous handler.
904
905 Note: callback() must be thread-safe.
906 """
907 raise NotImplementedError()
908
909 def remove_child_handler(self, pid):
910 """Removes the handler for process 'pid'.
911
912 The function returns True if the handler was successfully removed,
913 False if there was nothing to remove."""
914
915 raise NotImplementedError()
916
917 def attach_loop(self, loop):
918 """Attach the watcher to an event loop.
919
920 If the watcher was previously attached to an event loop, then it is
921 first detached before attaching to the new loop.
922
923 Note: loop may be None.
924 """
925 raise NotImplementedError()
926
927 def close(self):
928 """Close the watcher.
929
930 This must be called to make sure that any underlying resource is freed.
931 """
932 raise NotImplementedError()
933
934 def is_active(self):
935 """Return ``True`` if the watcher is active and is used by the event loop.
936
937 Return True if the watcher is installed and ready to handle process exit
938 notifications.
939
940 """
941 raise NotImplementedError()
942
943 def __enter__(self):
944 """Enter the watcher's context and allow starting new processes
945
946 This function must return self"""
947 raise NotImplementedError()
948
949 def __exit__(self, a, b, c):
950 """Exit the watcher's context"""
951 raise NotImplementedError()
952
953
954 class PidfdChildWatcher(AbstractChildWatcher):
955 """Child watcher implementation using Linux's pid file descriptors.
956
957 This child watcher polls process file descriptors (pidfds) to await child
958 process termination. In some respects, PidfdChildWatcher is a "Goldilocks"
959 child watcher implementation. It doesn't require signals or threads, doesn't
960 interfere with any processes launched outside the event loop, and scales
961 linearly with the number of subprocesses launched by the event loop. The
962 main disadvantage is that pidfds are specific to Linux, and only work on
963 recent (5.3+) kernels.
964 """
965
966 def __enter__(self):
967 return self
968
969 def __exit__(self, exc_type, exc_value, exc_traceback):
970 pass
971
972 def is_active(self):
973 return True
974
975 def close(self):
976 pass
977
978 def attach_loop(self, loop):
979 pass
980
981 def add_child_handler(self, pid, callback, *args):
982 loop = events.get_running_loop()
983 pidfd = os.pidfd_open(pid)
984 loop._add_reader(pidfd, self._do_wait, pid, pidfd, callback, args)
985
986 def _do_wait(self, pid, pidfd, callback, args):
987 loop = events.get_running_loop()
988 loop._remove_reader(pidfd)
989 try:
990 _, status = os.waitpid(pid, 0)
991 except ChildProcessError:
992 # The child process is already reaped
993 # (may happen if waitpid() is called elsewhere).
994 returncode = 255
995 logger.warning(
996 "child process pid %d exit status already read: "
997 " will report returncode 255",
998 pid)
999 else:
1000 returncode = waitstatus_to_exitcode(status)
1001
1002 os.close(pidfd)
1003 callback(pid, returncode, *args)
1004
1005 def remove_child_handler(self, pid):
1006 # asyncio never calls remove_child_handler() !!!
1007 # The method is no-op but is implemented because
1008 # abstract base classes require it.
1009 return True
1010
1011
1012 class BaseChildWatcher(AbstractChildWatcher):
1013
1014 def __init__(self):
1015 self._loop = None
1016 self._callbacks = {}
1017
1018 def close(self):
1019 self.attach_loop(None)
1020
1021 def is_active(self):
1022 return self._loop is not None and self._loop.is_running()
1023
1024 def _do_waitpid(self, expected_pid):
1025 raise NotImplementedError()
1026
1027 def _do_waitpid_all(self):
1028 raise NotImplementedError()
1029
1030 def attach_loop(self, loop):
1031 assert loop is None or isinstance(loop, events.AbstractEventLoop)
1032
1033 if self._loop is not None and loop is None and self._callbacks:
1034 warnings.warn(
1035 'A loop is being detached '
1036 'from a child watcher with pending handlers',
1037 RuntimeWarning)
1038
1039 if self._loop is not None:
1040 self._loop.remove_signal_handler(signal.SIGCHLD)
1041
1042 self._loop = loop
1043 if loop is not None:
1044 loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
1045
1046 # Prevent a race condition in case a child terminated
1047 # during the switch.
1048 self._do_waitpid_all()
1049
1050 def _sig_chld(self):
1051 try:
1052 self._do_waitpid_all()
1053 except (SystemExit, KeyboardInterrupt):
1054 raise
1055 except BaseException as exc:
1056 # self._loop should always be available here
1057 # as '_sig_chld' is added as a signal handler
1058 # in 'attach_loop'
1059 self._loop.call_exception_handler({
1060 'message': 'Unknown exception in SIGCHLD handler',
1061 'exception': exc,
1062 })
1063
1064
1065 class SafeChildWatcher(BaseChildWatcher):
1066 """'Safe' child watcher implementation.
1067
1068 This implementation avoids disrupting other code spawning processes by
1069 polling explicitly each process in the SIGCHLD handler instead of calling
1070 os.waitpid(-1).
1071
1072 This is a safe solution but it has a significant overhead when handling a
1073 big number of children (O(n) each time SIGCHLD is raised)
1074 """
1075
1076 def __init__(self):
1077 super().__init__()
1078 warnings._deprecated("SafeChildWatcher",
1079 "{name!r} is deprecated as of Python 3.12 and will be "
1080 "removed in Python {remove}.",
1081 remove=(3, 14))
1082
1083 def close(self):
1084 self._callbacks.clear()
1085 super().close()
1086
1087 def __enter__(self):
1088 return self
1089
1090 def __exit__(self, a, b, c):
1091 pass
1092
1093 def add_child_handler(self, pid, callback, *args):
1094 self._callbacks[pid] = (callback, args)
1095
1096 # Prevent a race condition in case the child is already terminated.
1097 self._do_waitpid(pid)
1098
1099 def remove_child_handler(self, pid):
1100 try:
1101 del self._callbacks[pid]
1102 return True
1103 except KeyError:
1104 return False
1105
1106 def _do_waitpid_all(self):
1107
1108 for pid in list(self._callbacks):
1109 self._do_waitpid(pid)
1110
1111 def _do_waitpid(self, expected_pid):
1112 assert expected_pid > 0
1113
1114 try:
1115 pid, status = os.waitpid(expected_pid, os.WNOHANG)
1116 except ChildProcessError:
1117 # The child process is already reaped
1118 # (may happen if waitpid() is called elsewhere).
1119 pid = expected_pid
1120 returncode = 255
1121 logger.warning(
1122 "Unknown child process pid %d, will report returncode 255",
1123 pid)
1124 else:
1125 if pid == 0:
1126 # The child process is still alive.
1127 return
1128
1129 returncode = waitstatus_to_exitcode(status)
1130 if self._loop.get_debug():
1131 logger.debug('process %s exited with returncode %s',
1132 expected_pid, returncode)
1133
1134 try:
1135 callback, args = self._callbacks.pop(pid)
1136 except KeyError: # pragma: no cover
1137 # May happen if .remove_child_handler() is called
1138 # after os.waitpid() returns.
1139 if self._loop.get_debug():
1140 logger.warning("Child watcher got an unexpected pid: %r",
1141 pid, exc_info=True)
1142 else:
1143 callback(pid, returncode, *args)
1144
1145
1146 class FastChildWatcher(BaseChildWatcher):
1147 """'Fast' child watcher implementation.
1148
1149 This implementation reaps every terminated processes by calling
1150 os.waitpid(-1) directly, possibly breaking other code spawning processes
1151 and waiting for their termination.
1152
1153 There is no noticeable overhead when handling a big number of children
1154 (O(1) each time a child terminates).
1155 """
1156 def __init__(self):
1157 super().__init__()
1158 self._lock = threading.Lock()
1159 self._zombies = {}
1160 self._forks = 0
1161 warnings._deprecated("FastChildWatcher",
1162 "{name!r} is deprecated as of Python 3.12 and will be "
1163 "removed in Python {remove}.",
1164 remove=(3, 14))
1165
1166 def close(self):
1167 self._callbacks.clear()
1168 self._zombies.clear()
1169 super().close()
1170
1171 def __enter__(self):
1172 with self._lock:
1173 self._forks += 1
1174
1175 return self
1176
1177 def __exit__(self, a, b, c):
1178 with self._lock:
1179 self._forks -= 1
1180
1181 if self._forks or not self._zombies:
1182 return
1183
1184 collateral_victims = str(self._zombies)
1185 self._zombies.clear()
1186
1187 logger.warning(
1188 "Caught subprocesses termination from unknown pids: %s",
1189 collateral_victims)
1190
1191 def add_child_handler(self, pid, callback, *args):
1192 assert self._forks, "Must use the context manager"
1193
1194 with self._lock:
1195 try:
1196 returncode = self._zombies.pop(pid)
1197 except KeyError:
1198 # The child is running.
1199 self._callbacks[pid] = callback, args
1200 return
1201
1202 # The child is dead already. We can fire the callback.
1203 callback(pid, returncode, *args)
1204
1205 def remove_child_handler(self, pid):
1206 try:
1207 del self._callbacks[pid]
1208 return True
1209 except KeyError:
1210 return False
1211
1212 def _do_waitpid_all(self):
1213 # Because of signal coalescing, we must keep calling waitpid() as
1214 # long as we're able to reap a child.
1215 while True:
1216 try:
1217 pid, status = os.waitpid(-1, os.WNOHANG)
1218 except ChildProcessError:
1219 # No more child processes exist.
1220 return
1221 else:
1222 if pid == 0:
1223 # A child process is still alive.
1224 return
1225
1226 returncode = waitstatus_to_exitcode(status)
1227
1228 with self._lock:
1229 try:
1230 callback, args = self._callbacks.pop(pid)
1231 except KeyError:
1232 # unknown child
1233 if self._forks:
1234 # It may not be registered yet.
1235 self._zombies[pid] = returncode
1236 if self._loop.get_debug():
1237 logger.debug('unknown process %s exited '
1238 'with returncode %s',
1239 pid, returncode)
1240 continue
1241 callback = None
1242 else:
1243 if self._loop.get_debug():
1244 logger.debug('process %s exited with returncode %s',
1245 pid, returncode)
1246
1247 if callback is None:
1248 logger.warning(
1249 "Caught subprocess termination from unknown pid: "
1250 "%d -> %d", pid, returncode)
1251 else:
1252 callback(pid, returncode, *args)
1253
1254
1255 class MultiLoopChildWatcher(AbstractChildWatcher):
1256 """A watcher that doesn't require running loop in the main thread.
1257
1258 This implementation registers a SIGCHLD signal handler on
1259 instantiation (which may conflict with other code that
1260 install own handler for this signal).
1261
1262 The solution is safe but it has a significant overhead when
1263 handling a big number of processes (*O(n)* each time a
1264 SIGCHLD is received).
1265 """
1266
1267 # Implementation note:
1268 # The class keeps compatibility with AbstractChildWatcher ABC
1269 # To achieve this it has empty attach_loop() method
1270 # and doesn't accept explicit loop argument
1271 # for add_child_handler()/remove_child_handler()
1272 # but retrieves the current loop by get_running_loop()
1273
1274 def __init__(self):
1275 self._callbacks = {}
1276 self._saved_sighandler = None
1277 warnings._deprecated("MultiLoopChildWatcher",
1278 "{name!r} is deprecated as of Python 3.12 and will be "
1279 "removed in Python {remove}.",
1280 remove=(3, 14))
1281
1282 def is_active(self):
1283 return self._saved_sighandler is not None
1284
1285 def close(self):
1286 self._callbacks.clear()
1287 if self._saved_sighandler is None:
1288 return
1289
1290 handler = signal.getsignal(signal.SIGCHLD)
1291 if handler != self._sig_chld:
1292 logger.warning("SIGCHLD handler was changed by outside code")
1293 else:
1294 signal.signal(signal.SIGCHLD, self._saved_sighandler)
1295 self._saved_sighandler = None
1296
1297 def __enter__(self):
1298 return self
1299
1300 def __exit__(self, exc_type, exc_val, exc_tb):
1301 pass
1302
1303 def add_child_handler(self, pid, callback, *args):
1304 loop = events.get_running_loop()
1305 self._callbacks[pid] = (loop, callback, args)
1306
1307 # Prevent a race condition in case the child is already terminated.
1308 self._do_waitpid(pid)
1309
1310 def remove_child_handler(self, pid):
1311 try:
1312 del self._callbacks[pid]
1313 return True
1314 except KeyError:
1315 return False
1316
1317 def attach_loop(self, loop):
1318 # Don't save the loop but initialize itself if called first time
1319 # The reason to do it here is that attach_loop() is called from
1320 # unix policy only for the main thread.
1321 # Main thread is required for subscription on SIGCHLD signal
1322 if self._saved_sighandler is not None:
1323 return
1324
1325 self._saved_sighandler = signal.signal(signal.SIGCHLD, self._sig_chld)
1326 if self._saved_sighandler is None:
1327 logger.warning("Previous SIGCHLD handler was set by non-Python code, "
1328 "restore to default handler on watcher close.")
1329 self._saved_sighandler = signal.SIG_DFL
1330
1331 # Set SA_RESTART to limit EINTR occurrences.
1332 signal.siginterrupt(signal.SIGCHLD, False)
1333
1334 def _do_waitpid_all(self):
1335 for pid in list(self._callbacks):
1336 self._do_waitpid(pid)
1337
1338 def _do_waitpid(self, expected_pid):
1339 assert expected_pid > 0
1340
1341 try:
1342 pid, status = os.waitpid(expected_pid, os.WNOHANG)
1343 except ChildProcessError:
1344 # The child process is already reaped
1345 # (may happen if waitpid() is called elsewhere).
1346 pid = expected_pid
1347 returncode = 255
1348 logger.warning(
1349 "Unknown child process pid %d, will report returncode 255",
1350 pid)
1351 debug_log = False
1352 else:
1353 if pid == 0:
1354 # The child process is still alive.
1355 return
1356
1357 returncode = waitstatus_to_exitcode(status)
1358 debug_log = True
1359 try:
1360 loop, callback, args = self._callbacks.pop(pid)
1361 except KeyError: # pragma: no cover
1362 # May happen if .remove_child_handler() is called
1363 # after os.waitpid() returns.
1364 logger.warning("Child watcher got an unexpected pid: %r",
1365 pid, exc_info=True)
1366 else:
1367 if loop.is_closed():
1368 logger.warning("Loop %r that handles pid %r is closed", loop, pid)
1369 else:
1370 if debug_log and loop.get_debug():
1371 logger.debug('process %s exited with returncode %s',
1372 expected_pid, returncode)
1373 loop.call_soon_threadsafe(callback, pid, returncode, *args)
1374
1375 def _sig_chld(self, signum, frame):
1376 try:
1377 self._do_waitpid_all()
1378 except (SystemExit, KeyboardInterrupt):
1379 raise
1380 except BaseException:
1381 logger.warning('Unknown exception in SIGCHLD handler', exc_info=True)
1382
1383
1384 class ThreadedChildWatcher(AbstractChildWatcher):
1385 """Threaded child watcher implementation.
1386
1387 The watcher uses a thread per process
1388 for waiting for the process finish.
1389
1390 It doesn't require subscription on POSIX signal
1391 but a thread creation is not free.
1392
1393 The watcher has O(1) complexity, its performance doesn't depend
1394 on amount of spawn processes.
1395 """
1396
1397 def __init__(self):
1398 self._pid_counter = itertools.count(0)
1399 self._threads = {}
1400
1401 def is_active(self):
1402 return True
1403
1404 def close(self):
1405 pass
1406
1407 def __enter__(self):
1408 return self
1409
1410 def __exit__(self, exc_type, exc_val, exc_tb):
1411 pass
1412
1413 def __del__(self, _warn=warnings.warn):
1414 threads = [thread for thread in list(self._threads.values())
1415 if thread.is_alive()]
1416 if threads:
1417 _warn(f"{self.__class__} has registered but not finished child processes",
1418 ResourceWarning,
1419 source=self)
1420
1421 def add_child_handler(self, pid, callback, *args):
1422 loop = events.get_running_loop()
1423 thread = threading.Thread(target=self._do_waitpid,
1424 name=f"asyncio-waitpid-{next(self._pid_counter)}",
1425 args=(loop, pid, callback, args),
1426 daemon=True)
1427 self._threads[pid] = thread
1428 thread.start()
1429
1430 def remove_child_handler(self, pid):
1431 # asyncio never calls remove_child_handler() !!!
1432 # The method is no-op but is implemented because
1433 # abstract base classes require it.
1434 return True
1435
1436 def attach_loop(self, loop):
1437 pass
1438
1439 def _do_waitpid(self, loop, expected_pid, callback, args):
1440 assert expected_pid > 0
1441
1442 try:
1443 pid, status = os.waitpid(expected_pid, 0)
1444 except ChildProcessError:
1445 # The child process is already reaped
1446 # (may happen if waitpid() is called elsewhere).
1447 pid = expected_pid
1448 returncode = 255
1449 logger.warning(
1450 "Unknown child process pid %d, will report returncode 255",
1451 pid)
1452 else:
1453 returncode = waitstatus_to_exitcode(status)
1454 if loop.get_debug():
1455 logger.debug('process %s exited with returncode %s',
1456 expected_pid, returncode)
1457
1458 if loop.is_closed():
1459 logger.warning("Loop %r that handles pid %r is closed", loop, pid)
1460 else:
1461 loop.call_soon_threadsafe(callback, pid, returncode, *args)
1462
1463 self._threads.pop(expected_pid)
1464
1465 def can_use_pidfd():
1466 if not hasattr(os, 'pidfd_open'):
1467 return False
1468 try:
1469 pid = os.getpid()
1470 os.close(os.pidfd_open(pid, 0))
1471 except OSError:
1472 # blocked by security policy like SECCOMP
1473 return False
1474 return True
1475
1476
1477 class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
1478 """UNIX event loop policy with a watcher for child processes."""
1479 _loop_factory = _UnixSelectorEventLoop
1480
1481 def __init__(self):
1482 super().__init__()
1483 self._watcher = None
1484
1485 def _init_watcher(self):
1486 with events._lock:
1487 if self._watcher is None: # pragma: no branch
1488 if can_use_pidfd():
1489 self._watcher = PidfdChildWatcher()
1490 else:
1491 self._watcher = ThreadedChildWatcher()
1492
1493 def set_event_loop(self, loop):
1494 """Set the event loop.
1495
1496 As a side effect, if a child watcher was set before, then calling
1497 .set_event_loop() from the main thread will call .attach_loop(loop) on
1498 the child watcher.
1499 """
1500
1501 super().set_event_loop(loop)
1502
1503 if (self._watcher is not None and
1504 threading.current_thread() is threading.main_thread()):
1505 self._watcher.attach_loop(loop)
1506
1507 def get_child_watcher(self):
1508 """Get the watcher for child processes.
1509
1510 If not yet set, a ThreadedChildWatcher object is automatically created.
1511 """
1512 if self._watcher is None:
1513 self._init_watcher()
1514
1515 warnings._deprecated("get_child_watcher",
1516 "{name!r} is deprecated as of Python 3.12 and will be "
1517 "removed in Python {remove}.", remove=(3, 14))
1518 return self._watcher
1519
1520 def set_child_watcher(self, watcher):
1521 """Set the watcher for child processes."""
1522
1523 assert watcher is None or isinstance(watcher, AbstractChildWatcher)
1524
1525 if self._watcher is not None:
1526 self._watcher.close()
1527
1528 self._watcher = watcher
1529 warnings._deprecated("set_child_watcher",
1530 "{name!r} is deprecated as of Python 3.12 and will be "
1531 "removed in Python {remove}.", remove=(3, 14))
1532
1533
1534 SelectorEventLoop = _UnixSelectorEventLoop
1535 DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy
1536 EventLoop = SelectorEventLoop