resource_tracker.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. _CLEANUP_FUNCS.update({
  34. 'semaphore': _multiprocessing.sem_unlink,
  35. 'shared_memory': _posixshmem.shm_unlink,
  36. })
  37. class ResourceTracker(object):
  38. def __init__(self):
  39. self._lock = threading.Lock()
  40. self._fd = None
  41. self._pid = None
  42. def _stop(self):
  43. with self._lock:
  44. if self._fd is None:
  45. # not running
  46. return
  47. # closing the "alive" file descriptor stops main()
  48. os.close(self._fd)
  49. self._fd = None
  50. os.waitpid(self._pid, 0)
  51. self._pid = None
  52. def getfd(self):
  53. self.ensure_running()
  54. return self._fd
  55. def ensure_running(self):
  56. '''Make sure that resource tracker process is running.
  57. This can be run from any process. Usually a child process will use
  58. the resource created by its parent.'''
  59. with self._lock:
  60. if self._fd is not None:
  61. # resource tracker was launched before, is it still running?
  62. if self._check_alive():
  63. # => still alive
  64. return
  65. # => dead, launch it again
  66. os.close(self._fd)
  67. # Clean-up to avoid dangling processes.
  68. try:
  69. # _pid can be None if this process is a child from another
  70. # python process, which has started the resource_tracker.
  71. if self._pid is not None:
  72. os.waitpid(self._pid, 0)
  73. except ChildProcessError:
  74. # The resource_tracker has already been terminated.
  75. pass
  76. self._fd = None
  77. self._pid = None
  78. warnings.warn('resource_tracker: process died unexpectedly, '
  79. 'relaunching. Some resources might leak.')
  80. fds_to_pass = []
  81. try:
  82. fds_to_pass.append(sys.stderr.fileno())
  83. except Exception:
  84. pass
  85. cmd = 'from multiprocessing.resource_tracker import main;main(%d)'
  86. r, w = os.pipe()
  87. try:
  88. fds_to_pass.append(r)
  89. # process will out live us, so no need to wait on pid
  90. exe = spawn.get_executable()
  91. args = [exe] + util._args_from_interpreter_flags()
  92. args += ['-c', cmd % r]
  93. # bpo-33613: Register a signal mask that will block the signals.
  94. # This signal mask will be inherited by the child that is going
  95. # to be spawned and will protect the child from a race condition
  96. # that can make the child die before it registers signal handlers
  97. # for SIGINT and SIGTERM. The mask is unregistered after spawning
  98. # the child.
  99. try:
  100. if _HAVE_SIGMASK:
  101. signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
  102. pid = util.spawnv_passfds(exe, args, fds_to_pass)
  103. finally:
  104. if _HAVE_SIGMASK:
  105. signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
  106. except:
  107. os.close(w)
  108. raise
  109. else:
  110. self._fd = w
  111. self._pid = pid
  112. finally:
  113. os.close(r)
  114. def _check_alive(self):
  115. '''Check that the pipe has not been closed by sending a probe.'''
  116. try:
  117. # We cannot use send here as it calls ensure_running, creating
  118. # a cycle.
  119. os.write(self._fd, b'PROBE:0:noop\n')
  120. except OSError:
  121. return False
  122. else:
  123. return True
  124. def register(self, name, rtype):
  125. '''Register name of resource with resource tracker.'''
  126. self._send('REGISTER', name, rtype)
  127. def unregister(self, name, rtype):
  128. '''Unregister name of resource with resource tracker.'''
  129. self._send('UNREGISTER', name, rtype)
  130. def _send(self, cmd, name, rtype):
  131. self.ensure_running()
  132. msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii')
  133. if len(name) > 512:
  134. # posix guarantees that writes to a pipe of less than PIPE_BUF
  135. # bytes are atomic, and that PIPE_BUF >= 512
  136. raise ValueError('name too long')
  137. nbytes = os.write(self._fd, msg)
  138. assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format(
  139. nbytes, len(msg))
  140. _resource_tracker = ResourceTracker()
  141. ensure_running = _resource_tracker.ensure_running
  142. register = _resource_tracker.register
  143. unregister = _resource_tracker.unregister
  144. getfd = _resource_tracker.getfd
  145. def main(fd):
  146. '''Run resource tracker.'''
  147. # protect the process from ^C and "killall python" etc
  148. signal.signal(signal.SIGINT, signal.SIG_IGN)
  149. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  150. if _HAVE_SIGMASK:
  151. signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
  152. for f in (sys.stdin, sys.stdout):
  153. try:
  154. f.close()
  155. except Exception:
  156. pass
  157. cache = {rtype: set() for rtype in _CLEANUP_FUNCS.keys()}
  158. try:
  159. # keep track of registered/unregistered resources
  160. with open(fd, 'rb') as f:
  161. for line in f:
  162. try:
  163. cmd, name, rtype = line.strip().decode('ascii').split(':')
  164. cleanup_func = _CLEANUP_FUNCS.get(rtype, None)
  165. if cleanup_func is None:
  166. raise ValueError(
  167. f'Cannot register {name} for automatic cleanup: '
  168. f'unknown resource type {rtype}')
  169. if cmd == 'REGISTER':
  170. cache[rtype].add(name)
  171. elif cmd == 'UNREGISTER':
  172. cache[rtype].remove(name)
  173. elif cmd == 'PROBE':
  174. pass
  175. else:
  176. raise RuntimeError('unrecognized command %r' % cmd)
  177. except Exception:
  178. try:
  179. sys.excepthook(*sys.exc_info())
  180. except:
  181. pass
  182. finally:
  183. # all processes have terminated; cleanup any remaining resources
  184. for rtype, rtype_cache in cache.items():
  185. if rtype_cache:
  186. try:
  187. warnings.warn('resource_tracker: There appear to be %d '
  188. 'leaked %s objects to clean up at shutdown' %
  189. (len(rtype_cache), rtype))
  190. except Exception:
  191. pass
  192. for name in rtype_cache:
  193. # For some reason the process which created and registered this
  194. # resource has failed to unregister it. Presumably it has
  195. # died. We therefore unlink it.
  196. try:
  197. try:
  198. _CLEANUP_FUNCS[rtype](name)
  199. except Exception as e:
  200. warnings.warn('resource_tracker: %r: %s' % (name, e))
  201. finally:
  202. pass