Debian Codegraph @

Lib/multiprocessing/resource_tracker.py

raw
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
18 import base64
19 import os
20 import signal
21 import sys
22 import threading
23 import warnings
24 from collections import deque
25
26 import json
27
28 from . import spawn
29 from . import util
30
31 __all__ = ['ensure_running', 'register', 'unregister']
32
33 _HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask')
34 _IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM)
35
36 def cleanup_noop(name):
37 raise RuntimeError('noop should never be registered or cleaned up')
38
39 _CLEANUP_FUNCS = {
40 'noop': cleanup_noop,
41 'dummy': lambda name: None, # Dummy resource used in tests
42 }
43
44 if os.name == 'posix':
45 import _multiprocessing
46 import _posixshmem
47
48 # Use sem_unlink() to clean up named semaphores.
49 #
50 # sem_unlink() may be missing if the Python build process detected the
51 # absence of POSIX named semaphores. In that case, no named semaphores were
52 # ever opened, so no cleanup would be necessary.
53 if hasattr(_multiprocessing, 'sem_unlink'):
54 _CLEANUP_FUNCS.update({
55 'semaphore': _multiprocessing.sem_unlink,
56 })
57 _CLEANUP_FUNCS.update({
58 'shared_memory': _posixshmem.shm_unlink,
59 })
60
61
62 class ReentrantCallError(RuntimeError):
63 pass
64
65
66 class ResourceTracker(object):
67
68 def __init__(self):
69 self._lock = threading.RLock()
70 self._fd = None
71 self._pid = None
72 self._exitcode = None
73 self._reentrant_messages = deque()
74
75 # True to use colon-separated lines, rather than JSON lines,
76 # for internal communication. (Mainly for testing).
77 # Filenames not supported by the simple format will always be sent
78 # using JSON.
79 # The reader should understand all formats.
80 self._use_simple_format = True
81
82 def _reentrant_call_error(self):
83 # gh-109629: this happens if an explicit call to the ResourceTracker
84 # gets interrupted by a garbage collection, invoking a finalizer (*)
85 # that itself calls back into ResourceTracker.
86 # (*) for example the SemLock finalizer
87 raise ReentrantCallError(
88 "Reentrant call into the multiprocessing resource tracker")
89
90 def __del__(self):
91 # making sure child processess are cleaned before ResourceTracker
92 # gets destructed.
93 # see https://github.com/python/cpython/issues/88887
94 self._stop(use_blocking_lock=False)
95
96 def _stop(self, use_blocking_lock=True):
97 if use_blocking_lock:
98 with self._lock:
99 self._stop_locked()
100 else:
101 acquired = self._lock.acquire(blocking=False)
102 try:
103 self._stop_locked()
104 finally:
105 if acquired:
106 self._lock.release()
107
108 def _stop_locked(
109 self,
110 close=os.close,
111 waitpid=os.waitpid,
112 waitstatus_to_exitcode=os.waitstatus_to_exitcode,
113 ):
114 # This shouldn't happen (it might when called by a finalizer)
115 # so we check for it anyway.
116 if self._lock._recursion_count() > 1:
117 raise self._reentrant_call_error()
118 if self._fd is None:
119 # not running
120 return
121 if self._pid is None:
122 return
123
124 # closing the "alive" file descriptor stops main()
125 close(self._fd)
126 self._fd = None
127
128 try:
129 _, status = waitpid(self._pid, 0)
130 except ChildProcessError:
131 self._pid = None
132 self._exitcode = None
133 return
134
135 self._pid = None
136
137 try:
138 self._exitcode = waitstatus_to_exitcode(status)
139 except ValueError:
140 # os.waitstatus_to_exitcode may raise an exception for invalid values
141 self._exitcode = None
142
143 def getfd(self):
144 self.ensure_running()
145 return self._fd
146
147 def ensure_running(self):
148 '''Make sure that resource tracker process is running.
149
150 This can be run from any process. Usually a child process will use
151 the resource created by its parent.'''
152 return self._ensure_running_and_write()
153
154 def _teardown_dead_process(self):
155 os.close(self._fd)
156
157 # Clean-up to avoid dangling processes.
158 try:
159 # _pid can be None if this process is a child from another
160 # python process, which has started the resource_tracker.
161 if self._pid is not None:
162 os.waitpid(self._pid, 0)
163 except ChildProcessError:
164 # The resource_tracker has already been terminated.
165 pass
166 self._fd = None
167 self._pid = None
168 self._exitcode = None
169
170 warnings.warn('resource_tracker: process died unexpectedly, '
171 'relaunching. Some resources might leak.')
172
173 def _launch(self):
174 fds_to_pass = []
175 try:
176 fds_to_pass.append(sys.stderr.fileno())
177 except Exception:
178 pass
179 r, w = os.pipe()
180 try:
181 fds_to_pass.append(r)
182 # process will out live us, so no need to wait on pid
183 exe = spawn.get_executable()
184 args = [
185 exe,
186 *util._args_from_interpreter_flags(),
187 '-c',
188 f'from multiprocessing.resource_tracker import main;main({r})',
189 ]
190 # bpo-33613: Register a signal mask that will block the signals.
191 # This signal mask will be inherited by the child that is going
192 # to be spawned and will protect the child from a race condition
193 # that can make the child die before it registers signal handlers
194 # for SIGINT and SIGTERM. The mask is unregistered after spawning
195 # the child.
196 prev_sigmask = None
197 try:
198 if _HAVE_SIGMASK:
199 prev_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
200 pid = util.spawnv_passfds(exe, args, fds_to_pass)
201 finally:
202 if prev_sigmask is not None:
203 signal.pthread_sigmask(signal.SIG_SETMASK, prev_sigmask)
204 except:
205 os.close(w)
206 raise
207 else:
208 self._fd = w
209 self._pid = pid
210 finally:
211 os.close(r)
212
213 def _make_probe_message(self):
214 """Return a probe message."""
215 if self._use_simple_format:
216 return b'PROBE:0:noop\n'
217 return (
218 json.dumps(
219 {"cmd": "PROBE", "rtype": "noop"},
220 ensure_ascii=True,
221 separators=(",", ":"),
222 )
223 + "\n"
224 ).encode("ascii")
225
226 def _ensure_running_and_write(self, msg=None):
227 with self._lock:
228 if self._lock._recursion_count() > 1:
229 # The code below is certainly not reentrant-safe, so bail out
230 if msg is None:
231 raise self._reentrant_call_error()
232 return self._reentrant_messages.append(msg)
233
234 if self._fd is not None:
235 # resource tracker was launched before, is it still running?
236 if msg is None:
237 to_send = self._make_probe_message()
238 else:
239 to_send = msg
240 try:
241 self._write(to_send)
242 except OSError:
243 self._teardown_dead_process()
244 self._launch()
245
246 msg = None # message was sent in probe
247 else:
248 self._launch()
249
250 while True:
251 try:
252 reentrant_msg = self._reentrant_messages.popleft()
253 except IndexError:
254 break
255 self._write(reentrant_msg)
256 if msg is not None:
257 self._write(msg)
258
259 def _check_alive(self):
260 '''Check that the pipe has not been closed by sending a probe.'''
261 try:
262 # We cannot use send here as it calls ensure_running, creating
263 # a cycle.
264 os.write(self._fd, self._make_probe_message())
265 except OSError:
266 return False
267 else:
268 return True
269
270 def register(self, name, rtype):
271 '''Register name of resource with resource tracker.'''
272 self._send('REGISTER', name, rtype)
273
274 def unregister(self, name, rtype):
275 '''Unregister name of resource with resource tracker.'''
276 self._send('UNREGISTER', name, rtype)
277
278 def _write(self, msg):
279 nbytes = os.write(self._fd, msg)
280 assert nbytes == len(msg), f"{nbytes=} != {len(msg)=}"
281
282 def _send(self, cmd, name, rtype):
283 if self._use_simple_format and '\n' not in name:
284 msg = f"{cmd}:{name}:{rtype}\n".encode("ascii")
285 if len(msg) > 512:
286 # posix guarantees that writes to a pipe of less than PIPE_BUF
287 # bytes are atomic, and that PIPE_BUF >= 512
288 raise ValueError('msg too long')
289 self._ensure_running_and_write(msg)
290 return
291
292 # POSIX guarantees that writes to a pipe of less than PIPE_BUF (512 on Linux)
293 # bytes are atomic. Therefore, we want the message to be shorter than 512 bytes.
294 # POSIX shm_open() and sem_open() require the name, including its leading slash,
295 # to be at most NAME_MAX bytes (255 on Linux)
296 # With json.dump(..., ensure_ascii=True) every non-ASCII byte becomes a 6-char
297 # escape like \uDC80.
298 # As we want the overall message to be kept atomic and therefore smaller than 512,
299 # we encode encode the raw name bytes with URL-safe Base64 - so a 255 long name
300 # will not exceed 340 bytes.
301 b = name.encode('utf-8', 'surrogateescape')
302 if len(b) > 255:
303 raise ValueError('shared memory name too long (max 255 bytes)')
304 b64 = base64.urlsafe_b64encode(b).decode('ascii')
305
306 payload = {"cmd": cmd, "rtype": rtype, "base64_name": b64}
307 msg = (json.dumps(payload, ensure_ascii=True, separators=(",", ":")) + "\n").encode("ascii")
308
309 # The entire JSON message is guaranteed < PIPE_BUF (512 bytes) by construction.
310 assert len(msg) <= 512, f"internal error: message too long ({len(msg)} bytes)"
311 assert msg.startswith(b'{')
312
313 self._ensure_running_and_write(msg)
314
315 _resource_tracker = ResourceTracker()
316 ensure_running = _resource_tracker.ensure_running
317 register = _resource_tracker.register
318 unregister = _resource_tracker.unregister
319 getfd = _resource_tracker.getfd
320
321
322 def _decode_message(line):
323 if line.startswith(b'{'):
324 try:
325 obj = json.loads(line.decode('ascii'))
326 except Exception as e:
327 raise ValueError("malformed resource_tracker message: %r" % (line,)) from e
328
329 cmd = obj["cmd"]
330 rtype = obj["rtype"]
331 b64 = obj.get("base64_name", "")
332
333 if not isinstance(cmd, str) or not isinstance(rtype, str) or not isinstance(b64, str):
334 raise ValueError("malformed resource_tracker fields: %r" % (obj,))
335
336 try:
337 name = base64.urlsafe_b64decode(b64).decode('utf-8', 'surrogateescape')
338 except ValueError as e:
339 raise ValueError("malformed resource_tracker base64_name: %r" % (b64,)) from e
340 else:
341 cmd, rest = line.strip().decode('ascii').split(':', maxsplit=1)
342 name, rtype = rest.rsplit(':', maxsplit=1)
343 return cmd, rtype, name
344
345
346 def main(fd):
347 '''Run resource tracker.'''
348 # protect the process from ^C and "killall python" etc
349 signal.signal(signal.SIGINT, signal.SIG_IGN)
350 signal.signal(signal.SIGTERM, signal.SIG_IGN)
351 if _HAVE_SIGMASK:
352 signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
353
354 for f in (sys.stdin, sys.stdout):
355 try:
356 f.close()
357 except Exception:
358 pass
359
360 cache = {rtype: set() for rtype in _CLEANUP_FUNCS.keys()}
361 exit_code = 0
362
363 try:
364 # keep track of registered/unregistered resources
365 with open(fd, 'rb') as f:
366 for line in f:
367 try:
368 cmd, rtype, name = _decode_message(line)
369 cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
370 if cleanup_func is None:
371 raise ValueError(
372 f'Cannot register {name} for automatic cleanup: '
373 f'unknown resource type {rtype}')
374
375 if cmd == 'REGISTER':
376 cache[rtype].add(name)
377 elif cmd == 'UNREGISTER':
378 cache[rtype].remove(name)
379 elif cmd == 'PROBE':
380 pass
381 else:
382 raise RuntimeError('unrecognized command %r' % cmd)
383 except Exception:
384 exit_code = 3
385 try:
386 sys.excepthook(*sys.exc_info())
387 except:
388 pass
389 finally:
390 # all processes have terminated; cleanup any remaining resources
391 for rtype, rtype_cache in cache.items():
392 if rtype_cache:
393 try:
394 exit_code = 1
395 if rtype == 'dummy':
396 # The test 'dummy' resource is expected to leak.
397 # We skip the warning (and *only* the warning) for it.
398 pass
399 else:
400 warnings.warn(
401 f'resource_tracker: There appear to be '
402 f'{len(rtype_cache)} leaked {rtype} objects to '
403 f'clean up at shutdown: {rtype_cache}'
404 )
405 except Exception:
406 pass
407 for name in rtype_cache:
408 # For some reason the process which created and registered this
409 # resource has failed to unregister it. Presumably it has
410 # died. We therefore unlink it.
411 try:
412 try:
413 _CLEANUP_FUNCS[rtype](name)
414 except Exception as e:
415 exit_code = 2
416 warnings.warn('resource_tracker: %r: %s' % (name, e))
417 finally:
418 pass
419
420 sys.exit(exit_code)