From 61597c8dfd50a7ab6048f07a7137748f19b06193 Mon Sep 17 00:00:00 2001 From: Antonio SJ Musumeci Date: Wed, 18 Nov 2026 23:45:00 -0500 Subject: [PATCH] fix: pick the moveonenospc source and destination correctly - moveonenospc copied from the branch stored when the file was opened, which a move never updates, so a second ENOSPC on the same handle tried to copy a path that no longer existed. Find the source branch from the fd's device and inode at the start of each move, trying the stored branch first. No match leaves the write's ENOSPC in place. - The source branch was dropped from the create policy's result, so a policy returning one branch (ff, mfs, lfs, lus, pfrd) left nothing when it picked the source, and a destination that was the source by another path (bind mount) was renamed over the file and unlinked. Remove every alias of the source before the policy runs, so it picks another branch; with no candidate left the move is refused. - Refuse relocation if a duplicate on another branch could become visible once the source is removed, and publish without replacing a destination that appeared meanwhile. When the no-replace rename is unsupported, publish with link(); a staging name that cannot be removed afterwards is logged instead of silently left behind. - Ask the create policy by the parent directory, as create does. The existing-path policies and newest only pick a branch that has the path they are given, and the destination has the directory but not the file yet. - TEST_movefile_enospc moves a handle twice and checks duplicates through the pool. tests.cpp covers the source by its own path and an alias, and every existing-path policy for nested and root files. --- mkdocs/docs/config/moveonenospc.md | 11 +- src/fs_copyfile.cpp | 52 +++++++- src/fs_copyfile.hpp | 1 + src/fs_findonfs.cpp | 31 ++--- src/fs_findonfs.hpp | 11 +- src/fs_is_same_file.hpp | 47 ++++++- src/fs_movefile_and_open.cpp | 81 ++++++++++-- tests/TEST_movefile_enospc | 204 +++++++++++++++++++++++------ tests/tests.cpp | 198 ++++++++++++++++++++++++++++ 9 files changed, 558 insertions(+), 78 deletions(-) diff --git a/mkdocs/docs/config/moveonenospc.md b/mkdocs/docs/config/moveonenospc.md index 154733cf..a1b54d75 100644 --- a/mkdocs/docs/config/moveonenospc.md +++ b/mkdocs/docs/config/moveonenospc.md @@ -20,9 +20,16 @@ situation. When enabled and a `write` fails with `ENOSPC` or `EDQUOT` mergerfs will: -1. Run the policy defined by `moveonenospc` to find a target branch. +1. Check that the file's path is absent on every branch other than the + source and its aliases, including read-only and no-create branches. + If the path already exists (even as a dangling symlink), or a branch + cannot be checked, refuse the move: removing the source could make a + later open find a different file. Otherwise, use the `moveonenospc` + policy to choose a destination from the eligible branches. 2. ["Move"](../faq/technical_behavior_and_limitations.md#how-does-mergerfs-handle-moving-and-copying-of-files) - the file from the source branch to the target branch. + the file from the source branch to the target branch. If another entry + appears at the destination during the copy, the move fails without + overwriting that entry or removing the source. 3. Retry only the unwritten portion of the request, so a partially completed append is not duplicated. diff --git a/src/fs_copyfile.cpp b/src/fs_copyfile.cpp index c8ea3dd8..d5d8a19c 100644 --- a/src/fs_copyfile.cpp +++ b/src/fs_copyfile.cpp @@ -33,11 +33,22 @@ #include "fs_rename.hpp" #include "fs_unlink.hpp" #include "fs_xattr.hpp" +#include "syslog.hpp" +#include "to_neg_errno.hpp" #include "scope_guard/scope_guard.hpp" #include #include +#include +#include + +#ifdef __linux__ +#include +#endif +#if defined(__linux__) || defined(__FreeBSD__) +#include +#endif static @@ -57,6 +68,42 @@ _ignorable_error(const s64 err_) return false; } +static +int +_publish_noreplace(const char *tmppath_, + const char *dstpath_) +{ + int rv; + +#if defined(SYS_renameat2) && defined(RENAME_NOREPLACE) + rv = ::to_neg_errno(::syscall(SYS_renameat2,AT_FDCWD,tmppath_, + AT_FDCWD,dstpath_,RENAME_NOREPLACE)); +#elif defined(__APPLE__) && defined(RENAME_EXCL) + rv = ::to_neg_errno(::renamex_np(tmppath_,dstpath_,RENAME_EXCL)); +#else + rv = -ENOSYS; +#endif + if((rv != -ENOSYS) && (rv != -EINVAL) && + (rv != -ENOTSUP) && (rv != -EOPNOTSUPP)) + return rv; + + // Some filesystems reject the rename flag. The staging file is a + // regular file in the same directory, so link can publish it atomically + // without replacement. Never fall back to a replacing rename. + rv = ::to_neg_errno(::link(tmppath_,dstpath_)); + if(rv < 0) + return rv; + // The destination is now published. A cleanup error cannot undo that, + // but the staged file would be left hidden forever: report it and + // keep the move successful. + rv = fs::unlink(tmppath_); + if(rv < 0) + SysLog::error("failed to unlink staged file {} after publishing {}: {}", + tmppath_,dstpath_,::strerror(-rv)); + + return 0; +} + s64 fs::copyfile(const int src_fd_, const struct stat &src_st_, @@ -155,7 +202,10 @@ fs::copyfile(const int src_fd_, continue; } - rv = fs::rename(dst_tmppath,dst_filepath_); + if(flags_.no_replace) + rv = ::_publish_noreplace(dst_tmppath.c_str(),dst_filepath_.c_str()); + else + rv = fs::rename(dst_tmppath.c_str(),dst_filepath_.c_str()); if((rv < 0) && (flags_.cleanup_failure)) fs::unlink(dst_tmppath); break; diff --git a/src/fs_copyfile.hpp b/src/fs_copyfile.hpp index 5cf25b6a..bbf2b4a1 100644 --- a/src/fs_copyfile.hpp +++ b/src/fs_copyfile.hpp @@ -31,6 +31,7 @@ namespace fs struct CopyFileFlags { int cleanup_failure:1; + bool no_replace:1 = false; }; s64 diff --git a/src/fs_findonfs.cpp b/src/fs_findonfs.cpp index 6f2b0538..6eb7c0bc 100644 --- a/src/fs_findonfs.cpp +++ b/src/fs_findonfs.cpp @@ -21,38 +21,30 @@ #include "branches.hpp" #include "errno.hpp" #include "fs_fstat.hpp" -#include "fs_lstat.hpp" +#include "fs_is_same_file.hpp" #include "fs_path.hpp" -#include - static int _findonfs(const Branches::Ptr &branches_, const fs::path &fusepath_, const int fd_, - std::string *basepath_) + fs::path *basepath_, + struct stat *st_) { int rv; - dev_t dev; - struct stat st; - fs::path fullpath; - rv = fs::fstat(fd_,&st); + rv = fs::fstat(fd_,st_); if(rv < 0) return rv; - dev = st.st_dev; + if(fs::is_same_file(*basepath_ / fusepath_,*st_) == 1) + return 0; + for(const auto &branch : *branches_) { - fullpath = branch.path / fusepath_; - - rv = fs::lstat(fullpath,&st); - if(rv < 0) - continue; - - if(st.st_dev != dev) + if(fs::is_same_file(branch.path / fusepath_,*st_) != 1) continue; *basepath_ = branch.path; @@ -66,9 +58,10 @@ _findonfs(const Branches::Ptr &branches_, int fs::findonfs(const Branches::Ptr &branches_, - const std::string &fusepath_, + const fs::path &fusepath_, const int fd_, - std::string *basepath_) + fs::path *basepath_, + struct stat *fd_st_) { - return ::_findonfs(branches_,fusepath_,fd_,basepath_); + return ::_findonfs(branches_,fusepath_,fd_,basepath_,fd_st_); } diff --git a/src/fs_findonfs.hpp b/src/fs_findonfs.hpp index 56f513da..e4788d54 100644 --- a/src/fs_findonfs.hpp +++ b/src/fs_findonfs.hpp @@ -19,15 +19,20 @@ #pragma once #include "branches.hpp" +#include "fs_path.hpp" -#include +#include namespace fs { + // Find the branch where `fusepath` is the file open as `fd`, trying + // `*basepath` first. Device and inode must both match so branches + // sharing a filesystem are told apart. `*fd_st` receives fd's stat. int findonfs(const Branches::Ptr &branches, - const std::string &fusepath, + const fs::path &fusepath, const int fd, - std::string *basepath); + fs::path *basepath, + struct stat *fd_st); } diff --git a/src/fs_is_same_file.hpp b/src/fs_is_same_file.hpp index 4b3bfb99..57bba8ae 100644 --- a/src/fs_is_same_file.hpp +++ b/src/fs_is_same_file.hpp @@ -18,6 +18,8 @@ #pragma once +#include "fs_lstat.hpp" +#include "fs_path.hpp" #include "to_neg_errno.hpp" #include @@ -28,6 +30,49 @@ namespace fs { + // Whether a and b describe the same object. + static + inline + bool + same_inode(const struct stat &a_, + const struct stat &b_) + { + return ((a_.st_dev == b_.st_dev) && + (a_.st_ino == b_.st_ino)); + } + + // Whether path names the object dev and ino identify, without + // following a final symlink: 1 if it does, 0 if it names another + // object, else lstat's negative errno. The name can change again + // before the caller acts on the answer. + static + inline + int + is_same_file(const fs::path &path_, + const dev_t dev_, + const ino_t ino_) + { + int rv; + struct stat st; + + rv = fs::lstat(path_,&st); + if(rv < 0) + return rv; + + return ((st.st_dev == dev_) && + (st.st_ino == ino_)); + } + + // As above, for the object st describes. + static + inline + int + is_same_file(const fs::path &path_, + const struct stat &st_) + { + return fs::is_same_file(path_,st_.st_dev,st_.st_ino); + } + static inline int @@ -44,7 +89,7 @@ namespace fs if(rv_a < 0 || rv_b < 0) return -errno; - if(st_a.st_dev != st_b.st_dev || st_a.st_ino != st_b.st_ino) + if(!fs::same_inode(st_a,st_b)) return 0; return 1; diff --git a/src/fs_movefile_and_open.cpp b/src/fs_movefile_and_open.cpp index 6f3bc86a..3b350fae 100644 --- a/src/fs_movefile_and_open.cpp +++ b/src/fs_movefile_and_open.cpp @@ -23,10 +23,11 @@ #include "fs_clonepath.hpp" #include "fs_close.hpp" #include "fs_copyfile.hpp" -#include "fs_file_size.hpp" #include "fs_findonfs.hpp" #include "fs_getfl.hpp" #include "fs_has_space.hpp" +#include "fs_is_same_file.hpp" +#include "fs_lstat.hpp" #include "fs_mktemp.hpp" #include "fs_open.hpp" #include "fs_path.hpp" @@ -35,6 +36,7 @@ #include "fs_unlink.hpp" #include "policy.hpp" +#include #include #include @@ -59,6 +61,51 @@ _cleanup_flags(const int flags_) return rv; } +// A duplicate on any branch could be exposed when the source is unlinked. +// Check even branches that the create policy cannot select. +static +int +_destination_candidates(const fs::path &src_branch_, + const fs::path &fusepath_, + const Branches::Ptr &branches_, + Branches::Ptr *candidates_) +{ + int rv; + struct stat src_st; + + rv = fs::stat(src_branch_,&src_st); + if(rv < 0) + return rv; + + for(const Branch &branch : *branches_) + { + struct stat st; + + rv = fs::stat(branch.path.c_str(),&st); + if(rv < 0) + return rv; + if(fs::same_inode(st,src_st)) + continue; + + rv = fs::lstat((branch.path / fusepath_).c_str(),&st); + if(rv == 0) + return -EEXIST; + if(rv != -ENOENT) + return rv; + if(branch.ro_or_nc()) + continue; + + if(!*candidates_) + { + *candidates_ = std::make_shared(&branches_->minfreespace()); + (*candidates_)->reserve(branches_->size()); + } + (*candidates_)->push_back(branch); + } + + return 0; +} + static int _movefile_and_open(const Policy::Create &createFunc_, @@ -70,16 +117,33 @@ _movefile_and_open(const Policy::Create &createFunc_, int rv; int dstfd_flags; int origfd_flags; - s64 src_size; + struct stat st; fs::path fusedir; fs::path src_branch; fs::path src_filepath; fs::path dst_filepath; + Branches::Ptr candidates; std::vector dst_branch; + // `branchpath_` is where the file was opened. An earlier move on the + // same handle leaves the fd on another branch. src_branch = branchpath_; + rv = fs::findonfs(branches_,fusepath_,origfd_,&src_branch,&st); + if(rv < 0) + return rv; - rv = createFunc_(branches_,fusepath_,dst_branch); + rv = ::_destination_candidates(src_branch,fusepath_,branches_,&candidates); + if(rv < 0) + return rv; + if(!candidates) + return -ENOSPC; + + // Ask by the parent directory, as create does. The file isn't on the + // destination yet, and the existing path policies (ep*) only pick a + // branch that already has the path they are given. + fusedir = fusepath_.parent_path(); + + rv = createFunc_(candidates,fusedir,dst_branch); if(rv < 0) return rv; if(dst_branch.empty()) @@ -89,15 +153,9 @@ _movefile_and_open(const Policy::Create &createFunc_, if(origfd_flags < 0) return origfd_flags; - src_size = fs::file_size(origfd_); - if(src_size < 0) - return src_size; - - if(fs::has_space(dst_branch[0]->path,src_size) == false) + if(fs::has_space(dst_branch[0]->path,st.st_size) == false) return -ENOSPC; - fusedir = fusepath_.parent_path(); - rv = fs::clonepath(src_branch,dst_branch[0]->path,fusedir); if(rv < 0) return -ENOSPC; @@ -105,7 +163,8 @@ _movefile_and_open(const Policy::Create &createFunc_, src_filepath = src_branch / fusepath_; dst_filepath = dst_branch[0]->path / fusepath_; - rv = fs::copyfile(src_filepath,dst_filepath,{.cleanup_failure = true}); + rv = fs::copyfile(src_filepath,dst_filepath, + {.cleanup_failure = true, .no_replace = true}); if(rv < 0) return -ENOSPC; diff --git a/tests/TEST_movefile_enospc b/tests/TEST_movefile_enospc index 09269068..3677de7f 100755 --- a/tests/TEST_movefile_enospc +++ b/tests/TEST_movefile_enospc @@ -1,5 +1,7 @@ #!/usr/bin/env python3 +import contextlib +import errno import os import shutil import subprocess @@ -14,24 +16,41 @@ from posix_parity import unmount_mergerfs SKIP = 77 +CHUNK = 64 * 1024 -def test_partial_append(): +class Skip(Exception): + pass + + +@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: - source, destination, pool = [os.path.join(root, name) for name in ("source", "destination", "pool")] - for directory in (source, destination, pool): + 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) - result = subprocess.run( - ["mount", "-t", "tmpfs", "-o", "size=1m", "tmpfs", source], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - ) - if result.returncode: - print(f"constrained tmpfs unavailable: {result.stderr.decode(errors='replace')}", end="") - return SKIP - + 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: @@ -43,44 +62,147 @@ def test_partial_append(): with open(os.path.join(source, "filler"), "wb") as stream: stream.write(b"F" * (available - remaining)) - mount_mergerfs( - [source, destination], pool, - "minfreespace=0,cache.files=full,cache.writeback=false,moveonenospc=mfs", - ) + if callable(options): + options = options(block_size) + mount_mergerfs([branches[name] for name in names], pool, options) mounted = True - - # The first write appends a prefix before ENOSPC. Relocation must - # preserve that progress instead of replaying it on the new branch. - 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)}") - - relocated = os.path.join(destination, "target") - if os.path.exists(os.path.join(source, "target")) or not os.path.isfile(relocated): - return fail("ENOSPC append did not relocate the file") - with open(relocated, "rb") as stream: - actual = stream.read() - expected = initial + payload - if actual != expected: - return fail(f"relocated append corrupted data: expected {len(expected)} bytes, got {len(actual)}") - with open(os.path.join(pool, "target"), "rb") as stream: - if stream.read() != expected: - return fail("relocated append differs through the pool") - return 0 + yield branches, pool, initial finally: if mounted: unmount_mergerfs(pool) - subprocess.run(["umount", source], check=True) + # 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 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_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 + + +TESTS = (test_partial_append, + test_second_relocation, + test_occupied_destination) def main(): if len(sys.argv) == 2 and sys.argv[1] == "--isolated": - return test_partial_append() + for test in TESTS: + try: + rv = test() + except Skip as e: + print(e, end="") + return SKIP + if rv: + print(f" ({test.__name__})", end="") + return rv + return 0 if find_mergerfs() is None or find_fusermount() is None: print("mergerfs or fusermount unavailable", end="") diff --git a/tests/tests.cpp b/tests/tests.cpp index 4739ff6d..a4cbb84e 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -4,6 +4,7 @@ #include "fs_clonepath.hpp" #include "fs_copyfile.hpp" #include "fs_inode.hpp" +#include "fs_movefile_and_open.hpp" #include "from_string.hpp" #include "fuse_link.hpp" #include "fuse_rename.hpp" @@ -3666,6 +3667,201 @@ test_fs_copyfile_source_changes_cleanup_tmpfiles() std::filesystem::remove_all(tmp_dir); } +static +std::string +_file_contents(const fs::path &path_) +{ + std::ifstream stream(path_,std::ios::binary); + std::ostringstream contents; + + contents << stream.rdbuf(); + + return contents.str(); +} + +// 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 +// the file and then unlinked. Such branches are removed before the +// 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() +{ + char tmp_template[] = "/tmp/mergerfs-test-movefile-same-XXXXXX"; + if(::mkdtemp(tmp_template) == nullptr) + { + TEST_CHECK(false); + return; + } + + const fs::path tmp_dir = tmp_template; + const fs::path src = tmp_dir / "src"; + const fs::path alias = tmp_dir / "alias"; + const fs::path other = tmp_dir / "other"; + const std::string data = "moveonenospc same branch\n"; + const Policy::Create ff(&Policies::Create::ff); + std::error_code ec; + struct stat before; + struct stat after; + int fd; + int rv; + + std::filesystem::create_directory(src,ec); + if(!ec) + std::filesystem::create_directory(other,ec); + if(!ec) + std::filesystem::create_directory_symlink(src,alias,ec); + TEST_CHECK(!ec); + if(ec) + { + std::filesystem::remove_all(tmp_dir); + return; + } + + auto reset = [&]() + { + std::filesystem::remove(other / "file",ec); + std::ofstream(src / "file",std::ios::binary|std::ios::trunc) << data; + fd = ::open((src / "file").c_str(),O_RDWR); + if(!TEST_CHECK(fd >= 0)) + return false; + if(!TEST_CHECK(::fstat(fd,&before) == 0)) + { + ::close(fd); + return false; + } + return true; + }; + + // Branches resolves symlinks while parsing, so the paths are set + // afterwards. + auto move = [&](const fs::path &first_, + const fs::path &second_) + { + Branches branches; + branches.minfreespace = 0; + TEST_CHECK(branches.from_string(src.string() + ":" + other.string()) == 0); + Branches::Ptr ptr = branches; + ptr->front().path = first_; + ptr->back().path = second_; + + return fs::movefile_and_open(ff,ptr,src,"file",fd); + }; + + // Every branch is the source: refused, file left alone. + if(reset()) + { + rv = move(src,alias); + TEST_CHECK(rv == -ENOSPC); + TEST_MSG("rv: %d",rv); + if(rv >= 0) + ::close(rv); + + if(TEST_CHECK(::stat((src / "file").c_str(),&after) == 0)) + TEST_CHECK(after.st_ino == before.st_ino); + TEST_CHECK(_file_contents(src / "file") == data); + ::close(fd); + } + + // ff would pick the source listed first; it picks `other` instead. + for(const auto &first : {src,alias,other}) + { + if(!reset()) + break; + + rv = move(first,((first == other) ? src : other)); + TEST_CHECK(rv >= 0); + TEST_MSG("first branch: %s; rv: %d",first.c_str(),rv); + if(rv >= 0) + ::close(rv); + TEST_CHECK(!std::filesystem::exists(src / "file")); + TEST_CHECK(_file_contents(other / "file") == data); + ::close(fd); + } + + std::filesystem::remove_all(tmp_dir); +} + +// The create policy is asked where the file goes, as create does, by +// its parent directory. The existing path policies (ep*) only choose a +// branch that already has the path, and the destination has the +// 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() +{ + char tmp_template[] = "/tmp/mergerfs-test-movefile-ep-XXXXXX"; + if(::mkdtemp(tmp_template) == nullptr) + { + TEST_CHECK(false); + return; + } + + const fs::path tmp_dir = tmp_template; + const fs::path src = tmp_dir / "src"; + const fs::path other = tmp_dir / "other"; + const std::string data = "moveonenospc existing path policy\n"; + const struct + { + const char *name; + Policy::CreateImpl *policy; + } policies[] = { + {"epall",&Policies::Create::epall}, + {"epff",&Policies::Create::epff}, + {"eplfs",&Policies::Create::eplfs}, + {"eplus",&Policies::Create::eplus}, + {"epmfs",&Policies::Create::epmfs}, + {"eppfrd",&Policies::Create::eppfrd}, + {"eprand",&Policies::Create::eprand}, + {"newest",&Policies::Create::newest}, + }; + std::error_code ec; + + std::filesystem::create_directories(src / "dir",ec); + TEST_CHECK(!ec); + if(ec) + { + std::filesystem::remove_all(tmp_dir); + return; + } + + // A file in a directory, and one at the root, whose parent is empty. + for(const char *relpath : {"dir/file","rootfile"}) + for(const auto &entry : policies) + { + int fd; + int rv; + Branches branches; + const Policy::Create policy(entry.policy); + + std::filesystem::remove_all(other,ec); + std::filesystem::create_directories(other / "dir",ec); + std::ofstream(src / relpath,std::ios::binary|std::ios::trunc) << data; + fd = ::open((src / relpath).c_str(),O_RDWR); + TEST_CHECK(fd >= 0); + if(fd < 0) + continue; + + branches.minfreespace = 0; + TEST_CHECK(branches.from_string(src.string() + ":" + other.string()) == 0); + Branches::Ptr ptr = branches; + + rv = fs::movefile_and_open(policy,ptr,src,relpath,fd); + TEST_CHECK(rv >= 0); + TEST_MSG("policy: %s; path: %s; rv: %d",entry.name,relpath,rv); + if(rv >= 0) + ::close(rv); + + TEST_CHECK(!std::filesystem::exists(src / relpath)); + TEST_CHECK(_file_contents(other / relpath) == data); + TEST_MSG("policy: %s; path: %s",entry.name,relpath); + ::close(fd); + } + + std::filesystem::remove_all(tmp_dir); +} + void test_hashset_put_and_size() { @@ -4410,6 +4606,8 @@ 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}, {"str_eq_nullptr",test_str_eq_nullptr}, {"str_startswith_char_nullptr",test_str_startswith_char_nullptr}, {"str_from_u64_suffixes",test_str_from_u64_suffixes},