mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
fix: relocate every handle of a file together, after removing the source
- Relocating only the writer left other opens on the old inode. A later write through one of them could succeed and disappear after close and reopen through the pool. Every handle of a kernel node, including opens made after a rename through mergerfs, now belongs to one group. Prepare a replacement descriptor for each handle and switch the group together. An open of the file while a relocation runs waits and gets the moved file. - Only a node that can be relocated gets a group: one first opened while moveonenospc is enabled and without a kernel passthrough ID, which stays on the original file and can't be switched. Every other node's handles take no lock. Enabling moveonenospc at runtime therefore applies to files opened afterwards. - The switch dup2s each replacement onto the handle's own descriptor number, so a handle's fd never changes while it is open. Operations that change the file hold the group's lock shared and wait for a move. Reads, flush and fsync take no lock and continue on the original, which the copy matches. fgetattr and statx take a second lock, which a move holds only from the source unlink until the switch, so they never report the unlinked original. - A copy is not a committed move. Prepare all bindings first, then remove the source; if that fails keep every handle on the original, clean up the provisional copy when it still denotes this copy, and return only bytes actually written. A handle whose descriptor number is at or above the descriptor limit refuses the move, the only way dup2 could fail after the removal. - The source was removed before its copy reached disk, so a crash could leave the name without its data. fsync the copy and the directories leading to it before removing the source, and the source's directory after, so on a filesystem that can sync them a crash leaves the original or a complete copy and never brings the original back over the copy. A failed sync after the removal is logged; the move has completed by then. fs::copyfile is split into stage and publish steps for this; the staged descriptor pins the copy for preparation and cleanup. - chmod, chown, utimes and xattr changes reach mergerfs by path and don't wait for a move. Compare ctime as well as size and mtime, so a change during the copy makes it retry and one after it refuses the move, rather than being lost with the source. - The kernel can reach one file through more than one node: a hardlink whose other name was removed while both were open, a rename made directly on a branch while the file was open, or overlapping branches. A move cannot switch another node's handles, which would keep writing to the original, so it is refused while any other node has the file open. The mover checks the canonical descriptor of every open node. That check and the descriptor limit run after the cheaper checks, so a full pool doesn't pay for them, and before the copy, so a lasting refusal doesn't cost a copy per write; they run again just before the unlink. An open through another node that races the move's last step is not coordinated with it; moveonenospc.md documents this. - Also refuse to relocate a file with more than one link or an entry in the rename-exdev staging tree. Each handle keeps a valid path after the move. - New shared acquisitions wait while a relocation is pending, so a stream of writes to allocated blocks can't starve the mover. - That wait uses std::atomic wait and notify_all, which libstdc++ first provides in GCC 11, so GCC 11 is now the oldest GCC that builds mergerfs. GCC 10 accepts -std=c++20 and concepts, so install-build-pkgs and run-rpmbuild also probe for the atomic operations: such a compiler is rejected up front, or run-rpmbuild moves on to a newer toolset. build.md names the minimum. - moveonenospc kept its enable bit and policy in two fields, which setxattr changed separately while requests read them. Keep one atomic policy pointer where null means disabled, and read it once per relocation. tests.cpp covers enabling, disabling and an invalid value keeping the previous setting. - The relocation moves out of fuse_write.cpp into moveonenospc.cpp, where one function holds every reason to refuse a move. fs::movefile_and_open no longer opens anything and becomes fs::movefile, which asks the caller's hooks whether to move and to switch its handles. - Document the group behaviour, durability and refusals in moveonenospc.md. - TEST_movefile_enospc covers preexisting, secondary and read-only handles, a hardlinked file, a file open through another node, enabling moveonenospc while a file is open, repeated relocation with a handle opened between moves, steady writers, concurrent relocation, reads and fstat during a copy, a mode change during the copy, and failed source removal with and without a written prefix, checking held handles and close/reopen contents. Its fixtures truncate the filler before unlinking it: a scanner holding the file open kept its space allocated, which made the hardlink case fail intermittently. Performance: a file that can't be relocated, because moveonenospc was disabled when it was first opened or it has a passthrough ID, takes no locks and allocates nothing; writes no longer take the per-handle lock they used to. For a relocatable file, reads, flush and fsync take no lock. Writes and other operations that change the file take the group's lock shared, about two uncontended atomic operations, and fgetattr and statx take the second lock, on its own cache line, the same way. An ENOSPC write takes the lock exclusively only when a move is possible. Opening and closing files adds no syscall; the first open of a relocatable file allocates its group. A relocation adds an fstat per open file to find other nodes of the file. While a file is being relocated, operations that change it and new opens of it wait for the copy, as the writer already did; reads and fstat continue.
This commit is contained in:
parent
93ccc160df
commit
c49989b75f
38 changed files with 2324 additions and 496 deletions
|
|
@ -4,21 +4,26 @@ import contextlib
|
|||
import errno
|
||||
import mmap
|
||||
import os
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from posix_parity import fail
|
||||
from posix_parity import find_fusermount
|
||||
from posix_parity import find_mergerfs
|
||||
from posix_parity import mergerfs_get_option
|
||||
from posix_parity import mergerfs_set_option
|
||||
from posix_parity import mount_mergerfs
|
||||
from posix_parity import unmount_mergerfs
|
||||
|
||||
|
||||
SKIP = 77
|
||||
CHUNK = 64 * 1024
|
||||
PROCESS_TIMEOUT = 15
|
||||
|
||||
|
||||
class Skip(Exception):
|
||||
|
|
@ -30,9 +35,10 @@ class SubcaseSkip(Exception):
|
|||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def enospc_pool(options, extra_tmpfs=()):
|
||||
def enospc_pool(options, extra_tmpfs=(), destination_size=None):
|
||||
"""Mount mergerfs over `source`, the `extra_tmpfs` (name, size)
|
||||
branches and an unconstrained `destination`, in that order.
|
||||
branches and `destination`, in that order. The destination uses the
|
||||
enclosing filesystem unless destination_size requests a private tmpfs.
|
||||
`source` is a 1 MiB tmpfs holding `target` and is full except for
|
||||
one block. `options` is the mount option string, or a function of
|
||||
that block size returning it. Yields (branch paths by name, pool,
|
||||
|
|
@ -47,7 +53,10 @@ def enospc_pool(options, extra_tmpfs=()):
|
|||
mounted_tmpfs = []
|
||||
mounted = False
|
||||
try:
|
||||
for name, size in [("source", "1m")] + list(extra_tmpfs):
|
||||
mounts = [("source", "1m"), *extra_tmpfs]
|
||||
if destination_size is not None:
|
||||
mounts.append(("destination", destination_size))
|
||||
for name, size in mounts:
|
||||
result = subprocess.run(
|
||||
["mount", "-t", "tmpfs", "-o", f"size={size}", "tmpfs", branches[name]],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
|
|
@ -82,21 +91,8 @@ def enospc_pool(options, extra_tmpfs=()):
|
|||
subprocess.run(["umount", "--lazy", path], check=True)
|
||||
|
||||
|
||||
def holders(branches):
|
||||
return [name for name, path in branches.items() if os.path.exists(os.path.join(path, "target"))]
|
||||
|
||||
|
||||
def check_relocated(branches, pool, expected):
|
||||
if holders(branches) != ["destination"]:
|
||||
return fail(f"target on {holders(branches)}, expected only destination")
|
||||
with open(os.path.join(branches["destination"], "target"), "rb") as stream:
|
||||
actual = stream.read()
|
||||
if actual != expected:
|
||||
return fail(f"relocated file corrupted: expected {len(expected)} bytes, got {len(actual)}")
|
||||
with open(os.path.join(pool, "target"), "rb") as stream:
|
||||
if stream.read() != expected:
|
||||
return fail("relocated file differs through the pool")
|
||||
return 0
|
||||
def holders(branches, name="target"):
|
||||
return [branch for branch, path in branches.items() if os.path.exists(os.path.join(path, name))]
|
||||
|
||||
|
||||
def read_file(path):
|
||||
|
|
@ -104,6 +100,157 @@ def read_file(path):
|
|||
return stream.read()
|
||||
|
||||
|
||||
def check_relocated(branches, pool, expected, name="target", branch="destination"):
|
||||
if holders(branches, name) != [branch]:
|
||||
return fail(f"{name} on {holders(branches, name)}, expected only {branch}")
|
||||
actual = read_file(os.path.join(branches[branch], name))
|
||||
if actual != expected:
|
||||
return fail(f"relocated file corrupted: expected {len(expected)} bytes, got {len(actual)}")
|
||||
if read_file(os.path.join(pool, name)) != expected:
|
||||
return fail("relocated file differs through the pool")
|
||||
return 0
|
||||
|
||||
|
||||
def expect_enospc(call):
|
||||
"""Run call, which should fail with ENOSPC. Returns its result if it
|
||||
succeeds instead; any other error propagates."""
|
||||
try:
|
||||
return call()
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOSPC:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def retry_while_enospc(call):
|
||||
"""Run call until it stops failing with ENOSPC and return its result,
|
||||
or None on timeout. For a refusal that ends once another handle's
|
||||
RELEASE arrives: the kernel sends it in the background, so a node can
|
||||
stay open briefly after close returns."""
|
||||
deadline = time.monotonic() + PROCESS_TIMEOUT
|
||||
while True:
|
||||
result = expect_enospc(call)
|
||||
if (result is not None) or (time.monotonic() >= deadline):
|
||||
return result
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def fill_remaining(branch):
|
||||
"""Consume the rest of a fixture branch through its filler file."""
|
||||
stat = os.statvfs(branch)
|
||||
available = stat.f_bavail * stat.f_frsize
|
||||
if available > 16 * 1024 * 1024:
|
||||
raise RuntimeError(f"refusing to fill an unconstrained filesystem: {branch}")
|
||||
if available:
|
||||
with open(os.path.join(branch, "filler"), "ab") as stream:
|
||||
stream.write(b"F" * available)
|
||||
if os.statvfs(branch).f_bavail:
|
||||
raise RuntimeError(f"could not fill {branch} completely")
|
||||
|
||||
|
||||
def free_filler(branch):
|
||||
"""Remove a fixture branch's filler file and release its space."""
|
||||
filler = os.path.join(branch, "filler")
|
||||
# Truncate before unlinking: a scanner or another process holding the
|
||||
# file open would otherwise keep its blocks allocated after unlink.
|
||||
os.truncate(filler, 0)
|
||||
os.unlink(filler)
|
||||
|
||||
|
||||
def prepare_sparse_target(branches, size, allocated=0):
|
||||
"""Replace the fixture with a full branch holding a sparse target."""
|
||||
source = branches["source"]
|
||||
free_filler(source)
|
||||
with open(os.path.join(source, "target"), "r+b") as stream:
|
||||
if allocated:
|
||||
stream.write(b"x" * allocated)
|
||||
stream.truncate(size)
|
||||
fill_remaining(source)
|
||||
|
||||
|
||||
def prepare_large_target(branches, block):
|
||||
"""Replace the fixture with a full branch whose target takes about
|
||||
three quarters of it, so that each copy attempt takes a while.
|
||||
Returns the target's contents."""
|
||||
source = branches["source"]
|
||||
stat = os.statvfs(source)
|
||||
size = (3 * stat.f_blocks * stat.f_frsize // 4) // block * block
|
||||
content = bytes(range(256)) * (size // 256)
|
||||
free_filler(source)
|
||||
with open(os.path.join(source, "target"), "wb") as stream:
|
||||
stream.write(content)
|
||||
fill_remaining(source)
|
||||
return content
|
||||
|
||||
|
||||
def fork_pwrite(fd, data, offset):
|
||||
"""Fork a child that writes data at offset through fd. It exits 0
|
||||
after a full write, 2 after a short one, or with the errno."""
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
written = os.pwrite(fd, data, offset)
|
||||
os._exit(0 if written == len(data) else 2)
|
||||
except OSError as e:
|
||||
os._exit(e.errno or 1)
|
||||
return pid
|
||||
|
||||
|
||||
def wait_for_processes(pids, timeout):
|
||||
"""Reap exited members, returning statuses and still-running pids."""
|
||||
pending = set(pids)
|
||||
statuses = {}
|
||||
deadline = time.monotonic() + timeout
|
||||
while pending:
|
||||
for pid in list(pending):
|
||||
waited, status = os.waitpid(pid, os.WNOHANG)
|
||||
if waited:
|
||||
statuses[pid] = status
|
||||
pending.remove(pid)
|
||||
if not pending:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
return statuses, pending
|
||||
|
||||
|
||||
def kill_and_reap(pids):
|
||||
statuses = {}
|
||||
for pid in pids:
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
for pid in pids:
|
||||
try:
|
||||
_, statuses[pid] = os.waitpid(pid, 0)
|
||||
except ChildProcessError:
|
||||
pass
|
||||
return statuses
|
||||
|
||||
|
||||
def process_succeeded(status):
|
||||
return os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0
|
||||
|
||||
|
||||
def read_with_timeout(fd, count, timeout):
|
||||
data = bytearray()
|
||||
deadline = time.monotonic() + timeout
|
||||
while len(data) < count:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
readable, _, _ = select.select([fd], [], [], remaining)
|
||||
if not readable:
|
||||
return None
|
||||
chunk = os.read(fd, count - len(data))
|
||||
if not chunk:
|
||||
return None
|
||||
data += chunk
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_partial_append():
|
||||
with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=mfs") as (
|
||||
branches, pool, initial,
|
||||
|
|
@ -283,6 +430,738 @@ def test_occupied_destination():
|
|||
return 0
|
||||
|
||||
|
||||
def check_relocation_rebinds_handles(trigger):
|
||||
# Both descriptors are opened before the move. The non-triggering peer,
|
||||
# a read-only peer, and a later open must all follow the relocated inode.
|
||||
options = "minfreespace=0,cache.files=off,func.open=ff,moveonenospc=mfs"
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
fill_remaining(branches["source"])
|
||||
path = os.path.join(pool, "target")
|
||||
fds = [os.open(path, os.O_RDWR), os.open(path, os.O_RDWR),
|
||||
os.open(path, os.O_RDONLY)]
|
||||
other = fds[1 - trigger]
|
||||
grow = b"G" * (2 * block)
|
||||
marker = b"M" * block
|
||||
tail = b"T" * block
|
||||
expected = marker + grow + tail
|
||||
try:
|
||||
written = os.pwrite(fds[trigger], grow, block)
|
||||
if written != len(grow):
|
||||
return fail(f"relocating write returned {written}, expected {len(grow)}")
|
||||
os.fsync(fds[trigger])
|
||||
|
||||
written = os.pwrite(other, marker, 0)
|
||||
if written != len(marker):
|
||||
return fail("peer overwrite was short")
|
||||
os.fsync(other)
|
||||
written = os.pwrite(other, tail, 3 * block)
|
||||
if written != len(tail):
|
||||
return fail("peer extension was short")
|
||||
os.fsync(other)
|
||||
|
||||
for name, fd in (("triggering", fds[trigger]), ("peer", other),
|
||||
("read-only", fds[2])):
|
||||
if os.pread(fd, len(expected), 0) != expected:
|
||||
return fail(f"held {name} handle reads stale data after relocation")
|
||||
late = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
if os.pread(late, len(expected), 0) != expected:
|
||||
return fail("handle opened after relocation reads stale data")
|
||||
finally:
|
||||
os.close(late)
|
||||
finally:
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
return check_relocated(branches, pool, expected)
|
||||
|
||||
|
||||
def test_relocation_rebinds_canonical_handle():
|
||||
# The second handle relocates, so the first (canonical) handle and a
|
||||
# read-only peer must be rebound too.
|
||||
return check_relocation_rebinds_handles(trigger=1)
|
||||
|
||||
|
||||
def test_relocation_rebinds_other_handles():
|
||||
# The canonical handle relocates, so the second writable handle must be
|
||||
# rebound in the opposite direction.
|
||||
return check_relocation_rebinds_handles(trigger=0)
|
||||
|
||||
|
||||
def test_other_node_refuses_relocation():
|
||||
# A rename made directly on a branch leaves the open file's node at
|
||||
# the old name, so opening the new name gives another node. A move
|
||||
# could not switch the first node's handles, which would keep writing
|
||||
# to the original: refuse it while that node has the file open, and
|
||||
# relocate once it is closed.
|
||||
options = ("minfreespace=0,cache.files=off,cache.entry=0,"
|
||||
"inodecalc=path-hash,func.open=ff,moveonenospc=mfs")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
fill_remaining(branches["source"])
|
||||
source = branches["source"]
|
||||
destination = branches["destination"]
|
||||
path = os.path.join(pool, "target")
|
||||
alias = os.path.join(pool, "alias")
|
||||
grow = b"G" * (2 * block)
|
||||
expected = initial + grow
|
||||
|
||||
fd_old = os.open(path, os.O_RDWR)
|
||||
fd_new = None
|
||||
try:
|
||||
os.rename(os.path.join(source, "target"), os.path.join(source, "alias"))
|
||||
fd_new = os.open(alias, os.O_RDWR)
|
||||
|
||||
written = expect_enospc(lambda: os.pwrite(fd_new, grow, block))
|
||||
if written is not None:
|
||||
return fail(f"write with the file open on another node returned {written}, expected ENOSPC")
|
||||
if os.listdir(destination):
|
||||
return fail("refused relocation left a destination copy")
|
||||
if os.pread(fd_old, block, 0) != initial:
|
||||
return fail("the other node's handle changed after the refused relocation")
|
||||
|
||||
os.close(fd_old)
|
||||
fd_old = None
|
||||
written = retry_while_enospc(lambda: os.pwrite(fd_new, grow, block))
|
||||
if written != len(grow):
|
||||
return fail(f"write after the other node closed returned {written}, expected {len(grow)}")
|
||||
os.fsync(fd_new)
|
||||
if os.pread(fd_new, len(expected), 0) != expected:
|
||||
return fail("relocated handle reads stale data")
|
||||
finally:
|
||||
for fd in (fd_old, fd_new):
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
|
||||
return check_relocated(branches, pool, expected, name="alias")
|
||||
|
||||
|
||||
def test_enabling_applies_to_later_opens():
|
||||
# Whether a file can be relocated is decided at its first open. One
|
||||
# opened while moveonenospc is disabled keeps failing after it is
|
||||
# enabled; once every handle is closed, opening it again relocates.
|
||||
options = "minfreespace=0,cache.files=off,func.open=ff,moveonenospc=false"
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
fill_remaining(branches["source"])
|
||||
path = os.path.join(pool, "target")
|
||||
grow = b"G" * (2 * block)
|
||||
|
||||
fd = os.open(path, os.O_RDWR)
|
||||
try:
|
||||
mergerfs_set_option(pool, "moveonenospc", "mfs")
|
||||
written = expect_enospc(lambda: os.pwrite(fd, grow, block))
|
||||
if written is not None:
|
||||
return fail(f"write to a file opened while disabled returned {written}, expected ENOSPC")
|
||||
finally:
|
||||
os.close(fd)
|
||||
if holders(branches) != ["source"]:
|
||||
return fail(f"target on {holders(branches)} before the reopen, expected only source")
|
||||
|
||||
def reopen_and_write():
|
||||
fd = os.open(path, os.O_RDWR)
|
||||
try:
|
||||
return os.pwrite(fd, grow, block)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
written = retry_while_enospc(reopen_and_write)
|
||||
if written != len(grow):
|
||||
return fail(f"relocating write returned {written}, expected {len(grow)}")
|
||||
return check_relocated(branches, pool, initial + grow)
|
||||
|
||||
|
||||
def test_second_relocation_switches_later_opens():
|
||||
# Hold a descriptor across two moves; a second descriptor, opened by
|
||||
# name after the first move, triggers the second. Both filesystems
|
||||
# must be bounded because this case deliberately fills each one.
|
||||
options = ("minfreespace=0,cache.files=off,cache.entry=0,"
|
||||
"func.open=ff,moveonenospc=mfs")
|
||||
with enospc_pool(options, destination_size="2m") as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
source = branches["source"]
|
||||
destination = branches["destination"]
|
||||
target = os.path.join(pool, "target")
|
||||
grow = b"G" * (2 * block)
|
||||
marker = b"M" * block
|
||||
tail = b"T" * block
|
||||
expected1 = initial + grow
|
||||
expected2 = expected1 + marker
|
||||
expected3 = expected2 + tail
|
||||
|
||||
fill_remaining(source)
|
||||
fd_a = os.open(target, os.O_RDWR)
|
||||
try:
|
||||
# First relocation: the source is full and the copy lands on
|
||||
# the destination.
|
||||
written = os.pwrite(fd_a, grow, block)
|
||||
if written != len(grow):
|
||||
return fail(f"first relocating write returned {written}, expected {len(grow)}")
|
||||
os.fsync(fd_a)
|
||||
|
||||
fd_b = os.open(target, os.O_RDWR)
|
||||
try:
|
||||
# Second relocation: the destination is filled, the
|
||||
# source freed, and the write through the later handle
|
||||
# moves the file back.
|
||||
fill_remaining(destination)
|
||||
free_filler(source)
|
||||
|
||||
written = os.pwrite(fd_b, marker, len(expected1))
|
||||
if written != len(marker):
|
||||
return fail(f"second relocating write returned {written}, expected {len(marker)}")
|
||||
os.fsync(fd_b)
|
||||
|
||||
# The first handle must have followed both relocations;
|
||||
# its append lands on the relocated file.
|
||||
written = os.pwrite(fd_a, tail, len(expected2))
|
||||
if written != len(tail):
|
||||
return fail(f"first handle did not follow the relocations ({written})")
|
||||
os.fsync(fd_a)
|
||||
|
||||
for name, fd in (("first", fd_a), ("later", fd_b)):
|
||||
if os.pread(fd, len(expected3), 0) != expected3:
|
||||
return fail(f"{name} handle sees stale bytes after the second relocation")
|
||||
finally:
|
||||
os.close(fd_b)
|
||||
finally:
|
||||
os.close(fd_a)
|
||||
|
||||
return check_relocated(branches, pool, expected3, branch="source")
|
||||
|
||||
|
||||
def test_hardlinked_file_refuses_relocation():
|
||||
# A relocation copies the file and removes the source name. With more
|
||||
# than one link the other names would stay on the original inode and
|
||||
# the names would describe different files afterwards: refuse, keep
|
||||
# the write failing, and stay coherent on the source.
|
||||
options = "minfreespace=0,cache.files=off,func.open=ff,moveonenospc=mfs"
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
source = branches["source"]
|
||||
destination = branches["destination"]
|
||||
target = os.path.join(pool, "target")
|
||||
linked = os.path.join(pool, "linked")
|
||||
os.link(target, linked)
|
||||
fill_remaining(source)
|
||||
|
||||
fds = [os.open(target, os.O_RDWR), os.open(linked, os.O_RDONLY)]
|
||||
try:
|
||||
written = expect_enospc(lambda: os.pwrite(fds[0], b"X" * block, block))
|
||||
if written is not None:
|
||||
return fail(f"linked append returned {written}, expected ENOSPC")
|
||||
|
||||
if os.listdir(destination):
|
||||
return fail("refused relocation left a destination copy")
|
||||
if os.pread(fds[1], len(initial), 0) != initial:
|
||||
return fail("peer link handle changed after refused relocation")
|
||||
|
||||
# No move was made, so freeing space lets the append land on
|
||||
# the still-linked source and stay visible through both names.
|
||||
free_filler(source)
|
||||
written = os.pwrite(fds[0], b"L" * block, block)
|
||||
if written != block:
|
||||
return fail(f"post-refusal append returned {written}, expected {block}")
|
||||
os.fsync(fds[0])
|
||||
expected = initial + b"L" * block
|
||||
if os.pread(fds[1], len(expected), 0) != expected:
|
||||
return fail("peer link handle missed the post-refusal append")
|
||||
finally:
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
|
||||
if os.stat(target).st_nlink != 2:
|
||||
return fail("refused relocation changed the link count")
|
||||
if holders(branches) != ["source"]:
|
||||
return fail(f"linked target on {holders(branches)}, expected only source")
|
||||
if read_file(linked) != expected:
|
||||
return fail("peer name missed the post-refusal append")
|
||||
if read_file(target) != expected:
|
||||
return fail("original name changed after refused relocation")
|
||||
return 0
|
||||
|
||||
|
||||
def test_exdev_staged_entry_refuses_relocation():
|
||||
# Keep a handle across EXDEV rename; open the same inode again by
|
||||
# traversing its actual published target. Neither handle may report
|
||||
# a successful write to an inode the pool can no longer reach.
|
||||
options = ("minfreespace=0,cache.files=off,cache.entry=0,category.create=epff,"
|
||||
"func.open=ff,moveonenospc=mfs,rename-exdev=rel-symlink")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
source = branches["source"]
|
||||
destination = branches["destination"]
|
||||
content = b"S" * block
|
||||
|
||||
# The staged file and its parent exist only on the source branch;
|
||||
# the publish parent exists only on the destination branch. Both
|
||||
# are laid down directly so the pool rename cannot complete
|
||||
# anywhere and must take the EXDEV fallback.
|
||||
os.makedirs(os.path.join(source, "d"))
|
||||
with open(os.path.join(source, "d", "f"), "wb") as stream:
|
||||
stream.write(content)
|
||||
os.makedirs(os.path.join(destination, "elsewhere"))
|
||||
fill_remaining(source)
|
||||
|
||||
published = os.path.join(pool, "elsewhere", "f")
|
||||
old = os.open(os.path.join(pool, "d", "f"), os.O_RDWR)
|
||||
try:
|
||||
os.rename(os.path.join(pool, "d", "f"), published)
|
||||
link = os.path.join(destination, "elsewhere", "f")
|
||||
if not os.path.islink(link):
|
||||
return fail("rename did not publish a replacement symlink")
|
||||
pool_target = os.path.join(os.path.dirname(published), os.readlink(link))
|
||||
fd = os.open(pool_target, os.O_RDWR)
|
||||
try:
|
||||
written = expect_enospc(lambda: os.pwrite(fd, b"X" * block, block))
|
||||
if written is not None:
|
||||
return fail(f"staged append returned {written}, expected ENOSPC")
|
||||
content = b"Y" * block
|
||||
if os.pwrite(old, content, 0) != block:
|
||||
return fail("short overwrite through the original descriptor")
|
||||
os.fsync(old)
|
||||
if os.pread(fd, block, 0) != content:
|
||||
return fail("staged-path handle did not see the original handle's write")
|
||||
finally:
|
||||
os.close(fd)
|
||||
finally:
|
||||
os.close(old)
|
||||
if read_file(published) != content:
|
||||
return fail("acknowledged overwrite lost after close and pool reopen")
|
||||
|
||||
staged = os.path.join(source, ".mergerfs_rename_exdev", "d")
|
||||
staged_name = os.listdir(staged)
|
||||
if len(staged_name) != 1:
|
||||
return fail(f"unexpected staging layout: {staged_name}")
|
||||
if read_file(os.path.join(staged, staged_name[0])) != content:
|
||||
return fail("staged file was modified by the refused relocation")
|
||||
if not os.path.exists(published):
|
||||
return fail("published name no longer resolves after refusal")
|
||||
if os.path.exists(os.path.join(destination, ".mergerfs_rename_exdev")):
|
||||
return fail("refused relocation copied the staged entry")
|
||||
if read_file(os.path.join(source, "target")) != initial:
|
||||
return fail("refused relocation changed the fixture target")
|
||||
return 0
|
||||
|
||||
|
||||
def test_concurrent_relocation():
|
||||
# Several independent handles hit ENOSPC on one sparse file while other
|
||||
# processes churn opens. All writers are bounded and killable on a stall.
|
||||
options = ("minfreespace=0,cache.files=off,parallel-direct-writes=true,"
|
||||
"func.open=ff,moveonenospc=mfs,read-thread-count=8")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
size = 16 * block
|
||||
writers = 4
|
||||
region = size // writers
|
||||
prepare_sparse_target(branches, size)
|
||||
path = os.path.join(pool, "target")
|
||||
churners = []
|
||||
writer_pids = []
|
||||
statuses = {}
|
||||
pending = set()
|
||||
try:
|
||||
for _ in range(2):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
while True:
|
||||
fd = os.open(path, os.O_RDONLY)
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
os._exit(1)
|
||||
churners.append(pid)
|
||||
|
||||
for index in range(writers):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
fd = None
|
||||
try:
|
||||
fd = os.open(path, os.O_WRONLY)
|
||||
chunk = bytes([65 + index]) * block
|
||||
for offset in range(index * region, (index + 1) * region, block):
|
||||
if os.pwrite(fd, chunk, offset) != len(chunk):
|
||||
os._exit(2)
|
||||
os.close(fd)
|
||||
os._exit(0)
|
||||
except OSError:
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
os._exit(1)
|
||||
writer_pids.append(pid)
|
||||
|
||||
statuses, pending = wait_for_processes(writer_pids, PROCESS_TIMEOUT)
|
||||
finally:
|
||||
unreaped = set(writer_pids) - set(statuses)
|
||||
cleaned = kill_and_reap(set(churners) | unreaped)
|
||||
if pending:
|
||||
return fail("concurrent relocating writers stalled")
|
||||
if any(not process_succeeded(status) for status in statuses.values()):
|
||||
return fail("a concurrent relocating writer failed or returned a short write")
|
||||
if any(not os.WIFSIGNALED(cleaned[pid]) for pid in churners):
|
||||
return fail("an open/close worker failed during relocation")
|
||||
|
||||
expected = b"".join(bytes([65 + index]) * region for index in range(writers))
|
||||
return check_relocated(branches, pool, expected)
|
||||
|
||||
|
||||
def test_relocation_not_starved():
|
||||
# Keep overwriting allocated blocks through one shared open description.
|
||||
# A child performs the relocating write and is killed on a watchdog
|
||||
# timeout; there is no throughput or latency target to make loaded hosts
|
||||
# flaky.
|
||||
options = ("minfreespace=0,cache.files=off,parallel-direct-writes=true,"
|
||||
"func.open=ff,moveonenospc=mfs,read-thread-count=16,"
|
||||
"process-thread-count=-1")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
block = len(initial)
|
||||
allocated = 8 * block
|
||||
size = 16 * block
|
||||
marker_offset = 12 * block
|
||||
marker = b"H" * block
|
||||
prepare_sparse_target(branches, size, allocated=allocated)
|
||||
path = os.path.join(pool, "target")
|
||||
fd = os.open(path, os.O_WRONLY)
|
||||
ready_read, ready_write = os.pipe()
|
||||
worker_pids = []
|
||||
mover_pid = None
|
||||
mover_status = None
|
||||
mover_pending = set()
|
||||
error = None
|
||||
try:
|
||||
# Match the 16-32 writer regime which exposed reader-preferring
|
||||
# shared_mutex starvation in the original regression report.
|
||||
for index in range(24):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
os.close(ready_read)
|
||||
chunk = bytes([65 + index]) * (2 * block)
|
||||
offset = (index * block) % (6 * block)
|
||||
ready = False
|
||||
while True:
|
||||
if os.pwrite(fd, chunk, offset) != len(chunk):
|
||||
os._exit(2)
|
||||
if not ready:
|
||||
os.write(ready_write, b"R")
|
||||
ready = True
|
||||
offset = (offset + 3 * block) % (6 * block)
|
||||
except OSError:
|
||||
os._exit(1)
|
||||
worker_pids.append(pid)
|
||||
os.close(ready_write)
|
||||
ready_write = -1
|
||||
|
||||
if read_with_timeout(ready_read, len(worker_pids), PROCESS_TIMEOUT) is None:
|
||||
error = "concurrent overwriters did not become ready"
|
||||
else:
|
||||
mover_pid = fork_pwrite(fd, marker, marker_offset)
|
||||
statuses, mover_pending = wait_for_processes([mover_pid], PROCESS_TIMEOUT)
|
||||
mover_status = statuses.get(mover_pid)
|
||||
if mover_pending:
|
||||
error = "relocating write stalled behind steady writers"
|
||||
elif not process_succeeded(mover_status):
|
||||
error = "relocating write failed behind steady writers"
|
||||
finally:
|
||||
worker_statuses = kill_and_reap(worker_pids)
|
||||
kill_and_reap(mover_pending)
|
||||
if ready_write >= 0:
|
||||
os.close(ready_write)
|
||||
os.close(ready_read)
|
||||
os.close(fd)
|
||||
|
||||
if error:
|
||||
return fail(error)
|
||||
if any(not os.WIFSIGNALED(status) for status in worker_statuses.values()):
|
||||
return fail("a steady overwrite failed before relocation completed")
|
||||
if holders(branches) != ["destination"]:
|
||||
return fail(f"target on {holders(branches)}, expected only destination")
|
||||
destination = os.path.join(branches["destination"], "target")
|
||||
if os.stat(destination).st_size != size:
|
||||
return fail("relocation changed the sparse target's logical size")
|
||||
for relocated in (destination, os.path.join(pool, "target")):
|
||||
with open(relocated, "rb") as stream:
|
||||
stream.seek(marker_offset)
|
||||
if stream.read(len(marker)) != marker:
|
||||
return fail("relocating write data missing after close/reopen")
|
||||
return 0
|
||||
|
||||
|
||||
def test_reads_proceed_during_relocation():
|
||||
# A move holds back operations that change the file for its whole
|
||||
# copy, but reads and fstat through another handle go on against the
|
||||
# original. Changing the source's mtime on the branch makes every
|
||||
# copy attempt retry, so the move stays in progress until stopped.
|
||||
options = ("minfreespace=0,cache.files=off,cache.attr=0,"
|
||||
"func.open=ff,moveonenospc=mfs")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
source = branches["source"]
|
||||
source_target = os.path.join(source, "target")
|
||||
destination = branches["destination"]
|
||||
block = len(initial)
|
||||
# A larger target makes each copy attempt long enough that the
|
||||
# touchers always land inside it.
|
||||
content = prepare_large_target(branches, block)
|
||||
grow = b"G" * (2 * block)
|
||||
expected = content + grow
|
||||
|
||||
path = os.path.join(pool, "target")
|
||||
writer = os.open(path, os.O_RDWR)
|
||||
reader = os.open(path, os.O_RDONLY)
|
||||
result_read, result_write = os.pipe()
|
||||
touchers = []
|
||||
others = []
|
||||
reaped = set()
|
||||
error = None
|
||||
try:
|
||||
for index in range(3):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
ns = index
|
||||
while True:
|
||||
ns += 3
|
||||
try:
|
||||
os.utime(source_target, ns=(ns, ns))
|
||||
except OSError:
|
||||
os._exit(0)
|
||||
touchers.append(pid)
|
||||
|
||||
mover = fork_pwrite(writer, grow, len(content))
|
||||
others.append(mover)
|
||||
|
||||
# A staging file on the destination means the move holds the
|
||||
# group and is copying.
|
||||
deadline = time.monotonic() + PROCESS_TIMEOUT
|
||||
while not os.listdir(destination):
|
||||
if time.monotonic() >= deadline:
|
||||
raise SubcaseSkip("the relocation never started copying")
|
||||
time.sleep(0.001)
|
||||
|
||||
# The result goes through a pipe: the child's exit closes its
|
||||
# inherited descriptors of the file, and the kernel's flush
|
||||
# waits for the in-flight direct write, however reads behave.
|
||||
peek = os.fork()
|
||||
if peek == 0:
|
||||
try:
|
||||
data = os.pread(reader, len(content), 0)
|
||||
st = os.fstat(reader)
|
||||
ok = (data == content and st.st_size == len(content))
|
||||
os.write(result_write, b"0" if ok else b"2")
|
||||
except OSError:
|
||||
os.write(result_write, b"1")
|
||||
os._exit(0)
|
||||
others.append(peek)
|
||||
|
||||
result = read_with_timeout(result_read, 1, PROCESS_TIMEOUT)
|
||||
if result is None:
|
||||
error = "a read or fstat waited for the relocation's copy"
|
||||
elif result != b"0":
|
||||
error = "a read or fstat during the relocation failed or returned wrong data"
|
||||
else:
|
||||
statuses, pending = wait_for_processes([mover], 0)
|
||||
reaped.update(statuses)
|
||||
if not pending:
|
||||
raise SubcaseSkip("the relocation finished before the read could be timed against it")
|
||||
kill_and_reap(touchers)
|
||||
reaped.update(touchers)
|
||||
statuses, pending = wait_for_processes([mover], PROCESS_TIMEOUT)
|
||||
reaped.update(statuses)
|
||||
if pending:
|
||||
error = "the relocation did not finish once the source stopped changing"
|
||||
elif not process_succeeded(statuses[mover]):
|
||||
error = "the relocating write failed"
|
||||
elif os.pread(reader, len(expected), 0) != expected:
|
||||
error = "the reading handle did not follow the relocation"
|
||||
finally:
|
||||
# Stop the touchers first so a held move can finish.
|
||||
kill_and_reap([pid for pid in touchers if pid not in reaped])
|
||||
kill_and_reap([pid for pid in others if pid not in reaped])
|
||||
os.close(result_read)
|
||||
os.close(result_write)
|
||||
os.close(reader)
|
||||
os.close(writer)
|
||||
|
||||
if error:
|
||||
return fail(error)
|
||||
return check_relocated(branches, pool, expected)
|
||||
|
||||
|
||||
def test_metadata_change_during_copy_is_kept():
|
||||
# chmod, chown, utimes and xattr changes reach mergerfs by path, so
|
||||
# they don't wait for a move. One made during the move must not be
|
||||
# lost with the source: while the source's mode keeps changing on the
|
||||
# branch, the move keeps copying or is refused, but never completes.
|
||||
# Once the changes stop, a write relocates and the copy carries the
|
||||
# final mode.
|
||||
options = ("minfreespace=0,cache.files=off,func.open=ff,moveonenospc=mfs")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
source = branches["source"]
|
||||
source_target = os.path.join(source, "target")
|
||||
destination = branches["destination"]
|
||||
block = len(initial)
|
||||
size = len(prepare_large_target(branches, block))
|
||||
grow = b"G" * (2 * block)
|
||||
final_mode = 0o640
|
||||
|
||||
fd = os.open(os.path.join(pool, "target"), os.O_RDWR)
|
||||
changers = []
|
||||
others = []
|
||||
reaped = set()
|
||||
error = None
|
||||
try:
|
||||
for _ in range(3):
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
stopping = []
|
||||
signal.signal(signal.SIGTERM, lambda *_: stopping.append(True))
|
||||
try:
|
||||
mode = 0o600
|
||||
while not stopping:
|
||||
os.chmod(source_target, mode)
|
||||
mode ^= 0o044
|
||||
os.chmod(source_target, final_mode)
|
||||
except OSError:
|
||||
os._exit(3)
|
||||
os._exit(0)
|
||||
changers.append(pid)
|
||||
|
||||
mover = fork_pwrite(fd, grow, size)
|
||||
others.append(mover)
|
||||
|
||||
mover_status = None
|
||||
deadline = time.monotonic() + PROCESS_TIMEOUT
|
||||
while not os.listdir(destination):
|
||||
waited, status = os.waitpid(mover, os.WNOHANG)
|
||||
if waited:
|
||||
mover_status = status
|
||||
reaped.add(mover)
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise SubcaseSkip("the relocation never started copying")
|
||||
time.sleep(0.001)
|
||||
|
||||
if mover_status is None:
|
||||
statuses, pending = wait_for_processes([mover], 0.5)
|
||||
reaped.update(statuses)
|
||||
mover_status = statuses.get(mover)
|
||||
if (mover_status is not None) and process_succeeded(mover_status):
|
||||
error = "the move completed while the source's mode kept changing"
|
||||
else:
|
||||
for pid in changers:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
statuses, pending = wait_for_processes(changers, PROCESS_TIMEOUT)
|
||||
reaped.update(statuses)
|
||||
if pending or not all(process_succeeded(st) for st in statuses.values()):
|
||||
error = "a changer could not apply its final mode"
|
||||
else:
|
||||
if mover_status is None:
|
||||
statuses, pending = wait_for_processes([mover], PROCESS_TIMEOUT)
|
||||
reaped.update(statuses)
|
||||
mover_status = statuses.get(mover)
|
||||
if mover_status is None:
|
||||
error = "the move did not finish once the mode stopped changing"
|
||||
elif not process_succeeded(mover_status):
|
||||
# Refused while the mode was changing: nothing moved,
|
||||
# and a write now relocates.
|
||||
if holders(branches) != ["source"]:
|
||||
error = f"a refused move left target on {holders(branches)}"
|
||||
elif os.pwrite(fd, grow, size) != len(grow):
|
||||
error = "the write after the changes stopped was short"
|
||||
finally:
|
||||
kill_and_reap([pid for pid in changers if pid not in reaped])
|
||||
kill_and_reap([pid for pid in others if pid not in reaped])
|
||||
os.close(fd)
|
||||
|
||||
if error:
|
||||
return fail(error)
|
||||
if holders(branches) != ["destination"]:
|
||||
return fail(f"target on {holders(branches)}, expected only destination")
|
||||
mode = os.stat(os.path.join(destination, "target")).st_mode & 0o777
|
||||
if mode != final_mode:
|
||||
return fail(f"relocated file has mode {mode:o}, expected {final_mode:o}")
|
||||
return 0
|
||||
|
||||
|
||||
def check_failed_source_unlink(cached):
|
||||
# A single-file bind mount makes the source writable but its directory
|
||||
# entry impossible to remove. A failed source removal must acknowledge
|
||||
# no suffix or leave a destination copy, and both handles must stay on
|
||||
# the source.
|
||||
cache_mode = "full" if cached else "off"
|
||||
options = (f"minfreespace=0,cache.files={cache_mode},cache.writeback=false,"
|
||||
"func.open=ff,moveonenospc=mfs")
|
||||
with enospc_pool(options) as (branches, pool, initial):
|
||||
source = os.path.join(branches["source"], "target")
|
||||
destination = branches["destination"]
|
||||
bind = subprocess.run(["mount", "--bind", source, source],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
if bind.returncode:
|
||||
raise SubcaseSkip("single-file bind mount unavailable: " +
|
||||
bind.stderr.decode(errors="replace"))
|
||||
try:
|
||||
if not cached:
|
||||
# The direct case has no space for even a prefix.
|
||||
fill_remaining(branches["source"])
|
||||
path = os.path.join(pool, "target")
|
||||
flags = os.O_RDWR | (os.O_APPEND if cached else 0)
|
||||
fds = [os.open(path, flags), os.open(path, flags)]
|
||||
block = len(initial)
|
||||
payload = b"N" * (2 * block)
|
||||
expected = initial + (payload[:block] if cached else b"")
|
||||
try:
|
||||
if cached:
|
||||
# One block is free, so an ordinary cached O_APPEND write
|
||||
# must report exactly that prefix and none of the suffix.
|
||||
try:
|
||||
written = os.write(fds[0], payload)
|
||||
except OSError as e:
|
||||
return fail("cached append failed instead of returning its prefix: " +
|
||||
e.strerror)
|
||||
if written != block:
|
||||
return fail(f"cached append returned {written}, expected prefix {block}")
|
||||
else:
|
||||
try:
|
||||
written = os.pwrite(fds[0], payload, block)
|
||||
except OSError as e:
|
||||
if e.errno not in (errno.ENOSPC, errno.EBUSY):
|
||||
return fail("failed-unlink append returned an unexpected error: " +
|
||||
e.strerror)
|
||||
else:
|
||||
return fail(f"failed-unlink append acknowledged {written} suffix bytes")
|
||||
|
||||
for index, fd in enumerate(fds):
|
||||
os.fsync(fd)
|
||||
actual = os.pread(fd, len(expected) + len(payload), 0)
|
||||
if actual != expected:
|
||||
return fail(f"held handle {index} changed after failed source removal")
|
||||
if os.listdir(destination):
|
||||
return fail("failed source removal left a destination copy")
|
||||
if read_file(source) != expected:
|
||||
return fail("failed source removal changed the source bytes")
|
||||
finally:
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
|
||||
if os.listdir(destination):
|
||||
return fail("failed source removal left destination data after close")
|
||||
if holders(branches) != ["source"]:
|
||||
return fail(f"target on {holders(branches)}, expected only source")
|
||||
if read_file(path) != expected:
|
||||
return fail("pool close/reopen changed bytes after failed source removal")
|
||||
finally:
|
||||
subprocess.run(["umount", "--lazy", source], check=False,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return 0
|
||||
|
||||
|
||||
def test_failed_source_unlink():
|
||||
return check_failed_source_unlink(cached=False)
|
||||
|
||||
|
||||
def test_cached_append_failed_source_unlink():
|
||||
return check_failed_source_unlink(cached=True)
|
||||
|
||||
|
||||
def test_direct_mmap_flush_reports_error():
|
||||
# Exercise actual shared-mmap writeback through a direct-I/O handle on
|
||||
# kernels which negotiated FUSE_DIRECT_IO_ALLOW_MMAP. Older kernels skip
|
||||
|
|
@ -342,6 +1221,19 @@ TESTS = (test_partial_append,
|
|||
test_mmap_flush_reports_error,
|
||||
test_second_relocation,
|
||||
test_occupied_destination,
|
||||
test_relocation_rebinds_canonical_handle,
|
||||
test_relocation_rebinds_other_handles,
|
||||
test_other_node_refuses_relocation,
|
||||
test_enabling_applies_to_later_opens,
|
||||
test_second_relocation_switches_later_opens,
|
||||
test_hardlinked_file_refuses_relocation,
|
||||
test_exdev_staged_entry_refuses_relocation,
|
||||
test_concurrent_relocation,
|
||||
test_relocation_not_starved,
|
||||
test_reads_proceed_during_relocation,
|
||||
test_metadata_change_during_copy_is_kept,
|
||||
test_failed_source_unlink,
|
||||
test_cached_append_failed_source_unlink,
|
||||
test_direct_mmap_flush_reports_error)
|
||||
|
||||
|
||||
|
|
|
|||
130
tests/tests.cpp
130
tests/tests.cpp
|
|
@ -5,7 +5,8 @@
|
|||
#include "fs_clonepath.hpp"
|
||||
#include "fs_copyfile.hpp"
|
||||
#include "fs_inode.hpp"
|
||||
#include "fs_movefile_and_open.hpp"
|
||||
#include "fs_movefile.hpp"
|
||||
#include "fs_open_fd.hpp"
|
||||
#include "fs_statvfs_cache.hpp"
|
||||
#include "from_string.hpp"
|
||||
#include "fuse_link.hpp"
|
||||
|
|
@ -16,6 +17,7 @@
|
|||
#include "hashset.hpp"
|
||||
#include "num.hpp"
|
||||
#include "policies.hpp"
|
||||
#include "procfs.hpp"
|
||||
#include "rapidhash/rapidhash.h"
|
||||
#include "rnd.hpp"
|
||||
#include "scope_guard/scope_guard.hpp"
|
||||
|
|
@ -70,8 +72,11 @@ test_direct_handle_writepage_error()
|
|||
TEST_ASSERT(::setrlimit(RLIMIT_FSIZE,&limit) == 0);
|
||||
DEFER { ::setrlimit(RLIMIT_FSIZE,&saved); };
|
||||
|
||||
// The handle owns its descriptor; the file keeps its own.
|
||||
const int handle_fd = ::dup(fd);
|
||||
TEST_ASSERT(handle_fd >= 0);
|
||||
Branch branch;
|
||||
FileInfo fi(fd,branch,"file",true);
|
||||
FileInfo fi(handle_fd,branch,"file",true);
|
||||
fuse_req_ctx_t ctx = {};
|
||||
fuse_file_info_t ffi = {};
|
||||
ffi.fh = fi.to_fh();
|
||||
|
|
@ -1445,14 +1450,22 @@ test_config_moveonenospc()
|
|||
{
|
||||
MoveOnENOSPC m(false);
|
||||
|
||||
TEST_CHECK(!m.policy());
|
||||
TEST_CHECK(m.to_string() == "false");
|
||||
TEST_CHECK(m.from_string("mfs") == 0);
|
||||
TEST_CHECK(m.policy());
|
||||
TEST_CHECK(m.to_string() == "mfs");
|
||||
TEST_CHECK(m.from_string("mspmfs") == 0);
|
||||
TEST_CHECK(m.to_string() == "mspmfs");
|
||||
TEST_CHECK(m.from_string("true") == 0);
|
||||
TEST_CHECK(m.to_string() == "pfrd");
|
||||
TEST_CHECK(m.from_string("blah") == -EINVAL);
|
||||
// An invalid value must leave the previous setting in force.
|
||||
TEST_CHECK(m.policy());
|
||||
TEST_CHECK(m.to_string() == "pfrd");
|
||||
TEST_CHECK(m.from_string("false") == 0);
|
||||
TEST_CHECK(!m.policy());
|
||||
TEST_CHECK(m.to_string() == "false");
|
||||
}
|
||||
|
||||
void
|
||||
|
|
@ -4036,6 +4049,61 @@ test_fs_copyfile_source_changes_cleanup_tmpfiles()
|
|||
std::filesystem::remove_all(tmp_dir);
|
||||
}
|
||||
|
||||
// Opens a read-write descriptor of the copy and switches nothing.
|
||||
struct ReopenCopyHooks final : public fs::MoveHooks
|
||||
{
|
||||
int
|
||||
check() final
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
prepare(const int dstfd_,
|
||||
const fs::path &) noexcept final
|
||||
{
|
||||
fd = fs::open_fd(dstfd_,O_RDWR);
|
||||
return ((fd < 0) ? fd : 0);
|
||||
}
|
||||
|
||||
void
|
||||
commit() noexcept final
|
||||
{
|
||||
}
|
||||
|
||||
int fd = -1;
|
||||
};
|
||||
|
||||
// Move the file fd_ describes and return a read-write descriptor of
|
||||
// the copy, or a negative errno.
|
||||
static
|
||||
int
|
||||
_movefile_fd(const Policy::Create &policy_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
const int fd_)
|
||||
{
|
||||
int rv;
|
||||
ReopenCopyHooks hooks;
|
||||
|
||||
// fs::open_fd reopens through /proc/self/fd on Linux.
|
||||
#ifdef __linux__
|
||||
procfs::init();
|
||||
DEFER { procfs::shutdown(); };
|
||||
#endif
|
||||
|
||||
rv = fs::movefile(policy_,branches_,branchpath_,fusepath_,fd_,hooks);
|
||||
if(rv < 0)
|
||||
{
|
||||
if(hooks.fd >= 0)
|
||||
::close(hooks.fd);
|
||||
return rv;
|
||||
}
|
||||
|
||||
return hooks.fd;
|
||||
}
|
||||
|
||||
static
|
||||
std::string
|
||||
_file_contents(const fs::path &path_)
|
||||
|
|
@ -4048,6 +4116,51 @@ _file_contents(const fs::path &path_)
|
|||
return contents.str();
|
||||
}
|
||||
|
||||
void
|
||||
test_fs_movefile_direct_io()
|
||||
{
|
||||
// A disk-backed /tmp and a tmpfs destination exercise the read/write
|
||||
// fallback when the filesystems cannot clone or use copy_file_range.
|
||||
if(::access("/dev/shm",W_OK|X_OK) < 0)
|
||||
return;
|
||||
char src_dir[] = "/tmp/mergerfs-test-direct-XXXXXX";
|
||||
char dst_dir[] = "/dev/shm/mergerfs-test-direct-XXXXXX";
|
||||
if(!TEST_CHECK(::mkdtemp(src_dir) != nullptr))
|
||||
return;
|
||||
DEFER { std::filesystem::remove_all(src_dir); };
|
||||
if(!TEST_CHECK(::mkdtemp(dst_dir) != nullptr))
|
||||
return;
|
||||
DEFER { std::filesystem::remove_all(dst_dir); };
|
||||
|
||||
const fs::path src = fs::path(src_dir) / "file";
|
||||
const fs::path dst = fs::path(dst_dir) / "file";
|
||||
const std::string data = "direct I/O relocation\n";
|
||||
std::ofstream(src,std::ios::binary) << data;
|
||||
const int fd = ::open(src.c_str(),O_RDWR|O_DIRECT);
|
||||
if((fd < 0) && ((errno == EINVAL) || (errno == EOPNOTSUPP)))
|
||||
return;
|
||||
if(!TEST_CHECK(fd >= 0))
|
||||
return;
|
||||
DEFER { ::close(fd); };
|
||||
|
||||
Branches branches;
|
||||
branches.minfreespace = 0;
|
||||
if(!TEST_CHECK(branches.from_string(std::string(src_dir) + ":" + dst_dir) == 0))
|
||||
return;
|
||||
const Policy::Create ff(&Policies::Create::ff);
|
||||
const int moved = ::_movefile_fd(ff,branches,src_dir,"file",fd);
|
||||
if(!TEST_CHECK(moved >= 0))
|
||||
{
|
||||
TEST_MSG("movefile: %d",moved);
|
||||
return;
|
||||
}
|
||||
::close(moved);
|
||||
TEST_CHECK(!std::filesystem::exists(src));
|
||||
TEST_CHECK(_file_contents(dst) == data);
|
||||
const int flags = ::fcntl(fd,F_GETFL);
|
||||
TEST_CHECK((flags >= 0) && (flags & O_DIRECT));
|
||||
}
|
||||
|
||||
// moveonenospc must never pick the branch the file is already on, by
|
||||
// its own path or by another path to the same directory (a bind mount;
|
||||
// a symlink stands in for one here). The copy would be renamed over
|
||||
|
|
@ -4055,7 +4168,7 @@ _file_contents(const fs::path &path_)
|
|||
// create policy runs, so a policy that picks one branch (ff here)
|
||||
// chooses another one rather than nothing.
|
||||
void
|
||||
test_fs_movefile_and_open_same_branch()
|
||||
test_fs_movefile_same_branch()
|
||||
{
|
||||
char tmp_template[] = "/tmp/mergerfs-test-movefile-same-XXXXXX";
|
||||
if(::mkdtemp(tmp_template) == nullptr)
|
||||
|
|
@ -4115,7 +4228,7 @@ test_fs_movefile_and_open_same_branch()
|
|||
ptr->front().path = first_;
|
||||
ptr->back().path = second_;
|
||||
|
||||
return fs::movefile_and_open(ff,ptr,src,"file",fd);
|
||||
return ::_movefile_fd(ff,ptr,src,"file",fd);
|
||||
};
|
||||
|
||||
// Every branch is the source: refused, file left alone.
|
||||
|
|
@ -4158,7 +4271,7 @@ test_fs_movefile_and_open_same_branch()
|
|||
// directory but not the file yet. Given the file's own path they found
|
||||
// nothing, so the write kept failing with ENOSPC.
|
||||
void
|
||||
test_fs_movefile_and_open_existing_path_policies()
|
||||
test_fs_movefile_existing_path_policies()
|
||||
{
|
||||
char tmp_template[] = "/tmp/mergerfs-test-movefile-ep-XXXXXX";
|
||||
if(::mkdtemp(tmp_template) == nullptr)
|
||||
|
|
@ -4216,7 +4329,7 @@ test_fs_movefile_and_open_existing_path_policies()
|
|||
TEST_CHECK(branches.from_string(src.string() + ":" + other.string()) == 0);
|
||||
Branches::Ptr ptr = branches;
|
||||
|
||||
rv = fs::movefile_and_open(policy,ptr,src,relpath,fd);
|
||||
rv = ::_movefile_fd(policy,ptr,src,relpath,fd);
|
||||
TEST_CHECK(rv >= 0);
|
||||
TEST_MSG("policy: %s; path: %s; rv: %d",entry.name,relpath,rv);
|
||||
if(rv >= 0)
|
||||
|
|
@ -5080,8 +5193,9 @@ TEST_LIST =
|
|||
{"fuse_symlink_request_ownership",test_fuse_symlink_request_ownership},
|
||||
{"fs_copyfile_basic",test_fs_copyfile_basic},
|
||||
{"fs_copyfile_source_changes_cleanup_tmpfiles",test_fs_copyfile_source_changes_cleanup_tmpfiles},
|
||||
{"fs_movefile_and_open_same_branch",test_fs_movefile_and_open_same_branch},
|
||||
{"fs_movefile_and_open_existing_path_policies",test_fs_movefile_and_open_existing_path_policies},
|
||||
{"fs_movefile_same_branch",test_fs_movefile_same_branch},
|
||||
{"fs_movefile_direct_io",test_fs_movefile_direct_io},
|
||||
{"fs_movefile_existing_path_policies",test_fs_movefile_existing_path_policies},
|
||||
{"direct_handle_writepage_error",test_direct_handle_writepage_error},
|
||||
{"readdir_factory_rejects_oversized_counts",test_readdir_factory_rejects_oversized_counts},
|
||||
{"statvfs_cache_failure_not_served_as_success",test_statvfs_cache_failure_not_served_as_success},
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue