resource_tracker.py 8.8 KB

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