#!/usr/bin/env python3 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): pass class SubcaseSkip(Exception): """An environmental skip which must not hide the other test cases.""" @contextlib.contextmanager def enospc_pool(options, extra_tmpfs=(), destination_size=None): """Mount mergerfs over `source`, the `extra_tmpfs` (name, size) 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, 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: 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, ) 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, name="target"): return [branch for branch, path in branches.items() if os.path.exists(os.path.join(path, name))] def read_file(path): with open(path, "rb") as stream: 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, ): # 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 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 # 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_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) 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())