Skip to content

Commit 8c2c396

Browse files
committed
make resource_tracker re-entrant safe
1 parent 151d1bf commit 8c2c396

File tree

1 file changed

+96
-75
lines changed

1 file changed

+96
-75
lines changed

Lib/multiprocessing/resource_tracker.py

Lines changed: 96 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ def __init__(self):
6666
self._fd = None
6767
self._pid = None
6868
self._exitcode = None
69+
self._reentrant_messages = collections.deque()
6970

7071
def _reentrant_call_error(self):
7172
# gh-109629: this happens if an explicit call to the ResourceTracker
@@ -132,80 +133,108 @@ def ensure_running(self):
132133
133134
This can be run from any process. Usually a child process will use
134135
the resource created by its parent.'''
136+
return self._ensure_running()
137+
138+
def _teardown_dead_process(self):
139+
os.close(self._fd)
140+
141+
# Clean-up to avoid dangling processes.
142+
try:
143+
# _pid can be None if this process is a child from another
144+
# python process, which has started the resource_tracker.
145+
if self._pid is not None:
146+
os.waitpid(self._pid, 0)
147+
except ChildProcessError:
148+
# The resource_tracker has already been terminated.
149+
pass
150+
self._fd = None
151+
self._pid = None
152+
self._exitcode = None
153+
154+
warnings.warn('resource_tracker: process died unexpectedly, '
155+
'relaunching. Some resources might leak.')
156+
157+
def _launch(self):
158+
fds_to_pass = []
159+
try:
160+
fds_to_pass.append(sys.stderr.fileno())
161+
except Exception:
162+
pass
163+
cmd = 'from multiprocessing.resource_tracker import main;main(%d)'
164+
r, w = os.pipe()
165+
try:
166+
fds_to_pass.append(r)
167+
# process will out live us, so no need to wait on pid
168+
exe = spawn.get_executable()
169+
args = [exe] + util._args_from_interpreter_flags()
170+
args += ['-c', cmd % r]
171+
# bpo-33613: Register a signal mask that will block the signals.
172+
# This signal mask will be inherited by the child that is going
173+
# to be spawned and will protect the child from a race condition
174+
# that can make the child die before it registers signal handlers
175+
# for SIGINT and SIGTERM. The mask is unregistered after spawning
176+
# the child.
177+
prev_sigmask = None
178+
try:
179+
if _HAVE_SIGMASK:
180+
prev_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
181+
pid = util.spawnv_passfds(exe, args, fds_to_pass)
182+
finally:
183+
if prev_sigmask is not None:
184+
signal.pthread_sigmask(signal.SIG_SETMASK, prev_sigmask)
185+
except:
186+
os.close(w)
187+
raise
188+
else:
189+
self._fd = w
190+
self._pid = pid
191+
finally:
192+
os.close(r)
193+
194+
def _ensure_running_and_write(self, msg=None):
135195
with self._lock:
136196
if self._lock._recursion_count() > 1:
137197
# The code below is certainly not reentrant-safe, so bail out
138-
return self._reentrant_call_error()
198+
if msg is not None:
199+
self._reentrant_messages.append(msg)
200+
return
139201
if self._fd is not None:
140202
# resource tracker was launched before, is it still running?
141-
if self._check_alive():
142-
# => still alive
143-
return
144-
# => dead, launch it again
145-
os.close(self._fd)
146-
147-
# Clean-up to avoid dangling processes.
203+
if msg is None:
204+
to_send = b'PROBE:0:noop\n'
205+
else:
206+
to_send = msg
148207
try:
149-
# _pid can be None if this process is a child from another
150-
# python process, which has started the resource_tracker.
151-
if self._pid is not None:
152-
os.waitpid(self._pid, 0)
153-
except ChildProcessError:
154-
# The resource_tracker has already been terminated.
155-
pass
156-
self._fd = None
157-
self._pid = None
158-
self._exitcode = None
159-
160-
warnings.warn('resource_tracker: process died unexpectedly, '
161-
'relaunching. Some resources might leak.')
162-
163-
fds_to_pass = []
164-
try:
165-
fds_to_pass.append(sys.stderr.fileno())
166-
except Exception:
167-
pass
168-
cmd = 'from multiprocessing.resource_tracker import main;main(%d)'
169-
r, w = os.pipe()
170-
try:
171-
fds_to_pass.append(r)
172-
# process will out live us, so no need to wait on pid
173-
exe = spawn.get_executable()
174-
args = [exe] + util._args_from_interpreter_flags()
175-
args += ['-c', cmd % r]
176-
# bpo-33613: Register a signal mask that will block the signals.
177-
# This signal mask will be inherited by the child that is going
178-
# to be spawned and will protect the child from a race condition
179-
# that can make the child die before it registers signal handlers
180-
# for SIGINT and SIGTERM. The mask is unregistered after spawning
181-
# the child.
182-
prev_sigmask = None
183-
try:
184-
if _HAVE_SIGMASK:
185-
prev_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
186-
pid = util.spawnv_passfds(exe, args, fds_to_pass)
187-
finally:
188-
if prev_sigmask is not None:
189-
signal.pthread_sigmask(signal.SIG_SETMASK, prev_sigmask)
190-
except:
191-
os.close(w)
192-
raise
208+
self._write(to_send)
209+
except OSError:
210+
dead = True
211+
else:
212+
dead = False
213+
if dead:
214+
self._teardown_dead_process()
215+
self._launch()
216+
217+
msg = None # message was sent in probe
193218
else:
194-
self._fd = w
195-
self._pid = pid
196-
finally:
197-
os.close(r)
219+
self._launch()
198220

199-
def _check_alive(self):
221+
while True:
222+
try:
223+
reentrant_msg = self._reentrant_messages.popleft()
224+
except IndexError:
225+
break
226+
self._write(reentrant_msg)
227+
if msg is not None:
228+
self._write(msg)
229+
230+
def _check_alive(self, msg=b'PROBE:0:noop\n'):
200231
'''Check that the pipe has not been closed by sending a probe.'''
201232
try:
202233
# We cannot use send here as it calls ensure_running, creating
203234
# a cycle.
204-
os.write(self._fd, b'PROBE:0:noop\n')
235+
return os.write(self._fd, b'PROBE:0:noop\n')
205236
except OSError:
206-
return False
207-
else:
208-
return True
237+
return None
209238

210239
def register(self, name, rtype):
211240
'''Register name of resource with resource tracker.'''
@@ -215,27 +244,19 @@ def unregister(self, name, rtype):
215244
'''Unregister name of resource with resource tracker.'''
216245
self._send('UNREGISTER', name, rtype)
217246

247+
def _write(self, msg):
248+
nbytes = os.write(self._fd, msg)
249+
assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format(
250+
nbytes, len(msg))
251+
218252
def _send(self, cmd, name, rtype):
219-
try:
220-
self.ensure_running()
221-
except ReentrantCallError:
222-
# The code below might or might not work, depending on whether
223-
# the resource tracker was already running and still alive.
224-
# Better warn the user.
225-
# (XXX is warnings.warn itself reentrant-safe? :-)
226-
warnings.warn(
227-
f"ResourceTracker called reentrantly for resource cleanup, "
228-
f"which is unsupported. "
229-
f"The {rtype} object {name!r} might leak.")
230253
msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii')
231254
if len(msg) > 512:
232255
# posix guarantees that writes to a pipe of less than PIPE_BUF
233256
# bytes are atomic, and that PIPE_BUF >= 512
234257
raise ValueError('msg too long')
235-
nbytes = os.write(self._fd, msg)
236-
assert nbytes == len(msg), "nbytes {0:n} but len(msg) {1:n}".format(
237-
nbytes, len(msg))
238258

259+
self._ensure_running_and_write(msg)
239260

240261
_resource_tracker = ResourceTracker()
241262
ensure_running = _resource_tracker.ensure_running

0 commit comments

Comments
 (0)