reduction.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #
  2. # Module to allow connection and socket objects to be transferred
  3. # between processes
  4. #
  5. # multiprocessing/reduction.py
  6. #
  7. # Copyright (c) 2006-2008, R Oudkerk
  8. # Licensed to PSF under a Contributor Agreement.
  9. #
  10. from __future__ import absolute_import
  11. import os
  12. import sys
  13. import socket
  14. import threading
  15. from pickle import Pickler
  16. from .. import current_process
  17. from .._ext import _billiard, win32
  18. from ..util import register_after_fork, debug, sub_debug
  19. is_win32 = sys.platform == 'win32'
  20. is_pypy = hasattr(sys, 'pypy_version_info')
  21. is_py3k = sys.version_info[0] == 3
  22. if not(is_win32 or is_pypy or is_py3k or hasattr(_billiard, 'recvfd')):
  23. raise ImportError('pickling of connections not supported')
  24. close = win32.CloseHandle if sys.platform == 'win32' else os.close
  25. __all__ = []
  26. # globals set later
  27. _listener = None
  28. _lock = None
  29. _cache = set()
  30. #
  31. # ForkingPickler
  32. #
  33. class ForkingPickler(Pickler): # noqa
  34. dispatch = Pickler.dispatch.copy()
  35. @classmethod
  36. def register(cls, type, reduce):
  37. def dispatcher(self, obj):
  38. rv = reduce(obj)
  39. self.save_reduce(obj=obj, *rv)
  40. cls.dispatch[type] = dispatcher
  41. def _reduce_method(m): # noqa
  42. if m.__self__ is None:
  43. return getattr, (m.__self__.__class__, m.__func__.__name__)
  44. else:
  45. return getattr, (m.__self__, m.__func__.__name__)
  46. ForkingPickler.register(type(ForkingPickler.save), _reduce_method)
  47. def _reduce_method_descriptor(m):
  48. return getattr, (m.__objclass__, m.__name__)
  49. ForkingPickler.register(type(list.append), _reduce_method_descriptor)
  50. ForkingPickler.register(type(int.__add__), _reduce_method_descriptor)
  51. try:
  52. from functools import partial
  53. except ImportError:
  54. pass
  55. else:
  56. def _reduce_partial(p):
  57. return _rebuild_partial, (p.func, p.args, p.keywords or {})
  58. def _rebuild_partial(func, args, keywords):
  59. return partial(func, *args, **keywords)
  60. ForkingPickler.register(partial, _reduce_partial)
  61. def dump(obj, file, protocol=None):
  62. ForkingPickler(file, protocol).dump(obj)
  63. #
  64. # Platform specific definitions
  65. #
  66. if sys.platform == 'win32':
  67. # XXX Should this subprocess import be here?
  68. import _subprocess # noqa
  69. def send_handle(conn, handle, destination_pid):
  70. from ..forking import duplicate
  71. process_handle = win32.OpenProcess(
  72. win32.PROCESS_ALL_ACCESS, False, destination_pid
  73. )
  74. try:
  75. new_handle = duplicate(handle, process_handle)
  76. conn.send(new_handle)
  77. finally:
  78. close(process_handle)
  79. def recv_handle(conn):
  80. return conn.recv()
  81. else:
  82. def send_handle(conn, handle, destination_pid): # noqa
  83. _billiard.sendfd(conn.fileno(), handle)
  84. def recv_handle(conn): # noqa
  85. return _billiard.recvfd(conn.fileno())
  86. #
  87. # Support for a per-process server thread which caches pickled handles
  88. #
  89. def _reset(obj):
  90. global _lock, _listener, _cache
  91. for h in _cache:
  92. close(h)
  93. _cache.clear()
  94. _lock = threading.Lock()
  95. _listener = None
  96. _reset(None)
  97. register_after_fork(_reset, _reset)
  98. def _get_listener():
  99. global _listener
  100. if _listener is None:
  101. _lock.acquire()
  102. try:
  103. if _listener is None:
  104. from ..connection import Listener
  105. debug('starting listener and thread for sending handles')
  106. _listener = Listener(authkey=current_process().authkey)
  107. t = threading.Thread(target=_serve)
  108. t.daemon = True
  109. t.start()
  110. finally:
  111. _lock.release()
  112. return _listener
  113. def _serve():
  114. from ..util import is_exiting, sub_warning
  115. while 1:
  116. try:
  117. conn = _listener.accept()
  118. handle_wanted, destination_pid = conn.recv()
  119. _cache.remove(handle_wanted)
  120. send_handle(conn, handle_wanted, destination_pid)
  121. close(handle_wanted)
  122. conn.close()
  123. except:
  124. if not is_exiting():
  125. sub_warning('thread for sharing handles raised exception',
  126. exc_info=True)
  127. #
  128. # Functions to be used for pickling/unpickling objects with handles
  129. #
  130. def reduce_handle(handle):
  131. from ..forking import Popen, duplicate
  132. if Popen.thread_is_spawning():
  133. return (None, Popen.duplicate_for_child(handle), True)
  134. dup_handle = duplicate(handle)
  135. _cache.add(dup_handle)
  136. sub_debug('reducing handle %d', handle)
  137. return (_get_listener().address, dup_handle, False)
  138. def rebuild_handle(pickled_data):
  139. from ..connection import Client
  140. address, handle, inherited = pickled_data
  141. if inherited:
  142. return handle
  143. sub_debug('rebuilding handle %d', handle)
  144. conn = Client(address, authkey=current_process().authkey)
  145. conn.send((handle, os.getpid()))
  146. new_handle = recv_handle(conn)
  147. conn.close()
  148. return new_handle
  149. #
  150. # Register `_billiard.Connection` with `ForkingPickler`
  151. #
  152. def reduce_connection(conn):
  153. rh = reduce_handle(conn.fileno())
  154. return rebuild_connection, (rh, conn.readable, conn.writable)
  155. def rebuild_connection(reduced_handle, readable, writable):
  156. handle = rebuild_handle(reduced_handle)
  157. return _billiard.Connection(
  158. handle, readable=readable, writable=writable
  159. )
  160. # Register `socket.socket` with `ForkingPickler`
  161. #
  162. def fromfd(fd, family, type_, proto=0):
  163. s = socket.fromfd(fd, family, type_, proto)
  164. if s.__class__ is not socket.socket:
  165. s = socket.socket(_sock=s)
  166. return s
  167. def reduce_socket(s):
  168. reduced_handle = reduce_handle(s.fileno())
  169. return rebuild_socket, (reduced_handle, s.family, s.type, s.proto)
  170. def rebuild_socket(reduced_handle, family, type_, proto):
  171. fd = rebuild_handle(reduced_handle)
  172. _sock = fromfd(fd, family, type_, proto)
  173. close(fd)
  174. return _sock
  175. ForkingPickler.register(socket.socket, reduce_socket)
  176. #
  177. # Register `_billiard.PipeConnection` with `ForkingPickler`
  178. #
  179. if sys.platform == 'win32':
  180. def reduce_pipe_connection(conn):
  181. rh = reduce_handle(conn.fileno())
  182. return rebuild_pipe_connection, (rh, conn.readable, conn.writable)
  183. def rebuild_pipe_connection(reduced_handle, readable, writable):
  184. handle = rebuild_handle(reduced_handle)
  185. return _billiard.PipeConnection(
  186. handle, readable=readable, writable=writable
  187. )