Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 59 additions & 11 deletions infra/worktree-reaper/bin/worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,27 @@ class ProcScanError(OSError):
"""


def proc_cwds():
cwds = []
def _strip_deleted(target):
if target.endswith(" (deleted)"):
target = target[: -len(" (deleted)")]
return target


def proc_refs():
"""All filesystem paths any process is tied to, from /proc (#6898).

For each pid: its cwd, its exe, every open fd target, and every
absolute-path token in its cmdline. The cwd-only scan this replaces
could not see a process holding an open file in a tree (or running
a binary from it) with its cwd elsewhere, so the reaper could
delete a tree in active use. Cost is bounded by the number of
processes plus their open fds (one readlink per fd), the same
order as any /proc scan. Per-pid errors (the process exited
mid-scan, or its entries are not ours to inspect) skip that entry,
exactly as the cwd scan did; only failing to list /proc itself
raises ProcScanError (fail closed, #5740).
"""
refs = []
me = str(os.getpid())
try:
pids = os.listdir("/proc")
Expand All @@ -434,20 +453,49 @@ def proc_cwds():
for pid in pids:
if not pid.isdigit() or pid == me:
continue
base = os.path.join("/proc", pid)
for name in ("cwd", "exe"):
try:
target = os.readlink(os.path.join(base, name))
except OSError:
continue
target = _strip_deleted(target)
if target.startswith("/"):
refs.append(target)
try:
target = os.readlink(os.path.join("/proc", pid, "cwd"))
fds = os.listdir(os.path.join(base, "fd"))
except OSError:
continue
if target.endswith(" (deleted)"):
target = target[: -len(" (deleted)")]
cwds.append(target)
return cwds
fds = []
for fd in fds:
try:
target = os.readlink(os.path.join(base, "fd", fd))
except OSError:
continue
target = _strip_deleted(target)
if target.startswith("/"):
refs.append(target)
try:
with open(os.path.join(base, "cmdline"), "rb") as fh:
tokens = fh.read().split(b"\0")
except OSError:
tokens = []
for token in tokens:
path = token.decode("utf-8", "surrogateescape")
if path.startswith("/"):
refs.append(path)
return refs


def proc_cwds():
"""Backward-compatible name: the scan now returns every /proc path
reference (cwd, exe, fd targets, cmdline paths), not only cwds."""
return proc_refs()


def tree_occupied(tree, cwds=None):
rp = os.path.realpath(tree)
for cwd in (proc_cwds() if cwds is None else cwds):
c = os.path.realpath(cwd)
for ref in (proc_refs() if cwds is None else cwds):
c = os.path.realpath(ref)
if c == rp or c.startswith(rp + os.sep):
return True
return False
Expand Down Expand Up @@ -620,7 +668,7 @@ def main(argv=None):

primaries = [expand(p) for p in args.primary] or discover_primaries(cfg)
try:
cwds = proc_cwds()
cwds = proc_refs()
except ProcScanError as exc:
# Fail closed (#5740): with no trustworthy occupancy scan,
# nothing in this run may be removed — stop before evaluating.
Expand Down
84 changes: 84 additions & 0 deletions infra/worktree-reaper/tests/test_worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,5 +426,89 @@ def fake_run_git(*args, **kwargs):
shutil.rmtree(root, ignore_errors=True)



class FdOccupancyTests(unittest.TestCase):
"""#6898: occupancy must see open fds and cmdline paths, not only cwds."""

def _wait_occupied(self, root, want=True):
deadline = time.time() + 10
while time.time() < deadline:
if wr.tree_occupied(root) == want:
return True
time.sleep(0.1)
return wr.tree_occupied(root) == want

def test_open_fd_in_tree_occupies_with_cwd_outside(self):
root = tempfile.mkdtemp(prefix="wtreaper-fd-")
holder = None
try:
held = os.path.join(root, "held.txt")
with open(held, "w") as fh:
fh.write("x")
# The path reaches the child via the environment, so its
# cmdline carries no reference to the tree: only the open
# fd can give it away. Its cwd is outside the tree.
holder = subprocess.Popen(
[sys.executable, "-c",
"import os, time; fh = open(os.environ['WR_HELD']); time.sleep(60)"],
cwd="/", env={**os.environ, "WR_HELD": held})
self.assertTrue(self._wait_occupied(root),
"a process holding an open file in the tree must occupy it")
finally:
if holder is not None:
holder.terminate()
holder.wait(timeout=10)
shutil.rmtree(root, ignore_errors=True)

def test_cmdline_path_in_tree_occupies(self):
root = tempfile.mkdtemp(prefix="wtreaper-cmdline-")
holder = None
try:
target = os.path.join(root, "mentioned.txt")
# The child never opens the file; the tree path appears
# only as an argv token in its cmdline.
holder = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(60)", target],
cwd="/")
self.assertTrue(self._wait_occupied(root),
"a cmdline path inside the tree must occupy it")
finally:
if holder is not None:
holder.terminate()
holder.wait(timeout=10)
shutil.rmtree(root, ignore_errors=True)

def test_reap_tree_recheck_sees_fd_holder(self):
root = tempfile.mkdtemp(prefix="wtreaper-fd-reap-")
holder = None
try:
held = os.path.join(root, "held.txt")
with open(held, "w") as fh:
fh.write("x")
holder = subprocess.Popen(
[sys.executable, "-c",
"import os, time; fh = open(os.environ['WR_HELD']); time.sleep(60)"],
cwd="/", env={**os.environ, "WR_HELD": held})
self.assertTrue(self._wait_occupied(root))
rec = {"tree": root, "branch": "queue/test", "action": "candidate"}
git_calls = []

def fake_run_git(*args, **kwargs):
git_calls.append(args)
return 0, "", ""

with mock.patch.object(wr, "run_git", fake_run_git), \
contextlib.redirect_stdout(io.StringIO()):
result = wr.reap_tree("/nonexistent-primary", rec, {})
self.assertFalse(result)
self.assertEqual(rec["reason"], "occupied-at-removal")
self.assertEqual(git_calls, [], "no git call may run while an fd holder lives")
self.assertTrue(os.path.isdir(root), "candidate tree must be retained")
finally:
if holder is not None:
holder.terminate()
holder.wait(timeout=10)
shutil.rmtree(root, ignore_errors=True)

if __name__ == "__main__":
unittest.main(verbosity=2)
Loading