mergerfs/tests/TEST_cfg_link_rename_exdev
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

210 lines
9.3 KiB
Python
Executable file

#!/usr/bin/env python3
import errno
import os
import re
import sys
import uuid
from os.path import join
from posix_parity import cleanup_dir
from posix_parity import fail
from posix_parity import mergerfs_get_option
from posix_parity import mergerfs_mount
from posix_parity import mergerfs_set_option
from posix_parity import touch
SKIP = 77
def get_errno(func):
try:
func()
return 0
except OSError as exc:
return exc.errno
def require_symlink(path, expected, label):
# Inspect the backend: through the pool dst can still be the cached
# regular inode of the source until the kernel revalidates it.
if not os.path.islink(path):
return f"{label}: expected backend symlink fallback"
target = os.readlink(path)
if target != expected:
return f"{label}: target {target!r} != {expected!r}"
return None
def require_rename_relocation(link_path, pool_dst, mount, mode, src_rel, label):
if not os.path.islink(link_path):
return None, f"{label}: expected backend symlink fallback"
target = os.readlink(link_path)
if mode == "rel-symlink":
if os.path.isabs(target):
return None, f"{label}: relative mode returned absolute target {target!r}"
pool_target = os.path.normpath(join(os.path.dirname(pool_dst), target))
else:
pool_target = target
expected_prefix = join(mount, ".mergerfs_rename_exdev") + os.sep
if not pool_target.startswith(expected_prefix):
return None, f"{label}: absolute target {target!r} is outside staging"
mount_prefix = mount.rstrip(os.sep) + os.sep
if not pool_target.startswith(mount_prefix):
return None, f"{label}: target {pool_target!r} escapes the pool"
relocated = os.path.relpath(pool_target, mount)
native = join(".mergerfs_rename_exdev", src_rel)
portable_suffix = join(os.path.dirname(src_rel), ".payload", os.path.basename(src_rel))
portable = re.fullmatch(
re.escape(join(".mergerfs_rename_exdev", ""))
+ r"\.p-[0-9a-f]{16}/" + re.escape(portable_suffix),
relocated,
)
if relocated != native and portable is None:
return None, f"{label}: invalid relocated target {relocated!r}"
expected = (
os.path.relpath(pool_target, os.path.dirname(pool_dst))
if mode == "rel-symlink"
else pool_target
)
if target != expected:
return None, f"{label}: target {target!r} != {expected!r}"
return relocated, None
def require_payload(path, label):
with open(path, "rb") as fp:
if fp.read() != b"src":
return f"{label}: backend payload mismatch"
return None
def setup_paths(branches, mount, rel_base, name, root=False):
src_rel = f"{rel_base}_{name}.src" if root else join(rel_base, f"{name}.src")
dst_rel = join(rel_base, "dst", "nested", name)
src = join(mount, src_rel)
dst = join(mount, dst_rel)
cleanup_dir(join(branches[0], rel_base))
cleanup_dir(join(branches[1], rel_base))
os.makedirs(join(branches[0], rel_base), exist_ok=True)
os.makedirs(join(branches[1], rel_base, "dst", "nested"), exist_ok=True)
touch(join(branches[0], src_rel), b"src")
return src, dst, src_rel, dst_rel
def main():
try:
with mergerfs_mount(
num_branches=2, options="defaults,use_ino,category.create=mfs,minfreespace=0"
) as (mount, branches):
rel_base = f".mergerfs_exdev_test_{os.getpid()}_{uuid.uuid4().hex}"
root_sources = []
if len(branches) < 2:
print("EXDEV fallback test requires at least 2 branches", end="")
return SKIP
branches = branches[:2]
try:
orig_create = mergerfs_get_option(mount, "category.create")
orig_link = mergerfs_get_option(mount, "link-exdev")
orig_rename = mergerfs_get_option(mount, "rename-exdev")
try:
mergerfs_set_option(mount, "category.create", "epmfs")
src, dst, src_rel, _ = setup_paths(branches, mount, rel_base, "link_pass")
mergerfs_set_option(mount, "link-exdev", "passthrough")
err = get_errno(lambda: os.link(src, dst + ".link.pass"))
if err != errno.EXDEV:
return fail(f"link-exdev passthrough expected EXDEV, errno={err}")
for mode in ("rel-symlink", "abs-base-symlink", "abs-pool-symlink"):
src, dst, src_rel, dst_rel = setup_paths(branches, mount, rel_base, f"link_{mode}")
mergerfs_set_option(mount, "link-exdev", mode)
err = get_errno(lambda: os.link(src, dst))
if err != 0:
return fail(f"link-exdev={mode} returned errno={err}")
src_base = join(branches[0], src_rel)
if mode == "rel-symlink":
expected = os.path.relpath(src, os.path.dirname(dst))
elif mode == "abs-base-symlink":
expected = src_base
else:
expected = src
err_msg = require_symlink(join(branches[1], dst_rel), expected, f"link-exdev={mode}")
if err_msg:
return fail(err_msg)
err_msg = require_payload(src_base, f"link-exdev={mode}")
if err_msg:
return fail(err_msg)
if os.path.lexists(join(branches[0], dst_rel)):
return fail(f"link-exdev={mode}: destination unexpectedly created on source branch")
src, dst, _, _ = setup_paths(branches, mount, rel_base, "rename_pass")
mergerfs_set_option(mount, "rename-exdev", "passthrough")
err = get_errno(lambda: os.rename(src, dst))
if err != errno.EXDEV:
return fail(f"rename-exdev passthrough expected EXDEV, errno={err}")
# Run root sources first, before any fallback creates staging.
for root in (True, False):
for mode in ("rel-symlink", "abs-symlink"):
# Each root case must start without a staging directory.
if root:
cleanup_dir(join(branches[0], ".mergerfs_rename_exdev"))
name = f"rename_{mode}_{root}"
if root:
root_sources.append(f"{rel_base}_{name}.src")
src, dst, src_rel, dst_rel = setup_paths(branches, mount, rel_base, name, root=root)
mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(src, dst))
if err != 0:
return fail(f"rename-exdev={mode}, root={root} returned errno={err}")
label = f"rename-exdev={mode}, root={root}"
# The kernel still has the source's inode at dst. Using
# it must not fail (it used to return EIO as the inode
# appeared to change type).
try:
os.lstat(dst)
with open(dst, "rb") as fp:
if fp.read() != b"src":
return fail(f"{label}: pool payload mismatch")
except OSError as exc:
return fail(f"{label}: pool access after rename failed, errno={exc.errno}")
staged_rel, err_msg = require_rename_relocation(
join(branches[1], dst_rel), dst, mount, mode, src_rel, label
)
if err_msg:
return fail(err_msg)
if os.path.lexists(join(branches[0], src_rel)):
return fail(f"{label}: source was not moved")
err_msg = require_payload(join(branches[0], staged_rel), label)
if err_msg:
return fail(err_msg)
finally:
mergerfs_set_option(mount, "category.create", orig_create)
mergerfs_set_option(mount, "link-exdev", orig_link)
mergerfs_set_option(mount, "rename-exdev", orig_rename)
return 0
finally:
for branch in branches:
cleanup_dir(join(branch, rel_base))
for src_rel in root_sources:
if os.path.lexists(join(branch, src_rel)):
os.unlink(join(branch, src_rel))
cleanup_dir(join(branch, ".mergerfs_rename_exdev"))
except RuntimeError as exc:
if str(exc) in ("mergerfs binary not found", "fusermount3/fusermount not found"):
print(str(exc), end="")
return SKIP
return fail(f"EXDEV fallback test failed: {exc}")
except OSError as exc:
return fail(f"EXDEV fallback test failed: {exc}")
if __name__ == "__main__":
raise SystemExit(main())