|
| 1 | +# PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 |
| 2 | +# -------------------------------------------- |
| 3 | +# |
| 4 | +# 1. This LICENSE AGREEMENT is between the Python Software Foundation |
| 5 | +# ("PSF"), and the Individual or Organization ("Licensee") accessing and |
| 6 | +# otherwise using this software ("Python") in source or binary form and |
| 7 | +# its associated documentation. |
| 8 | +# |
| 9 | +# 2. Subject to the terms and conditions of this License Agreement, PSF hereby |
| 10 | +# grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, |
| 11 | +# analyze, test, perform and/or display publicly, prepare derivative works, |
| 12 | +# distribute, and otherwise use Python alone or in any derivative version, |
| 13 | +# provided, however, that PSF's License Agreement and PSF's notice of copyright, |
| 14 | +# i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, |
| 15 | +# 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; |
| 16 | +# All Rights Reserved" are retained in Python alone or in any derivative version |
| 17 | +# prepared by Licensee. |
| 18 | +# |
| 19 | +# 3. In the event Licensee prepares a derivative work that is based on |
| 20 | +# or incorporates Python or any part thereof, and wants to make |
| 21 | +# the derivative work available to others as provided herein, then |
| 22 | +# Licensee hereby agrees to include in any such work a brief summary of |
| 23 | +# the changes made to Python. |
| 24 | +# |
| 25 | +# 4. PSF is making Python available to Licensee on an "AS IS" |
| 26 | +# basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
| 27 | +# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND |
| 28 | +# DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
| 29 | +# FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT |
| 30 | +# INFRINGE ANY THIRD PARTY RIGHTS. |
| 31 | +# |
| 32 | +# 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |
| 33 | +# FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS |
| 34 | +# A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, |
| 35 | +# OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
| 36 | +# |
| 37 | +# 6. This License Agreement will automatically terminate upon a material |
| 38 | +# breach of its terms and conditions. |
| 39 | +# |
| 40 | +# 7. Nothing in this License Agreement shall be deemed to create any |
| 41 | +# relationship of agency, partnership, or joint venture between PSF and |
| 42 | +# Licensee. This License Agreement does not grant permission to use PSF |
| 43 | +# trademarks or trade name in a trademark sense to endorse or promote |
| 44 | +# products or services of Licensee, or any third party. |
| 45 | +# |
| 46 | +# 8. By copying, installing or otherwise using Python, Licensee |
| 47 | +# agrees to be bound by the terms and conditions of this License |
| 48 | +# Agreement. |
| 49 | +# |
| 50 | +# type: ignore |
| 51 | + |
| 52 | +import itertools |
| 53 | +import os |
| 54 | +import threading |
| 55 | +import warnings |
| 56 | +from asyncio import AbstractChildWatcher, events |
| 57 | +from asyncio.log import logger |
| 58 | + |
| 59 | + |
| 60 | +class ThreadedChildWatcher(AbstractChildWatcher): |
| 61 | + """Threaded child watcher implementation. |
| 62 | + The watcher uses a thread per process |
| 63 | + for waiting for the process finish. |
| 64 | + It doesn't require subscription on POSIX signal |
| 65 | + but a thread creation is not free. |
| 66 | + The watcher has O(1) complexity, its performance doesn't depend |
| 67 | + on amount of spawn processes. |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__(self): |
| 71 | + self._pid_counter = itertools.count(0) |
| 72 | + self._threads = {} |
| 73 | + |
| 74 | + def is_active(self): |
| 75 | + return True |
| 76 | + |
| 77 | + def close(self): |
| 78 | + self._join_threads() |
| 79 | + |
| 80 | + def _join_threads(self): |
| 81 | + """Internal: Join all non-daemon threads""" |
| 82 | + threads = [ |
| 83 | + thread |
| 84 | + for thread in list(self._threads.values()) |
| 85 | + if thread.is_alive() and not thread.daemon |
| 86 | + ] |
| 87 | + for thread in threads: |
| 88 | + thread.join() |
| 89 | + |
| 90 | + def __enter__(self): |
| 91 | + return self |
| 92 | + |
| 93 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 94 | + pass |
| 95 | + |
| 96 | + def __del__(self, _warn=warnings.warn): |
| 97 | + threads = [ |
| 98 | + thread for thread in list(self._threads.values()) if thread.is_alive() |
| 99 | + ] |
| 100 | + if threads: |
| 101 | + _warn( |
| 102 | + f"{self.__class__} has registered but not finished child processes", |
| 103 | + ResourceWarning, |
| 104 | + source=self, |
| 105 | + ) |
| 106 | + |
| 107 | + def add_child_handler(self, pid, callback, *args): |
| 108 | + loop = events.get_running_loop() |
| 109 | + thread = threading.Thread( |
| 110 | + target=self._do_waitpid, |
| 111 | + name=f"waitpid-{next(self._pid_counter)}", |
| 112 | + args=(loop, pid, callback, args), |
| 113 | + daemon=True, |
| 114 | + ) |
| 115 | + self._threads[pid] = thread |
| 116 | + thread.start() |
| 117 | + |
| 118 | + def remove_child_handler(self, pid): |
| 119 | + # asyncio never calls remove_child_handler() !!! |
| 120 | + # The method is no-op but is implemented because |
| 121 | + # abstract base classe requires it |
| 122 | + return True |
| 123 | + |
| 124 | + def attach_loop(self, loop): |
| 125 | + pass |
| 126 | + |
| 127 | + def _do_waitpid(self, loop, expected_pid, callback, args): |
| 128 | + assert expected_pid > 0 |
| 129 | + |
| 130 | + try: |
| 131 | + pid, status = os.waitpid(expected_pid, 0) |
| 132 | + except ChildProcessError: |
| 133 | + # The child process is already reaped |
| 134 | + # (may happen if waitpid() is called elsewhere). |
| 135 | + pid = expected_pid |
| 136 | + returncode = 255 |
| 137 | + logger.warning( |
| 138 | + "Unknown child process pid %d, will report returncode 255", pid |
| 139 | + ) |
| 140 | + else: |
| 141 | + returncode = _compute_returncode(status) |
| 142 | + if loop.get_debug(): |
| 143 | + logger.debug( |
| 144 | + "process %s exited with returncode %s", expected_pid, returncode |
| 145 | + ) |
| 146 | + |
| 147 | + if loop.is_closed(): |
| 148 | + logger.warning("Loop %r that handles pid %r is closed", loop, pid) |
| 149 | + else: |
| 150 | + loop.call_soon_threadsafe(callback, pid, returncode, *args) |
| 151 | + |
| 152 | + self._threads.pop(expected_pid) |
| 153 | + |
| 154 | + |
| 155 | +def _compute_returncode(status): |
| 156 | + if os.WIFSIGNALED(status): |
| 157 | + # The child process died because of a signal. |
| 158 | + return -os.WTERMSIG(status) |
| 159 | + elif os.WIFEXITED(status): |
| 160 | + # The child process exited (e.g sys.exit()). |
| 161 | + return os.WEXITSTATUS(status) |
| 162 | + else: |
| 163 | + # The child exited, but we don't understand its status. |
| 164 | + # This shouldn't happen, but if it does, let's just |
| 165 | + # return that status; perhaps that helps debug it. |
| 166 | + return status |
0 commit comments