resource_tracker.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. import os
  18. import signal
  19. import sys
  20. import threading
  21. import warnings
  22. from . import spawn
  23. from . import util
  24. __all__ = ['ensure_running', 'register', 'unregister']
  25. _HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask')
  26. _IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM)
  27. _CLEANUP_FUNCS = {
  28. 'noop': lambda: None,
  29. }
  30. if os.name == 'posix':
  31. import _multiprocessing
  32. import _posixshmem
  33. # Use sem_unlink() to clean up named semaphores.
  34. #
  35. # sem_unlink() may be missing if the Python build process detected the
  36. # absence of POSIX named semaphores. In that case, no named semaphores were
  37. # ever opened, so no cleanup would be necessary.
  38. if hasattr(_multiprocessing, 'sem_unlink'):
  39. _CLEANUP_FUNCS.update({
  40. 'semaphore': _multiprocessing.sem_unlink,
  41. })
  42. _CLEANUP_FUNCS.update({
  43. 'shared_memory': _posixshmem.shm_unlink,
  44. })
  45. class ReentrantCallError(RuntimeError):
  46. pass
  47. class ResourceTracker(object):
  48. def __init__(self):
  49. self._lock = threading.RLock()
  50. self._fd = None
  51. self._pid = None
  52. def _reentrant_call_error(self):
  53. # gh-109629: this happens if an explicit call to the ResourceTracker
  54. # gets interrupted by a garbage collection, invoking a finalizer (*)
  55. # that itself calls back into ResourceTracker.
  56. # (*) for example the SemLock finalizer
  57. raise ReentrantCallError(
  58. "Reentrant call into the multiprocessing resource tracker")
  59. def _stop(self):
  60. with self._lock:
  61. # This should not happen (_stop() isn't called by a finalizer)
  62. # but we check for it anyway.
  63. if self._lock._recursion_count() > 1:
  64. return self._reentrant_call_error()
  65. if self._fd is None:
  66. # not running
  67. return
  68. # closing the "alive" file descriptor stops main()
  69. os.close(self._fd)
  70. self._fd = None
  71. os.waitpid(self._pid, 0)
  72. self._pid = None
  73. def getfd(self):
  74. self.ensure_running()
  75. return self._fd
  76. def ensure_running(self):
  77. '''Make sure that resource tracker process is running.
  78. This can be run from any process. Usually a child process will use
  79. the resource created by its parent.'''
  80. with self._lock:
  81. if self._lock._recursion_count() > 1:
  82. # The code below is certainly not reentrant-safe, so bail out
  83. return self._reentrant_call_error()
  84. if self._fd is not None:
  85. # resource tracker was launched before, is it still running?
  86. if self._check_alive():
  87. # => still alive
  88. return
  89. # => dead, launch it again
  90. os.close(self._fd)
  91. # Clean-up to avoid dangling processes.
  92. try:
  93. # _pid can be None if this process is a child from another
  94. # python process, which has started the resource_tracker.
  95. if self._pid is not None:
  96. os.waitpid(self._pid, 0)
  97. except ChildProcessError:
  98. # The resource_tracker has already been terminated.
  99. pass
  100. self._fd = None
  101. self._pid = None
  102. warnings.warn('resource_tracker: process died unexpectedly, '
  103. 'relaunching. Some resources might leak.')
  104. fds_to_pass = []
  105. try:
  106. fds_to_pass.append(sys.stderr.fileno())
  107. except Exception:
  108. pass
  109. cmd = 'from multiprocessing.resource_tracker import main;main(%d)'
  110. r, w = os.pipe()
  111. try:
  112. fds_to_pass.append(r)
  113. # process will out live us, so no need to wait on pid
  114. exe = spawn.get_executable()
  115. args = [exe] + util._args_from_interpreter_flags()
  116. args += ['-c', cmd % r]
  117. # bpo-33613: Register a signal mask that will block the signals.
  118. # This signal mask will be inherited by the child that is going
  119. # to be spawned and will protect the child from a race condition
  120. # that can make the child die before it registers signal handlers
  121. # for SIGINT and SIGTERM. The mask is unregistered after spawning
  122. # the child.
  123. prev_sigmask = None
  124. try:
  125. if _HAVE_SIGMASK:
  126. prev_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
  127. pid = util.spawnv_passfds(exe, args, fds_to_pass)
  128. finally:
  129. if prev_sigmask is not None:
  130. signal.pthread_sigmask(signal.SIG_SETMASK, prev_sigmask)
  131. except:
  132. os.close(w)
  133. raise
  134. else:
  135. self._fd = w
  136. self._pid = pid
  137. finally:
  138. os.close(r)
  139. def _check_alive(self):
  140. '''Check that the pipe has not been closed by sending a probe.'''
  141. try:
  142. # We cannot use send here as it calls ensure_running, creating
  143. # a cycle.
  144. os.write(self._fd, b'PROBE:0:noop\n')
  145. except OSError:
  146. return False
  147. else:
  148. return True
  149. def register(self, name, rtype):
  150. '''Register name of resource with resource tracker.'''
  151. self._send('REGISTER', name, rtype)
  152. def unregister(self, name, rtype):
  153. '''Unregister name of resource with resource tracker.'''
  154. self._send('UNREGISTER', name, rtype)
  155. def _send(self, cmd, name, rtype):
  156. try:
  157. self.ensure_running()
  158. except ReentrantCallError:
  159. # The code below might or might not work, depending on whether
  160. # the resource tracker was already running and still alive.
  161. # Better warn the user.
  162. # (XXX is warnings.warn itself reentrant-safe? :-)
  163. warnings.warn(
  164. f"ResourceTracker called reentrantly for resource cleanup, "
  165. f"which is unsupported. "
  166. f"The {rtype} object {name!r} might leak.")
  167. msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii')
  168. if len(msg) > 512:
  169. # posix guarantees that writes to a pipe of less than PIPE_BUF
  170. # bytes are atomic, and that PIPE_BUF >= 512
  171. raise ValueError('msg too long')
  172. nbytes = os.write(self._fd, msg)
  173. assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format(
  174. nbytes, len(msg))
  175. _resource_tracker = ResourceTracker()
  176. ensure_running = _resource_tracker.ensure_running
  177. register = _resource_tracker.register
  178. unregister = _resource_tracker.unregister
  179. getfd = _resource_tracker.getfd
  180. def main(fd):
  181. '''Run resource tracker.'''
  182. # protect the process from ^C and "killall python" etc
  183. signal.signal(signal.SIGINT, signal.SIG_IGN)
  184. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  185. if _HAVE_SIGMASK:
  186. signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
  187. for f in (sys.stdin, sys.stdout):
  188. try:
  189. f.close()
  190. except Exception:
  191. pass
  192. cache = {rtype: set() for rtype in _CLEANUP_FUNCS.keys()}
  193. try:
  194. # keep track of registered/unregistered resources
  195. with open(fd, 'rb') as f:
  196. for line in f:
  197. try:
  198. cmd, name, rtype = line.strip().decode('ascii').split(':')
  199. cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
  200. if cleanup_func is None:
  201. raise ValueError(
  202. f'Cannot register {name} for automatic cleanup: '
  203. f'unknown resource type {rtype}')
  204. if cmd == 'REGISTER':
  205. cache[rtype].add(name)
  206. elif cmd == 'UNREGISTER':
  207. cache[rtype].remove(name)
  208. elif cmd == 'PROBE':
  209. pass
  210. else:
  211. raise RuntimeError('unrecognized command %r' % cmd)
  212. except Exception:
  213. try:
  214. sys.excepthook(*sys.exc_info())
  215. except:
  216. pass
  217. finally:
  218. # all processes have terminated; cleanup any remaining resources
  219. for rtype, rtype_cache in cache.items():
  220. if rtype_cache:
  221. try:
  222. warnings.warn('resource_tracker: There appear to be %d '
  223. 'leaked %s objects to clean up at shutdown' %
  224. (len(rtype_cache), rtype))
  225. except Exception:
  226. pass
  227. for name in rtype_cache:
  228. # For some reason the process which created and registered this
  229. # resource has failed to unregister it. Presumably it has
  230. # died. We therefore unlink it.
  231. try:
  232. try:
  233. _CLEANUP_FUNCS[rtype](name)
  234. except Exception as e:
  235. warnings.warn('resource_tracker: %r: %s' % (name, e))
  236. finally:
  237. pass