mergerfs/tests/TEST_rename_exdev_publication
Antonio SJ Musumeci c9854f236f fix: make the rename-exdev fallback safe and transactional
rename-exdev (opt-in; the default is passthrough) moves a source it
cannot rename across branches into a staging tree and publishes a
symlink at the destination. This reworks that fallback so a rename
either completes or leaves both names as they were.

- Staging opens every component relative to a pinned parent with
  O_NOFOLLOW, requires a daemon-owned staging root, and refuses when
  the tree can't be trusted.
- Staged names are taken without replacement and must be free on
  every configured branch, not only those holding the source, so a
  later lookup cannot reach another rename's payload. Over-long names
  are shortened. Fallback renames are serialized.
- Destinations: a compatible existing destination is replaced, kept
  under a temporary name until every branch is published, and
  restored if a later branch fails. A destination on a read-only
  branch, or a no-create one where the link can't be created, is
  refused before anything moves. Temporary and restore names never
  replace an entry, and a restore that fails is reported.
- An ordinary rename (rename-exdev=passthrough) also refuses with
  EXDEV when the destination exists on a read-only branch that does
  not hold the source: that copy could neither be replaced nor
  removed and would shadow the renamed file there. It is never
  scheduled for removal either.
- The replacement symlink is prepared in a daemon-private directory,
  its UID and GID are verified through a pinned descriptor, and it is
  published without replacement, before any source moves. A sticky,
  world-writable destination directory under Linux protected symlinks
  is refused. Each prepared link is tracked by identity for cleanup.
- Symlink sources are recreated with their original text, owner and
  times instead of staged, since staging changes where a relative
  target resolves. Sources of different types on different branches
  are refused. A hidden source that cannot be removed fails the rename.
- libfuse re-parents the kernel's node onto the staged inode, using a
  name allocated before publication, so open handles and cached
  dentries keep working and nothing can fail after the rename commits.
- Without renameat2 (FreeBSD 14.4 and 15.0, or seccomp), regular
  files and directories use a portable layout: a fresh daemon-owned
  wrapper, access gates that mirror the source's parents with the
  source's GID and its read and execute bits only, and the payload
  directory inside the last gate. Foreign-owned parents, unsettable
  group ownership and non-trivial ACLs are refused before the source
  moves. A namespace the source never entered is removed. A portable
  directory that can't be restored stays staged with its path logged,
  and an existing directory destination is refused before a portable
  source moves: keeping it aside would need the no-replace rename the
  portable layout lacks.
- Document the fallback, its refusals and FreeBSD limits.
- TEST_rename_exdev_publication, TEST_rename_exdev_portable and
  tests.cpp cover publication rollback, shadows, collisions,
  ownership, sticky directories, mixed source types, a refused portable
  directory destination and the portable layout through a mounted
  pool. TEST_rename_exdev_publication keeps its fixture if its tmpfs
  can't be detached.

Performance: an ordinary rename only adds an lstat per read-only
branch, and only when one is configured. The fallback adds about two
lstats per branch plus the staging work, and fallback renames run one
at a time.
2026-11-29 23:11:10 -05:00

305 lines
12 KiB
Python
Executable file

#!/usr/bin/env python3
# rename-exdev publication and rollback: a failed publication on a
# later branch must restore the destinations already replaced, and a
# source symlink which can't be removed must fail the rename.
import errno
import os
import shutil
import subprocess
import sys
import tempfile
from os.path import join
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_get_option
from posix_parity import mergerfs_set_option
from posix_parity import mount_mergerfs
from posix_parity import touch
from posix_parity import unmount_mergerfs
SKIP = 77
OPTIONS = ("minfreespace=0,category.create=epmfs,func.symlink=epall,"
"rename-exdev=rel-symlink,cache.entry=0,cache.attr=0,"
"cache.negative_entry=0")
class Skip(Exception):
pass
def read(path):
with open(path, "rb") as fp:
return fp.read()
def rename_errno(src, dst):
try:
os.rename(src, dst)
return 0
except OSError as exc:
return exc.errno
def bind(source, target, readonly=False):
rv = subprocess.run(["mount", "--bind", source, target],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
raise Skip("bind mount unavailable: " + rv.stderr.decode(errors="replace"))
if readonly:
rv = subprocess.run(["mount", "-o", "remount,bind,ro", target],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
raise Skip("read-only bind mount unavailable: " +
rv.stderr.decode(errors="replace"))
def unbind(target):
subprocess.run(["umount", "--lazy", target], check=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def check_regular(path, data, label):
if os.path.islink(path) or not os.path.isfile(path):
return f"{label}: {path} is not a regular file"
if read(path) != data:
return f"{label}: {path} has {read(path)!r}, expected {data!r}"
return None
def check_only(directory, names, label):
entries = sorted(os.listdir(directory))
if entries != sorted(names):
return f"{label}: {directory} has {entries}, expected {sorted(names)}"
return None
def published(branches, pool):
# Control: publication on both destination branches succeeds and
# leaves no temporary names behind.
touch(join(branches[0], "pub", "source"), b"SOURCE")
for i in (1, 2):
touch(join(branches[i], "pubout", "dest"), f"OLD-B{i}".encode())
err = rename_errno(join(pool, "pub", "source"), join(pool, "pubout", "dest"))
if err:
return f"control rename failed: {errno.errorcode.get(err, err)}"
for i in (1, 2):
dest = join(branches[i], "pubout", "dest")
if not os.path.islink(dest):
return f"control: b{i} destination is not the replacement symlink"
msg = check_only(join(branches[i], "pubout"), ["dest"], "control")
if msg:
return msg
# The payload is staged on b0 only. Resolve the link there rather than
# through the pool so the kernel's cached source node doesn't matter.
link = join(branches[1], "pubout", "dest")
payload = os.path.normpath(join(branches[0], "pubout", os.readlink(link)))
if read(payload) != b"SOURCE":
return "control: destination does not reach the payload"
return None
def partial_publication(branches, pool):
touch(join(branches[0], "work", "source"), b"SOURCE")
for i in (1, 2):
touch(join(branches[i], "out", "dest"), f"OLD-B{i}".encode())
# Renaming over a mount point fails with EBUSY, so publication on the
# second branch fails after the first one was replaced.
busy = join(branches[2], "out", "dest")
bind(busy, busy)
try:
err = rename_errno(join(pool, "work", "source"), join(pool, "out", "dest"))
finally:
unbind(busy)
if err != errno.EBUSY:
return f"partial publication returned {errno.errorcode.get(err, err)}, expected EBUSY"
for msg in (check_regular(join(branches[0], "work", "source"), b"SOURCE", "source"),
check_regular(join(branches[1], "out", "dest"), b"OLD-B1", "b1 destination"),
check_regular(join(branches[2], "out", "dest"), b"OLD-B2", "b2 destination"),
check_only(join(branches[1], "out"), ["dest"], "b1"),
check_only(join(branches[2], "out"), ["dest"], "b2")):
if msg:
return msg
return None
def unremovable_symlink_source(branches, pool):
src = join(branches[0], "lnk", "link")
os.makedirs(os.path.dirname(src))
os.symlink("../relative/target", src)
os.makedirs(join(branches[1], "out2"))
srcdir = os.path.dirname(src)
bind(srcdir, srcdir, readonly=True)
try:
err = rename_errno(join(pool, "lnk", "link"), join(pool, "out2", "link"))
finally:
unbind(srcdir)
if err == 0:
return "symlink source rename succeeded although the source can't be removed"
if not os.path.islink(src) or os.readlink(src) != "../relative/target":
return "symlink source changed after a failed rename"
return check_only(join(branches[1], "out2"), [], "symlink destination")
def mixed_source_types(branches, pool):
# epall sees two different objects at one name. Recreating the first
# link is not permission to discard the second branch's regular file.
src = join("mixed", "source")
dst = join("mixed-out", "dest")
os.mkdir(join(branches[0], "mixed"))
os.symlink("link-text", join(branches[0], src))
touch(join(branches[1], src), b"independent bytes")
os.mkdir(join(branches[2], "mixed-out"))
if not rename_errno(join(pool, src), join(pool, dst)):
return "rename of mixed source types succeeded"
if os.readlink(join(pool, src)) != "link-text" or os.path.lexists(join(pool, dst)):
return "refused rename changed the visible names"
msg = check_regular(join(branches[1], src), b"independent bytes", "hidden source")
if msg:
return msg
# The same refusal when the first branch holds the regular file and
# a later one the symlink: staging would move the link one directory
# deeper, where its relative target dangles.
src = join("mixed2", "source")
dst = join("mixed2-out", "dest")
os.mkdir(join(branches[0], "mixed2"))
touch(join(branches[0], src), b"file bytes")
os.mkdir(join(branches[1], "mixed2"))
os.symlink("link-text", join(branches[1], src))
os.mkdir(join(branches[2], "mixed2-out"))
err = rename_errno(join(pool, src), join(pool, dst))
if err != errno.EXDEV:
return (f"file-first rename of mixed source types returned "
f"{errno.errorcode.get(err, err)}, expected EXDEV")
if read(join(pool, src)) != b"file bytes":
return "file-first refusal changed the visible source"
if os.readlink(join(branches[1], src)) != "link-text":
return "file-first refusal changed the hidden symlink"
if os.path.lexists(join(pool, dst)):
return "file-first refusal published a destination"
return None
def cross_branch_staging_collision(branches, pool):
# Recreate the same maximum-length source on a *different* branch.
# The destinations must resolve independently via the pool, not just
# to two intact backing inodes that happen to have the same union name.
src = join("versions", "x" * os.pathconf(branches[0], "PC_NAME_MAX"))
os.mkdir(join(branches[2], "versions-out"))
targets = []
for branch, name, data in zip(branches, ("first", "second"), (b"one", b"two")):
touch(join(branch, src), data)
dst = join("versions-out", name)
os.rename(join(pool, src), join(pool, dst))
target = os.readlink(join(branches[2], dst))
targets.append(os.path.normpath(join(pool, "versions-out", target)))
if targets[0] == targets[1]:
return "both published links use the same staged pool path"
if [read(target) for target in targets] != [b"one", b"two"]:
return "published targets resolve to the wrong generation through the pool"
if [read(join(pool, "versions-out", name)) for name in ("first", "second")] != [b"one", b"two"]:
return "pool destinations no longer read their respective contents"
return None
def destination_shadows(branches, pool):
original = mergerfs_get_option(pool, "branches")
try:
# A logical RO branch on writable media and a truly unremovable
# file on an NC branch both take precedence over the new link.
for case, mode, native in (("fallback-ro", "RO", False),
("ordinary-ro", "RO", True),
("busy-shadow", "NC", False)):
src = join(case + "-in", "src")
dst = join(case + "-out", "dst")
shadow = join(branches[0], dst)
touch(shadow, b"old")
touch(join(branches[1], src), b"new")
os.mkdir(join(branches[1 if native else 2], case + "-out"))
mergerfs_set_option(pool, "branches", ":".join([branches[0] + "=" + mode, *branches[1:]]))
if mode == "NC":
bind(shadow, shadow)
try:
err = rename_errno(join(pool, src), join(pool, dst))
finally:
if mode == "NC":
unbind(shadow)
if err == 0:
return f"{case}: rename acknowledged a shadowed destination"
if read(join(pool, src)) != b"new" or read(join(pool, dst)) != b"old":
return f"{case}: source or destination changed after refusal"
if any(os.path.lexists(join(branch, dst)) for branch in branches[1:]):
return f"{case}: unexpected published destination after refusal"
finally:
mergerfs_set_option(pool, "branches", original)
return None
def isolated():
root = tempfile.mkdtemp(prefix="mergerfs-exdev-publication-")
# A private tmpfs gives every run the same renameat2 and bind support.
rv = subprocess.run(["mount", "-t", "tmpfs", "tmpfs", root],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
shutil.rmtree(root, ignore_errors=True)
print("private tmpfs unavailable", end="")
return SKIP
branches = [join(root, f"b{i}") for i in range(3)]
pool = join(root, "pool")
for path in branches + [pool]:
os.mkdir(path)
try:
mount_mergerfs(branches, pool, OPTIONS)
try:
for case in (published, partial_publication, unremovable_symlink_source,
mixed_source_types, cross_branch_staging_collision, destination_shadows):
msg = case(branches, pool)
if msg:
return fail(f"{case.__name__}: {msg}")
finally:
unmount_mergerfs(pool)
return 0
except Skip as exc:
print(str(exc), end="")
return SKIP
finally:
unbind(root)
if is_mount_point(root):
raise OSError(f"could not detach tmpfs; preserved fixture at {root}")
shutil.rmtree(root)
def main():
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
return isolated()
if find_mergerfs() is None or find_fusermount() is None:
print("mergerfs or fusermount unavailable", end="")
return SKIP
if any(shutil.which(tool) is None for tool in ("unshare", "mount", "umount")):
print("unshare/mount/umount unavailable", end="")
return SKIP
# Bind mounts provide the failures; keep them in a private namespace.
namespace = ["unshare", "-Urm"]
probe = subprocess.run(namespace + ["true"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if probe.returncode:
print("private user/mount namespaces unavailable", end="")
return SKIP
return subprocess.run(namespace + [sys.executable, os.path.realpath(__file__),
"--isolated"]).returncode
if __name__ == "__main__":
raise SystemExit(main())