Debian Codegraph @

lib-python/3/multiprocessing/reduction.py

raw symbols SCIP
1 #
2 # Module which deals with pickling of objects.
3 #
4 # multiprocessing/reduction.py
5 #
6 # Copyright (c) 2006-2008, R Oudkerk
7 # Licensed to PSF under a Contributor Agreement.
8 #
9
10 from abc import ABCMeta
11 import copyreg
12 import functools
13 import io
14 import os
15 import pickle
16 import socket
17 import sys
18
19 from . import context
20
21 __all__ = ['send_handle', 'recv_handle', 'ForkingPickler', 'register', 'dump']
22
23
24 HAVE_SEND_HANDLE = (sys.platform == 'win32' or
25 (hasattr(socket, 'CMSG_LEN') and
26 hasattr(socket, 'SCM_RIGHTS') and
27 hasattr(socket.socket, 'sendmsg')))
28
29 #
30 # Pickler subclass
31 #
32
33 class ForkingPickler(pickle.Pickler):
34 '''Pickler subclass used by multiprocessing.'''
35 _extra_reducers = {}
36 _copyreg_dispatch_table = copyreg.dispatch_table
37
38 def __init__(self, *args):
39 super().__init__(*args)
40 self.dispatch_table = self._copyreg_dispatch_table.copy()
41 self.dispatch_table.update(self._extra_reducers)
42 if hasattr(self, 'pypy_extensions'):
43 self.pypy_extensions = True
44
45 @classmethod
46 def register(cls, type, reduce):
47 '''Register a reduce function for a type.'''
48 cls._extra_reducers[type] = reduce
49
50 @classmethod
51 def dumps(cls, obj, protocol=None):
52 buf = io.BytesIO()
53 cls(buf, protocol).dump(obj)
54 return buf.getbuffer()
55
56 loads = pickle.loads
57
58 register = ForkingPickler.register
59
60 def dump(obj, file, protocol=None):
61 '''Replacement for pickle.dump() using ForkingPickler.'''
62 ForkingPickler(file, protocol).dump(obj)
63
64 #
65 # Platform specific definitions
66 #
67
68 if sys.platform == 'win32':
69 # Windows
70 __all__ += ['DupHandle', 'duplicate', 'steal_handle']
71 import _winapi
72
73 def duplicate(handle, target_process=None, inheritable=False,
74 *, source_process=None):
75 '''Duplicate a handle. (target_process is a handle not a pid!)'''
76 current_process = _winapi.GetCurrentProcess()
77 if source_process is None:
78 source_process = current_process
79 if target_process is None:
80 target_process = current_process
81 return _winapi.DuplicateHandle(
82 source_process, handle, target_process,
83 0, inheritable, _winapi.DUPLICATE_SAME_ACCESS)
84
85 def steal_handle(source_pid, handle):
86 '''Steal a handle from process identified by source_pid.'''
87 source_process_handle = _winapi.OpenProcess(
88 _winapi.PROCESS_DUP_HANDLE, False, source_pid)
89 try:
90 return _winapi.DuplicateHandle(
91 source_process_handle, handle,
92 _winapi.GetCurrentProcess(), 0, False,
93 _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
94 finally:
95 _winapi.CloseHandle(source_process_handle)
96
97 def send_handle(conn, handle, destination_pid):
98 '''Send a handle over a local connection.'''
99 dh = DupHandle(handle, _winapi.DUPLICATE_SAME_ACCESS, destination_pid)
100 conn.send(dh)
101
102 def recv_handle(conn):
103 '''Receive a handle over a local connection.'''
104 return conn.recv().detach()
105
106 class DupHandle(object):
107 '''Picklable wrapper for a handle.'''
108 def __init__(self, handle, access, pid=None):
109 if pid is None:
110 # We just duplicate the handle in the current process and
111 # let the receiving process steal the handle.
112 pid = os.getpid()
113 proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid)
114 try:
115 self._handle = _winapi.DuplicateHandle(
116 _winapi.GetCurrentProcess(),
117 handle, proc, access, False, 0)
118 finally:
119 _winapi.CloseHandle(proc)
120 self._access = access
121 self._pid = pid
122
123 def detach(self):
124 '''Get the handle. This should only be called once.'''
125 # retrieve handle from process which currently owns it
126 if self._pid == os.getpid():
127 # The handle has already been duplicated for this process.
128 return self._handle
129 # We must steal the handle from the process whose pid is self._pid.
130 proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False,
131 self._pid)
132 try:
133 return _winapi.DuplicateHandle(
134 proc, self._handle, _winapi.GetCurrentProcess(),
135 self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE)
136 finally:
137 _winapi.CloseHandle(proc)
138
139 else:
140 # Unix
141 __all__ += ['DupFd', 'sendfds', 'recvfds']
142 import array
143
144 # On MacOSX we should acknowledge receipt of fds -- see Issue14669
145 ACKNOWLEDGE = sys.platform == 'darwin'
146
147 def sendfds(sock, fds):
148 '''Send an array of fds over an AF_UNIX socket.'''
149 fds = array.array('i', fds)
150 msg = bytes([len(fds) % 256])
151 sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
152 if ACKNOWLEDGE and sock.recv(1) != b'A':
153 raise RuntimeError('did not receive acknowledgement of fd')
154
155 def recvfds(sock, size):
156 '''Receive an array of fds over an AF_UNIX socket.'''
157 a = array.array('i')
158 bytes_size = a.itemsize * size
159 msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_SPACE(bytes_size))
160 if not msg and not ancdata:
161 raise EOFError
162 try:
163 if ACKNOWLEDGE:
164 sock.send(b'A')
165 if len(ancdata) != 1:
166 raise RuntimeError('received %d items of ancdata' %
167 len(ancdata))
168 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
169 if (cmsg_level == socket.SOL_SOCKET and
170 cmsg_type == socket.SCM_RIGHTS):
171 if len(cmsg_data) % a.itemsize != 0:
172 raise ValueError
173 a.frombytes(cmsg_data)
174 if len(a) % 256 != msg[0]:
175 raise AssertionError(
176 "Len is {0:n} but msg[0] is {1!r}".format(
177 len(a), msg[0]))
178 return list(a)
179 except (ValueError, IndexError):
180 pass
181 raise RuntimeError('Invalid data received')
182
183 def send_handle(conn, handle, destination_pid):
184 '''Send a handle over a local connection.'''
185 with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s:
186 sendfds(s, [handle])
187
188 def recv_handle(conn):
189 '''Receive a handle over a local connection.'''
190 with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s:
191 return recvfds(s, 1)[0]
192
193 def DupFd(fd):
194 '''Return a wrapper for an fd.'''
195 popen_obj = context.get_spawning_popen()
196 if popen_obj is not None:
197 return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
198 elif HAVE_SEND_HANDLE:
199 from . import resource_sharer
200 return resource_sharer.DupFd(fd)
201 else:
202 raise ValueError('SCM_RIGHTS appears not to be available')
203
204 #
205 # Try making some callable types picklable
206 #
207
208 def _reduce_method(m):
209 if m.__self__ is None:
210 return getattr, (m.__class__, m.__func__.__name__)
211 else:
212 return getattr, (m.__self__, m.__func__.__name__)
213 class _C:
214 def f(self):
215 pass
216 register(type(_C().f), _reduce_method)
217
218
219 def _reduce_method_descriptor(m):
220 return getattr, (m.__objclass__, m.__name__)
221 register(type(list.append), _reduce_method_descriptor)
222 register(type(int.__add__), _reduce_method_descriptor)
223
224
225 def _reduce_partial(p):
226 return _rebuild_partial, (p.func, p.args, p.keywords or {})
227 def _rebuild_partial(func, args, keywords):
228 return functools.partial(func, *args, **keywords)
229 register(functools.partial, _reduce_partial)
230
231 #
232 # Make sockets picklable
233 #
234
235 if sys.platform == 'win32':
236 def _reduce_socket(s):
237 from .resource_sharer import DupSocket
238 return _rebuild_socket, (DupSocket(s),)
239 def _rebuild_socket(ds):
240 return ds.detach()
241 register(socket.socket, _reduce_socket)
242
243 else:
244 def _reduce_socket(s):
245 df = DupFd(s.fileno())
246 return _rebuild_socket, (df, s.family, s.type, s.proto)
247 def _rebuild_socket(df, family, type, proto):
248 fd = df.detach()
249 return socket.socket(family, type, proto, fileno=fd)
250 register(socket.socket, _reduce_socket)
251
252
253 class AbstractReducer(metaclass=ABCMeta):
254 '''Abstract base class for use in implementing a Reduction class
255 suitable for use in replacing the standard reduction mechanism
256 used in multiprocessing.'''
257 ForkingPickler = ForkingPickler
258 register = register
259 dump = dump
260 send_handle = send_handle
261 recv_handle = recv_handle
262
263 if sys.platform == 'win32':
264 steal_handle = steal_handle
265 duplicate = duplicate
266 DupHandle = DupHandle
267 else:
268 sendfds = sendfds
269 recvfds = recvfds
270 DupFd = DupFd
271
272 _reduce_method = _reduce_method
273 _reduce_method_descriptor = _reduce_method_descriptor
274 _rebuild_partial = _rebuild_partial
275 _reduce_socket = _reduce_socket
276 _rebuild_socket = _rebuild_socket
277
278 def __init__(self, *args):
279 register(type(_C().f), _reduce_method)
280 register(type(list.append), _reduce_method_descriptor)
281 register(type(int.__add__), _reduce_method_descriptor)
282 register(functools.partial, _reduce_partial)
283 register(socket.socket, _reduce_socket)