1############################################################################### 2# Server process to keep track of unlinked resources (like shared memory 3# segments, semaphores etc.) and clean them. 4# 5# On Unix we run a server process which keeps track of unlinked 6# resources. The server ignores SIGINT and SIGTERM and reads from a 7# pipe. Every other process of the program has a copy of the writable 8# end of the pipe, so we get EOF when all other processes have exited. 9# Then the server process unlinks any remaining resource names. 10# 11# This is important because there may be system limits for such resources: for 12# instance, the system only supports a limited number of named semaphores, and 13# shared-memory segments live in the RAM. If a python process leaks such a 14# resource, this resource will not be removed till the next reboot. Without 15# this resource tracker process, "killall python" would probably leave unlinked 16# resources. 17 18import os 19import signal 20import sys 21import threading 22import warnings 23 24from . import spawn 25from . import util 26 27__all__ = ['ensure_running', 'register', 'unregister'] 28 29_HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask') 30_IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM) 31 32def cleanup_noop(name): 33 raise RuntimeError('noop should never be registered or cleaned up') 34 35_CLEANUP_FUNCS = { 36 'noop': cleanup_noop, 37 'dummy': lambda name: None, # Dummy resource used in tests 38} 39 40if os.name == 'posix': 41 import _multiprocessing 42 import _posixshmem 43 44 # Use sem_unlink() to clean up named semaphores. 45 # 46 # sem_unlink() may be missing if the Python build process detected the 47 # absence of POSIX named semaphores. In that case, no named semaphores were 48 # ever opened, so no cleanup would be necessary. 49 if hasattr(_multiprocessing, 'sem_unlink'): 50 _CLEANUP_FUNCS.update({ 51 'semaphore': _multiprocessing.sem_unlink, 52 }) 53 _CLEANUP_FUNCS.update({ 54 'shared_memory': _posixshmem.shm_unlink, 55 }) 56 57 58class ReentrantCallError(RuntimeError): 59 pass 60 61 62class ResourceTracker(object): 63 64 def __init__(self): 65 self._lock = threading.RLock() 66 self._fd = None 67 self._pid = None 68 self._exitcode = None 69 70 def _reentrant_call_error(self): 71 # gh-109629: this happens if an explicit call to the ResourceTracker 72 # gets interrupted by a garbage collection, invoking a finalizer (*) 73 # that itself calls back into ResourceTracker. 74 # (*) for example the SemLock finalizer 75 raise ReentrantCallError( 76 "Reentrant call into the multiprocessing resource tracker") 77 78 def _stop(self): 79 with self._lock: 80 # This should not happen (_stop() isn't called by a finalizer) 81 # but we check for it anyway. 82 if self._lock._recursion_count() > 1: 83 return self._reentrant_call_error() 84 if self._fd is None: 85 # not running 86 return 87 88 # closing the "alive" file descriptor stops main() 89 os.close(self._fd) 90 self._fd = None 91 92 _, status = os.waitpid(self._pid, 0) 93 94 self._pid = None 95 96 try: 97 self._exitcode = os.waitstatus_to_exitcode(status) 98 except ValueError: 99 # os.waitstatus_to_exitcode may raise an exception for invalid values 100 self._exitcode = None 101 102 def getfd(self): 103 self.ensure_running() 104 return self._fd 105 106 def ensure_running(self): 107 '''Make sure that resource tracker process is running. 108 109 This can be run from any process. Usually a child process will use 110 the resource created by its parent.''' 111 with self._lock: 112 if self._lock._recursion_count() > 1: 113 # The code below is certainly not reentrant-safe, so bail out 114 return self._reentrant_call_error() 115 if self._fd is not None: 116 # resource tracker was launched before, is it still running? 117 if self._check_alive(): 118 # => still alive 119 return 120 # => dead, launch it again 121 os.close(self._fd) 122 123 # Clean-up to avoid dangling processes. 124 try: 125 # _pid can be None if this process is a child from another 126 # python process, which has started the resource_tracker. 127 if self._pid is not None: 128 os.waitpid(self._pid, 0) 129 except ChildProcessError: 130 # The resource_tracker has already been terminated. 131 pass 132 self._fd = None 133 self._pid = None 134 self._exitcode = None 135 136 warnings.warn('resource_tracker: process died unexpectedly, ' 137 'relaunching. Some resources might leak.') 138 139 fds_to_pass = [] 140 try: 141 fds_to_pass.append(sys.stderr.fileno()) 142 except Exception: 143 pass 144 cmd = 'from multiprocessing.resource_tracker import main;main(%d)' 145 r, w = os.pipe() 146 try: 147 fds_to_pass.append(r) 148 # process will out live us, so no need to wait on pid 149 exe = spawn.get_executable() 150 args = [exe] + util._args_from_interpreter_flags() 151 args += ['-c', cmd % r] 152 # bpo-33613: Register a signal mask that will block the signals. 153 # This signal mask will be inherited by the child that is going 154 # to be spawned and will protect the child from a race condition 155 # that can make the child die before it registers signal handlers 156 # for SIGINT and SIGTERM. The mask is unregistered after spawning 157 # the child. 158 try: 159 if _HAVE_SIGMASK: 160 signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS) 161 pid = util.spawnv_passfds(exe, args, fds_to_pass) 162 finally: 163 if _HAVE_SIGMASK: 164 signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) 165 except: 166 os.close(w) 167 raise 168 else: 169 self._fd = w 170 self._pid = pid 171 finally: 172 os.close(r) 173 174 def _check_alive(self): 175 '''Check that the pipe has not been closed by sending a probe.''' 176 try: 177 # We cannot use send here as it calls ensure_running, creating 178 # a cycle. 179 os.write(self._fd, b'PROBE:0:noop\n') 180 except OSError: 181 return False 182 else: 183 return True 184 185 def register(self, name, rtype): 186 '''Register name of resource with resource tracker.''' 187 self._send('REGISTER', name, rtype) 188 189 def unregister(self, name, rtype): 190 '''Unregister name of resource with resource tracker.''' 191 self._send('UNREGISTER', name, rtype) 192 193 def _send(self, cmd, name, rtype): 194 try: 195 self.ensure_running() 196 except ReentrantCallError: 197 # The code below might or might not work, depending on whether 198 # the resource tracker was already running and still alive. 199 # Better warn the user. 200 # (XXX is warnings.warn itself reentrant-safe? :-) 201 warnings.warn( 202 f"ResourceTracker called reentrantly for resource cleanup, " 203 f"which is unsupported. " 204 f"The {rtype} object {name!r} might leak.") 205 msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii') 206 if len(msg) > 512: 207 # posix guarantees that writes to a pipe of less than PIPE_BUF 208 # bytes are atomic, and that PIPE_BUF >= 512 209 raise ValueError('msg too long') 210 nbytes = os.write(self._fd, msg) 211 assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format( 212 nbytes, len(msg)) 213 214 215_resource_tracker = ResourceTracker() 216ensure_running = _resource_tracker.ensure_running 217register = _resource_tracker.register 218unregister = _resource_tracker.unregister 219getfd = _resource_tracker.getfd 220 221 222def main(fd): 223 '''Run resource tracker.''' 224 # protect the process from ^C and "killall python" etc 225 signal.signal(signal.SIGINT, signal.SIG_IGN) 226 signal.signal(signal.SIGTERM, signal.SIG_IGN) 227 if _HAVE_SIGMASK: 228 signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) 229 230 for f in (sys.stdin, sys.stdout): 231 try: 232 f.close() 233 except Exception: 234 pass 235 236 cache = {rtype: set() for rtype in _CLEANUP_FUNCS.keys()} 237 exit_code = 0 238 239 try: 240 # keep track of registered/unregistered resources 241 with open(fd, 'rb') as f: 242 for line in f: 243 try: 244 cmd, name, rtype = line.strip().decode('ascii').split(':') 245 cleanup_func = _CLEANUP_FUNCS.get(rtype, None) 246 if cleanup_func is None: 247 raise ValueError( 248 f'Cannot register {name} for automatic cleanup: ' 249 f'unknown resource type {rtype}') 250 251 if cmd == 'REGISTER': 252 cache[rtype].add(name) 253 elif cmd == 'UNREGISTER': 254 cache[rtype].remove(name) 255 elif cmd == 'PROBE': 256 pass 257 else: 258 raise RuntimeError('unrecognized command %r' % cmd) 259 except Exception: 260 exit_code = 3 261 try: 262 sys.excepthook(*sys.exc_info()) 263 except: 264 pass 265 finally: 266 # all processes have terminated; cleanup any remaining resources 267 for rtype, rtype_cache in cache.items(): 268 if rtype_cache: 269 try: 270 exit_code = 1 271 if rtype == 'dummy': 272 # The test 'dummy' resource is expected to leak. 273 # We skip the warning (and *only* the warning) for it. 274 pass 275 else: 276 warnings.warn( 277 f'resource_tracker: There appear to be ' 278 f'{len(rtype_cache)} leaked {rtype} objects to ' 279 f'clean up at shutdown: {rtype_cache}' 280 ) 281 except Exception: 282 pass 283 for name in rtype_cache: 284 # For some reason the process which created and registered this 285 # resource has failed to unregister it. Presumably it has 286 # died. We therefore unlink it. 287 try: 288 try: 289 _CLEANUP_FUNCS[rtype](name) 290 except Exception as e: 291 exit_code = 2 292 warnings.warn('resource_tracker: %r: %s' % (name, e)) 293 finally: 294 pass 295 296 sys.exit(exit_code) 297