mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
- When ENOSPC recovery failed after part of a write reached the file (moveonenospc off, no branch to move to, or the move or retry failing), write returned the error and dropped the count although those bytes were on disk. An O_APPEND writer retrying the whole buffer duplicated them. Return the bytes written as a short write, as a local filesystem does; a write that wrote nothing still returns the error. - The kernel flushes its page cache (cache.writeback, dirty mmap pages) with writepage requests, ignores the size in the reply and drops the pages. A short count there lost data while write, fsync, msync and close all succeeded. Use the request's writepage flag, not the handle's cache mode, so cached and direct-I/O handles both return the error for an incomplete flush. - TEST_movefile_enospc covers a short append, writeback and mmap flushes and a direct shared mapping where the kernel allows one. tests.cpp calls the write callback directly so the direct-handle contract is covered on every kernel. Document both in moveonenospc.md.
385 lines
16 KiB
Python
Executable file
385 lines
16 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
import contextlib
|
|
import errno
|
|
import mmap
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
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 mount_mergerfs
|
|
from posix_parity import unmount_mergerfs
|
|
|
|
|
|
SKIP = 77
|
|
CHUNK = 64 * 1024
|
|
|
|
|
|
class Skip(Exception):
|
|
pass
|
|
|
|
|
|
class SubcaseSkip(Exception):
|
|
"""An environmental skip which must not hide the other test cases."""
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def enospc_pool(options, extra_tmpfs=()):
|
|
"""Mount mergerfs over `source`, the `extra_tmpfs` (name, size)
|
|
branches and an unconstrained `destination`, in that order.
|
|
`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,
|
|
target content)."""
|
|
with tempfile.TemporaryDirectory(prefix="mergerfs-enospc-") as root:
|
|
names = ["source"] + [name for name, _ in extra_tmpfs] + ["destination"]
|
|
branches = {name: os.path.join(root, name) for name in names}
|
|
pool = os.path.join(root, "pool")
|
|
for directory in list(branches.values()) + [pool]:
|
|
os.mkdir(directory)
|
|
|
|
mounted_tmpfs = []
|
|
mounted = False
|
|
try:
|
|
for name, size in [("source", "1m")] + list(extra_tmpfs):
|
|
result = subprocess.run(
|
|
["mount", "-t", "tmpfs", "-o", f"size={size}", "tmpfs", branches[name]],
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
)
|
|
if result.returncode:
|
|
raise Skip(f"constrained tmpfs unavailable: {result.stderr.decode(errors='replace')}")
|
|
mounted_tmpfs.append(branches[name])
|
|
|
|
source = branches["source"]
|
|
block_size = os.statvfs(source).f_frsize
|
|
initial = b"initial\n" * (block_size // 8)
|
|
with open(os.path.join(source, "target"), "wb") as stream:
|
|
stream.write(initial)
|
|
|
|
stat = os.statvfs(source)
|
|
remaining = block_size
|
|
available = stat.f_bavail * stat.f_frsize
|
|
with open(os.path.join(source, "filler"), "wb") as stream:
|
|
stream.write(b"F" * (available - remaining))
|
|
|
|
if callable(options):
|
|
options = options(block_size)
|
|
mount_mergerfs([branches[name] for name in names], pool, options)
|
|
mounted = True
|
|
yield branches, pool, initial
|
|
finally:
|
|
if mounted:
|
|
unmount_mergerfs(pool)
|
|
# The daemon may still hold branch fds while it exits after
|
|
# the unmount. Lazy unmount; the namespace dies with us.
|
|
for path in reversed(mounted_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 read_file(path):
|
|
with open(path, "rb") as stream:
|
|
return stream.read()
|
|
|
|
|
|
def test_partial_append():
|
|
with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=mfs") as (
|
|
branches, pool, initial,
|
|
):
|
|
# The first write appends a prefix before ENOSPC. Relocation must
|
|
# preserve that progress instead of replaying it on the new branch.
|
|
block_size = len(initial)
|
|
payload = bytes(range(256)) * (block_size // 64)
|
|
fd = os.open(os.path.join(pool, "target"), os.O_WRONLY | os.O_APPEND)
|
|
try:
|
|
written = os.write(fd, payload)
|
|
finally:
|
|
os.close(fd)
|
|
if written != len(payload):
|
|
return fail(f"append returned {written}, expected {len(payload)}")
|
|
return check_relocated(branches, pool, initial + payload)
|
|
|
|
|
|
def test_partial_without_move():
|
|
with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=false") as (
|
|
branches, pool, initial,
|
|
):
|
|
# Only one block fits. The bytes written before ENOSPC stay on
|
|
# disk, so the write must report them as a short write, not
|
|
# fail: a caller that retries the whole buffer would append
|
|
# them twice.
|
|
block_size = len(initial)
|
|
payload = bytes(range(256)) * (block_size // 64)
|
|
fd = os.open(os.path.join(pool, "target"), os.O_WRONLY | os.O_APPEND)
|
|
try:
|
|
try:
|
|
written = os.write(fd, payload)
|
|
except OSError as e:
|
|
return fail(f"append failed with {e.strerror} after writing a prefix")
|
|
finally:
|
|
os.close(fd)
|
|
if not 0 < written < len(payload):
|
|
return fail(f"append returned {written}, expected a short write")
|
|
with open(os.path.join(branches["source"], "target"), "rb") as stream:
|
|
actual = stream.read()
|
|
if actual != initial + payload[:written]:
|
|
return fail(f"source holds {len(actual)} bytes, expected {len(initial) + written}")
|
|
if holders(branches) != ["source"]:
|
|
return fail(f"target on {holders(branches)}, expected only source")
|
|
return 0
|
|
|
|
|
|
def flush_errors(calls):
|
|
"""Run each (name, function) and return the names that raised ENOSPC."""
|
|
failed = []
|
|
for name, call in calls:
|
|
try:
|
|
call()
|
|
except OSError as e:
|
|
if e.errno != errno.ENOSPC:
|
|
raise
|
|
failed.append(name)
|
|
return failed
|
|
|
|
|
|
def test_writeback_flush_reports_error():
|
|
with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=true,moveonenospc=false") as (
|
|
branches, pool, initial,
|
|
):
|
|
# The kernel flushes its page cache with writes whose reply size
|
|
# it ignores. The tail that doesn't fit is dropped, so the
|
|
# error has to reach fsync or close: a short count would hide it.
|
|
payload = bytes(range(1, 256)) * (len(initial) // 32)
|
|
failed = []
|
|
fd = os.open(os.path.join(pool, "target"), os.O_WRONLY)
|
|
try:
|
|
failed += flush_errors([
|
|
("write", lambda: os.pwrite(fd, payload, len(initial))),
|
|
("fsync", lambda: os.fsync(fd)),
|
|
])
|
|
finally:
|
|
failed += flush_errors([("close", lambda: os.close(fd))])
|
|
if not failed:
|
|
return fail("write, fsync and close all succeeded but the data did not fit")
|
|
return 0
|
|
|
|
|
|
def test_mmap_flush_reports_error():
|
|
with enospc_pool("minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=false") as (
|
|
branches, pool, initial,
|
|
):
|
|
# Dirty shared mmap pages are flushed the same way even without
|
|
# writeback cache, so msync must report the error.
|
|
payload = bytes(range(1, 256)) * (len(initial) // 32)
|
|
total = len(initial) + len(payload)
|
|
failed = []
|
|
fd = os.open(os.path.join(pool, "target"), os.O_RDWR)
|
|
try:
|
|
os.ftruncate(fd, total)
|
|
with mmap.mmap(fd, total) as mapping:
|
|
mapping[len(initial):] = payload
|
|
failed += flush_errors([("msync", mapping.flush), ("fsync", lambda: os.fsync(fd))])
|
|
finally:
|
|
failed += flush_errors([("close", lambda: os.close(fd))])
|
|
if not failed:
|
|
return fail("msync, fsync and close all succeeded but the data did not fit")
|
|
return 0
|
|
|
|
|
|
def test_second_relocation():
|
|
# lfs over branches with at least minfreespace free picks `middle`
|
|
# first; once it fills too only `destination` is left. The same open
|
|
# handle has to move twice. Sizes follow the block size: a chunk
|
|
# must not fit in the block left free on `source`, and the two
|
|
# blocks the first move frees there must stay below minfreespace.
|
|
# With 64K pages fixed 64K values fail both.
|
|
def options(block_size):
|
|
return (f"minfreespace={max(CHUNK, 4 * block_size)},"
|
|
"cache.files=full,cache.writeback=false,moveonenospc=lfs")
|
|
|
|
with enospc_pool(options, extra_tmpfs=[("middle", "512k")]) as (branches, pool, initial):
|
|
chunk_size = max(CHUNK, 2 * len(initial))
|
|
expected = bytearray(initial)
|
|
fd = os.open(os.path.join(pool, "target"), os.O_WRONLY | os.O_APPEND)
|
|
try:
|
|
for i in range(16):
|
|
chunk = bytes([i]) * chunk_size
|
|
try:
|
|
written = os.write(fd, chunk)
|
|
except OSError as e:
|
|
return fail(f"chunk {i} failed with {e.strerror}; target on {holders(branches)}")
|
|
if written != len(chunk):
|
|
return fail(f"chunk {i} returned {written}, expected {len(chunk)}")
|
|
expected += chunk
|
|
if i == 0 and holders(branches) != ["middle"]:
|
|
return fail(f"first relocation put target on {holders(branches)}, expected middle")
|
|
finally:
|
|
os.close(fd)
|
|
return check_relocated(branches, pool, bytes(expected))
|
|
|
|
|
|
def test_occupied_destination():
|
|
options = "minfreespace=0,cache.files=off,func.open=ff,moveonenospc=ff"
|
|
with enospc_pool(options, extra_tmpfs=[("occupied", "1m")]) as (branches, pool, initial):
|
|
occupied = os.path.join(branches["occupied"], "target")
|
|
original = b"independent file\n"
|
|
with open(occupied, "wb") as stream:
|
|
stream.write(original)
|
|
|
|
payload = b"A" * (2 * len(initial))
|
|
fd = os.open(os.path.join(pool, "target"), os.O_RDWR | os.O_APPEND)
|
|
try:
|
|
if os.read(fd, len(initial)) != initial:
|
|
return fail("first-found open did not select the source target")
|
|
# Consume the fixture's last block. The target already ends on
|
|
# a block boundary, so even a short append requires relocation.
|
|
with open(os.path.join(branches["source"], "filler"), "ab") as stream:
|
|
stream.write(initial)
|
|
if os.statvfs(branches["source"]).f_bavail != 0:
|
|
return fail("source still has space before append")
|
|
try:
|
|
written = os.write(fd, payload)
|
|
except OSError as e:
|
|
if e.errno != errno.ENOSPC:
|
|
raise
|
|
else:
|
|
return fail(f"append returned {written}, expected ENOSPC")
|
|
finally:
|
|
os.close(fd)
|
|
# A held handle can mask a change in what the pool name resolves to.
|
|
with open(os.path.join(pool, "target"), "rb") as stream:
|
|
if stream.read() != initial:
|
|
return fail("pool reopen did not return the original source contents")
|
|
with open(os.path.join(branches["source"], "target"), "rb") as stream:
|
|
if stream.read() != initial:
|
|
return fail("refused append changed the source target")
|
|
with open(occupied, "rb") as stream:
|
|
if stream.read() != original:
|
|
return fail("relocation overwrote an independent target")
|
|
if os.listdir(branches["destination"]):
|
|
return fail("refused relocation left a copy on the empty branch")
|
|
return 0
|
|
|
|
|
|
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
|
|
# only this subcase; the callback contract is tested separately.
|
|
options = ("minfreespace=0,cache.files=off,cache.writeback=false,"
|
|
"moveonenospc=false,direct-io-allow-mmap=true")
|
|
with enospc_pool(options) as (branches, pool, initial):
|
|
negotiated = mergerfs_get_option(pool, "direct-io-allow-mmap").strip().lower()
|
|
if negotiated != "true":
|
|
raise SubcaseSkip("kernel did not negotiate direct-I/O shared mmap")
|
|
block = len(initial)
|
|
payload = (bytes(range(1, 256)) * ((2 * block + 254) // 255))[:2 * block]
|
|
total = len(initial) + len(payload)
|
|
failed = []
|
|
fd = os.open(os.path.join(pool, "target"), os.O_RDWR)
|
|
try:
|
|
os.ftruncate(fd, total)
|
|
with mmap.mmap(fd, total, flags=mmap.MAP_SHARED,
|
|
prot=mmap.PROT_READ | mmap.PROT_WRITE) as mapping:
|
|
mapping[len(initial):] = payload
|
|
failed += flush_errors([("msync", mapping.flush),
|
|
("fsync", lambda: os.fsync(fd))])
|
|
finally:
|
|
failed += flush_errors([("close", lambda: os.close(fd))])
|
|
if not failed:
|
|
return fail("direct shared mmap writeback acknowledged data which did not fit")
|
|
|
|
# Only one payload block fits, but writeback order is a kernel choice.
|
|
# Check every byte without assuming that the first payload block won:
|
|
# each position is either still sparse zero or its expected byte, and
|
|
# no more than one of the two payload blocks may contain written data.
|
|
actual = read_file(os.path.join(branches["source"], "target"))
|
|
if len(actual) != total or actual[:block] != initial:
|
|
return fail("direct shared mmap writeback changed the original bytes or file size")
|
|
changed_blocks = 0
|
|
suffix = actual[block:]
|
|
for offset in range(0, len(payload), block):
|
|
actual_chunk = suffix[offset:offset + block]
|
|
expected_chunk = payload[offset:offset + block]
|
|
if any(value not in (0, expected)
|
|
for value, expected in zip(actual_chunk, expected_chunk)):
|
|
return fail("direct shared mmap writeback persisted unexpected bytes")
|
|
if any(actual_chunk):
|
|
changed_blocks += 1
|
|
if changed_blocks > 1:
|
|
return fail("direct shared mmap writeback used more than the one free block")
|
|
if read_file(os.path.join(pool, "target")) != actual:
|
|
return fail("direct shared mmap writeback differs after close/reopen")
|
|
if holders(branches) != ["source"]:
|
|
return fail(f"target on {holders(branches)}, expected only source")
|
|
return 0
|
|
|
|
|
|
TESTS = (test_partial_append,
|
|
test_partial_without_move,
|
|
test_writeback_flush_reports_error,
|
|
test_mmap_flush_reports_error,
|
|
test_second_relocation,
|
|
test_occupied_destination,
|
|
test_direct_mmap_flush_reports_error)
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
|
|
subcase_skips = 0
|
|
for test in TESTS:
|
|
try:
|
|
rv = test()
|
|
except SubcaseSkip as e:
|
|
subcase_skips += 1
|
|
print(f"SKIP {test.__name__}: {e}")
|
|
continue
|
|
except Skip as e:
|
|
print(e, end="")
|
|
return SKIP
|
|
if rv:
|
|
print(f" ({test.__name__})", end="")
|
|
return rv
|
|
if subcase_skips:
|
|
print(f"{subcase_skips} environmental subcase(s) skipped; all others ran")
|
|
return 0
|
|
|
|
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
|
|
|
|
# Limit disk usage inside a private namespace, including for non-root runs.
|
|
namespace = ["unshare", "-Urnm"]
|
|
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())
|