resource_tracker.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. try:
  124. if _HAVE_SIGMASK:
  125. signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
  126. pid = util.spawnv_passfds(exe, args, fds_to_pass)
  127. finally:
  128. if _HAVE_SIGMASK:
  129. signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
  130. except:
  131. os.close(w)
  132. raise
  133. else:
  134. self._fd = w
  135. self._pid = pid
  136. finally:
  137. os.close(r)
  138. def _check_alive(self):
  139. '''Check that the pipe has not been closed by sending a probe.'''
  140. try:
  141. # We cannot use send here as it calls ensure_running, creating
  142. # a cycle.
  143. os.write(self._fd, b'PROBE:0:noop\n')
  144. except OSError:
  145. return False
  146. else:
  147. return True
  148. def register(self, name, rtype):
  149. '''Register name of resource with resource tracker.'''
  150. self._send('REGISTER', name, rtype)
  151. def unregister(self, name, rtype):
  152. '''Unregister name of resource with resource tracker.'''
  153. self._send('UNREGISTER', name, rtype)
  154. def _send(self, cmd, name, rtype):
  155. try:
  156. self.ensure_running()
  157. except ReentrantCallError:
  158. # The code below might or might not work, depending on whether
  159. # the resource tracker was already running and still alive.
  160. # Better warn the user.
  161. # (XXX is warnings.warn itself reentrant-safe? :-)
  162. warnings.warn(
  163. f"ResourceTracker called reentrantly for resource cleanup, "
  164. f"which is unsupported. "
  165. f"The {rtype} object {name!r} might leak.")
  166. msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii')
  167. if len(msg) > 512:
  168. # posix guarantees that writes to a pipe of less than PIPE_BUF
  169. # bytes are atomic, and that PIPE_BUF >= 512
  170. raise ValueError('msg too long')
  171. nbytes = os.write(self._fd, msg)
  172. assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format(
  173. nbytes, len(msg))
  174. _resource_tracker = ResourceTracker()
  175. ensure_running = _resource_tracker.ensure_running
  176. register = _resource_tracker.register
  177. unregister = _resource_tracker.unregister
  178. getfd = _resource_tracker.getfd
  179. def main(fd):
  180. '''Run resource tracker.'''
  181. # protect the process from ^C and "killall python" etc
  182. signal.signal(signal.SIGINT, signal.SIG_IGN)
  183. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  184. if _HAVE_SIGMASK:
  185. signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
  186. for f in (sys.stdin, sys.stdout):
  187. try:
  188. f.close()
  189. except Exception:
  190. pass
  191. cache = {rtype: set() for rtype in _CLEANUP_FUNCS.keys()}
  192. try:
  193. # keep track of registered/unregistered resources
  194. with open(fd, 'rb') as f:
  195. for line in f:
  196. try:
  197. cmd, name, rtype = line.strip().decode('ascii').split(':')
  198. cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
  199. if cleanup_func is None:
  200. raise ValueError(
  201. f'Cannot register {name} for automatic cleanup: '
  202. f'unknown resource type {rtype}')
  203. if cmd == 'REGISTER':
  204. cache[rtype].add(name)
  205. elif cmd == 'UNREGISTER':
  206. cache[rtype].remove(name)
  207. elif cmd == 'PROBE':
  208. pass
  209. else:
  210. raise RuntimeError('unrecognized command %r' % cmd)
  211. except Exception:
  212. try:
  213. sys.excepthook(*sys.exc_info())
  214. except:
  215. pass
  216. finally:
  217. # all processes have terminated; cleanup any remaining resources
  218. for rtype, rtype_cache in cache.items():
  219. if rtype_cache:
  220. try:
  221. warnings.warn('resource_tracker: There appear to be %d '
  222. 'leaked %s objects to clean up at shutdown' %
  223. (len(rtype_cache), rtype))
  224. except Exception:
  225. pass
  226. for name in rtype_cache:
  227. # For some reason the process which created and registered this
  228. # resource has failed to unregister it. Presumably it has
  229. # died. We therefore unlink it.
  230. try:
  231. try:
  232. _CLEANUP_FUNCS[rtype](name)
  233. except Exception as e:
  234. warnings.warn('resource_tracker: %r: %s' % (name, e))
  235. finally:
  236. pass