mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
test: never delete a fixture through a live mount
Fixture cleanup trusted fusermount's exit status, ignored unmount failures and then ran rmtree over the fixture, through the mount if it was still attached. unmount_mergerfs now checks the mount table after each attempt, including the lazy -uz fallback, and raises UnmountError if the mount stays attached. The fixture is then kept and its path reported instead of deleted, without masking an exception from the test body. TEST_teardown_safety checks both.
This commit is contained in:
parent
271a4324a7
commit
330e453f43
2 changed files with 180 additions and 7 deletions
133
tests/TEST_teardown_safety
Executable file
133
tests/TEST_teardown_safety
Executable file
|
|
@ -0,0 +1,133 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
# Teardown safety regression: a busy mount must detach through the lazy
|
||||
# `-uz` fallback with backing data intact, and a refused unmount must
|
||||
# propagate while the fixture stays attached and un-removed (rmtree must
|
||||
# never descend through a live mount).
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import posix_parity
|
||||
from posix_parity import UnmountError
|
||||
from posix_parity import fail
|
||||
from posix_parity import find_fusermount
|
||||
from posix_parity import find_mergerfs
|
||||
from posix_parity import is_mount_point
|
||||
from posix_parity import mergerfs_mount
|
||||
from posix_parity import touch
|
||||
|
||||
|
||||
def test_busy_mount_lazy_detach():
|
||||
"""Busy mount: plain -u refuses, -uz detaches, backing stays intact."""
|
||||
with mergerfs_mount() as (mount, branches):
|
||||
touch(os.path.join(mount, "busy"), b"BUSY")
|
||||
holder = os.open(os.path.join(mount, "busy"), os.O_RDONLY)
|
||||
try:
|
||||
# Negative control: the open holder must defeat a plain -u,
|
||||
# so the detach below can only come from the lazy fallback.
|
||||
if subprocess.run([find_fusermount(), "-u", mount],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL).returncode == 0:
|
||||
return fail("busy mount: plain fusermount -u unexpectedly succeeded")
|
||||
posix_parity.unmount_mergerfs(mount)
|
||||
if is_mount_point(mount):
|
||||
return fail("busy mount: still attached after unmount_mergerfs")
|
||||
backings = [b for b in branches if os.path.exists(os.path.join(b, "busy"))]
|
||||
if len(backings) != 1:
|
||||
return fail(f"busy mount: expected one backing file, found {len(backings)}")
|
||||
with open(os.path.join(backings[0], "busy"), "rb") as stream:
|
||||
if stream.read() != b"BUSY":
|
||||
return fail("busy mount: backing content lost across lazy detach")
|
||||
finally:
|
||||
os.close(holder)
|
||||
return 0
|
||||
|
||||
|
||||
def test_refused_unmount_preserves_fixture():
|
||||
"""A refused teardown propagates and never rmtrees the attachment."""
|
||||
original_unmount = posix_parity.unmount_mergerfs
|
||||
|
||||
def refusing_unmount(mountpoint):
|
||||
raise UnmountError("forced unmount failure (teardown safety probe)")
|
||||
|
||||
posix_parity.unmount_mergerfs = refusing_unmount
|
||||
mount = None
|
||||
branches = None
|
||||
raised = None
|
||||
try:
|
||||
try:
|
||||
with mergerfs_mount() as (mount, branches):
|
||||
touch(os.path.join(mount, "keep"), b"PRESERVE")
|
||||
except Exception as exc:
|
||||
raised = exc
|
||||
finally:
|
||||
posix_parity.unmount_mergerfs = original_unmount
|
||||
|
||||
if mount is None:
|
||||
# __enter__ never yielded: mergerfs_mount cleaned its own fixture.
|
||||
return fail(f"refused unmount: teardown failure not propagated: {raised!r}")
|
||||
tmpdir = os.path.dirname(mount)
|
||||
msg = None
|
||||
if not isinstance(raised, UnmountError):
|
||||
msg = f"refused unmount: teardown failure not propagated: {raised!r}"
|
||||
elif not is_mount_point(mount):
|
||||
# The pre-contract teardown rmtree'd here, deleting the backing
|
||||
# tree through the live mount.
|
||||
msg = "refused unmount: fixture no longer attached"
|
||||
else:
|
||||
backings = [b for b in branches if os.path.exists(os.path.join(b, "keep"))]
|
||||
if len(backings) != 1:
|
||||
msg = "refused unmount: backing file missing"
|
||||
else:
|
||||
with open(os.path.join(backings[0], "keep"), "rb") as stream:
|
||||
if stream.read() != b"PRESERVE":
|
||||
msg = "refused unmount: backing content lost"
|
||||
# Leave nothing attached on any exit path; never rmtree beneath a
|
||||
# live mount.
|
||||
note = ""
|
||||
try:
|
||||
if is_mount_point(mount):
|
||||
posix_parity.unmount_mergerfs(mount)
|
||||
except Exception as exc:
|
||||
note = f"; probe cleanup failed ({exc}); fixture preserved at {tmpdir}"
|
||||
else:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
if msg or note:
|
||||
return fail(f"{msg or 'refused unmount: invariants held'}{note}")
|
||||
return 0
|
||||
|
||||
|
||||
def run_checks():
|
||||
for test in (test_busy_mount_lazy_detach,
|
||||
test_refused_unmount_preserves_fixture):
|
||||
rv = test()
|
||||
if rv:
|
||||
return rv
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
if find_mergerfs() is None or find_fusermount() is None:
|
||||
print("mergerfs or fusermount unavailable", end="")
|
||||
return 77
|
||||
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
|
||||
return run_checks()
|
||||
if shutil.which("unshare") is None:
|
||||
print("unshare unavailable", end="")
|
||||
return 77
|
||||
probe = subprocess.run(["unshare", "-Urm", "true"],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if probe.returncode:
|
||||
print("private user/mount namespaces unavailable", end="")
|
||||
return 77
|
||||
# Match the other mount tests: mount inside a private namespace so
|
||||
# setuid fusermount works for non-root runs.
|
||||
return subprocess.run(["unshare", "-Urm", sys.executable,
|
||||
os.path.realpath(__file__), "--isolated"]).returncode
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
import ctypes
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
|
|
@ -46,16 +47,46 @@ def mount_mergerfs(branches, mountpoint, options=None):
|
|||
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
|
||||
|
||||
class UnmountError(Exception):
|
||||
"""Teardown failure, not a RuntimeError that callers treat as a skip."""
|
||||
|
||||
|
||||
def is_mount_point(path):
|
||||
# Resolve symlinked parents, but never stat a dead FUSE mount on Linux.
|
||||
parent, leaf = os.path.split(os.path.abspath(path))
|
||||
path = os.path.join(os.path.realpath(parent), leaf)
|
||||
if sys.platform.startswith("linux"):
|
||||
encoded = os.fsencode(path)
|
||||
# mountinfo escapes whitespace and backslashes as octal; compare
|
||||
# the escaped path directly. Read errors must not authorize rmtree.
|
||||
encoded = re.sub(rb"[\t\n \\]", lambda m: b"\\%03o" % m[0][0], encoded)
|
||||
with open("/proc/self/mountinfo", "rb") as table:
|
||||
return any(line.split()[4] == encoded for line in table)
|
||||
try:
|
||||
child = os.lstat(path)
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
return child.st_dev != os.stat(parent).st_dev
|
||||
|
||||
|
||||
def unmount_mergerfs(mountpoint):
|
||||
"""Return only after the mount is detached or was confirmed absent."""
|
||||
if not is_mount_point(mountpoint):
|
||||
return
|
||||
um = find_fusermount()
|
||||
if um is None:
|
||||
raise RuntimeError("fusermount3/fusermount not found")
|
||||
for attempt in range(3):
|
||||
u = subprocess.run([um, "-u", mountpoint], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if u.returncode == 0:
|
||||
result = subprocess.run([um, "-u", mountpoint], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if not is_mount_point(mountpoint):
|
||||
return
|
||||
time.sleep(1)
|
||||
subprocess.run([um, "-z", mountpoint], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
result = subprocess.run([um, "-uz", mountpoint], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if not is_mount_point(mountpoint):
|
||||
return
|
||||
stderr = result.stderr.decode("utf-8", errors="replace").strip()
|
||||
raise UnmountError(f"failed to unmount {mountpoint} "
|
||||
f"(fusermount exit {result.returncode}): {stderr}")
|
||||
|
||||
|
||||
@contextmanager
|
||||
|
|
@ -70,6 +101,7 @@ def mergerfs_mount(num_branches=2, options=None):
|
|||
tmp_parent = os.path.join(tests_dir, ".test_tmp")
|
||||
os.makedirs(tmp_parent, exist_ok=True)
|
||||
tmpdir = tempfile.mkdtemp(prefix="mergerfs_test_", dir=tmp_parent)
|
||||
mountpoint = None
|
||||
try:
|
||||
branches = [os.path.join(tmpdir, f"branch{i}") for i in range(num_branches)]
|
||||
for b in branches:
|
||||
|
|
@ -79,11 +111,19 @@ def mergerfs_mount(num_branches=2, options=None):
|
|||
mount_mergerfs(branches, mountpoint, options)
|
||||
yield mountpoint, branches
|
||||
finally:
|
||||
# Never rmtree through an attached or uninspectable mount, even
|
||||
# if the mount command raised after attaching. Preserve the body
|
||||
# exception when cleanup also fails.
|
||||
body_failed = sys.exc_info()[0] is not None
|
||||
try:
|
||||
unmount_mergerfs(mountpoint)
|
||||
except Exception:
|
||||
pass
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
if mountpoint is not None:
|
||||
unmount_mergerfs(mountpoint)
|
||||
except Exception as exc:
|
||||
print(f"fixture preserved at {tmpdir}: {exc}", file=sys.stderr)
|
||||
if not body_failed:
|
||||
raise
|
||||
else:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def temp_dir(root):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue