blob: 010d871638541f03ca06147a2080dc9968fe72fb [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
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 --- see COPYING.txt
8#
9
10__all__ = []
11
12import os
13import sys
14import socket
15import threading
16import copyreg
17
18import _multiprocessing
19from multiprocessing import current_process
20from multiprocessing.forking import Popen, duplicate, close
21from multiprocessing.util import register_after_fork, debug, sub_debug
22from multiprocessing.connection import Client, Listener
23
24
25#
26#
27#
28
29if not(sys.platform == 'win32' or hasattr(_multiprocessing, 'recvfd')):
30 raise ImportError('pickling of connections not supported')
31
32#
33# Platform specific definitions
34#
35
36if sys.platform == 'win32':
37 import _subprocess
38 from ._multiprocessing import win32
39
40 def send_handle(conn, handle, destination_pid):
41 process_handle = win32.OpenProcess(
42 win32.PROCESS_ALL_ACCESS, False, destination_pid
43 )
44 try:
45 new_handle = duplicate(handle, process_handle)
46 conn.send(new_handle)
47 finally:
48 close(process_handle)
49
50 def recv_handle(conn):
51 return conn.recv()
52
53else:
54 def send_handle(conn, handle, destination_pid):
55 _multiprocessing.sendfd(conn.fileno(), handle)
56
57 def recv_handle(conn):
58 return _multiprocessing.recvfd(conn.fileno())
59
60#
61# Support for a per-process server thread which caches pickled handles
62#
63
64_cache = set()
65
66def _reset(obj):
67 global _lock, _listener, _cache
68 for h in _cache:
69 close(h)
70 _cache.clear()
71 _lock = threading.Lock()
72 _listener = None
73
74_reset(None)
75register_after_fork(_reset, _reset)
76
77def _get_listener():
78 global _listener
79
80 if _listener is None:
81 _lock.acquire()
82 try:
83 if _listener is None:
84 debug('starting listener and thread for sending handles')
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +000085 _listener = Listener(authkey=current_process().authkey)
Benjamin Petersone711caf2008-06-11 16:44:04 +000086 t = threading.Thread(target=_serve)
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +000087 t.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +000088 t.start()
89 finally:
90 _lock.release()
91
92 return _listener
93
94def _serve():
95 from .util import is_exiting, sub_warning
96
97 while 1:
98 try:
99 conn = _listener.accept()
100 handle_wanted, destination_pid = conn.recv()
101 _cache.remove(handle_wanted)
102 send_handle(conn, handle_wanted, destination_pid)
103 close(handle_wanted)
104 conn.close()
105 except:
106 if not is_exiting():
107 import traceback
108 sub_warning(
109 'thread for sharing handles raised exception :\n' +
110 '-'*79 + '\n' + traceback.format_exc() + '-'*79
111 )
112
113#
114# Functions to be used for pickling/unpickling objects with handles
115#
116
117def reduce_handle(handle):
118 if Popen.thread_is_spawning():
119 return (None, Popen.duplicate_for_child(handle), True)
120 dup_handle = duplicate(handle)
121 _cache.add(dup_handle)
122 sub_debug('reducing handle %d', handle)
123 return (_get_listener().address, dup_handle, False)
124
125def rebuild_handle(pickled_data):
126 address, handle, inherited = pickled_data
127 if inherited:
128 return handle
129 sub_debug('rebuilding handle %d', handle)
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000130 conn = Client(address, authkey=current_process().authkey)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000131 conn.send((handle, os.getpid()))
132 new_handle = recv_handle(conn)
133 conn.close()
134 return new_handle
135
136#
137# Register `_multiprocessing.Connection` with `copy_reg`
138#
139
140def reduce_connection(conn):
141 rh = reduce_handle(conn.fileno())
142 return rebuild_connection, (rh, conn.readable, conn.writable)
143
144def rebuild_connection(reduced_handle, readable, writable):
145 handle = rebuild_handle(reduced_handle)
146 return _multiprocessing.Connection(
147 handle, readable=readable, writable=writable
148 )
149
150copyreg.pickle(_multiprocessing.Connection, reduce_connection)
151
152#
153# Register `socket.socket` with `copy_reg`
154#
155
156def fromfd(fd, family, type_, proto=0):
157 s = socket.fromfd(fd, family, type_, proto)
158 if s.__class__ is not socket.socket:
159 s = socket.socket(_sock=s)
160 return s
161
162def reduce_socket(s):
163 reduced_handle = reduce_handle(s.fileno())
164 return rebuild_socket, (reduced_handle, s.family, s.type, s.proto)
165
166def rebuild_socket(reduced_handle, family, type_, proto):
167 fd = rebuild_handle(reduced_handle)
168 _sock = fromfd(fd, family, type_, proto)
169 close(fd)
170 return _sock
171
172copyreg.pickle(socket.socket, reduce_socket)
173
174#
175# Register `_multiprocessing.PipeConnection` with `copy_reg`
176#
177
178if sys.platform == 'win32':
179
180 def reduce_pipe_connection(conn):
181 rh = reduce_handle(conn.fileno())
182 return rebuild_pipe_connection, (rh, conn.readable, conn.writable)
183
184 def rebuild_pipe_connection(reduced_handle, readable, writable):
185 handle = rebuild_handle(reduced_handle)
186 return _multiprocessing.PipeConnection(
187 handle, readable=readable, writable=writable
188 )
189
190 copyreg.pickle(_multiprocessing.PipeConnection, reduce_pipe_connection)