From cd0679b01f537f6c95b8ecbb935e111ce2eea5ed Mon Sep 17 00:00:00 2001 From: "Antonio S. Musumeci" Date: Sun, 22 Nov 2026 01:24:45 -0500 Subject: [PATCH] fix: leave the source branch out before moveonenospc picks a branch - The source branch was dropped from the create policy's result. ff, mfs, lfs, lus and pfrd return a single branch, so when that branch was the source nothing was left and the write kept ENOSPC even with room elsewhere. That happens when the source has free space by statvfs but still returns ENOSPC or EDQUOT: a quota, exhausted inodes, full btrfs metadata, or a cached statfs. - Build the candidate list without the source (matched by device and inode, as before) and run the policy on that, so it picks another branch. With no candidate left the move is still refused. - test_fs_movefile_and_open_same_branch now checks that ff relocates past a source listed first, by its own path or an alias, and that a list made only of the source is refused. Refuse relocation if a duplicate on another branch could become visible when the source is removed. Keep non-replacing publication to protect against a late arrival at the destination. The mounted test checks the original and duplicate contents, then reopens the file through the pool. --- mkdocs/docs/config/moveonenospc.md | 11 ++++- src/fs_copyfile.cpp | 44 ++++++++++++++++- src/fs_copyfile.hpp | 1 + src/fs_movefile_and_open.cpp | 58 +++++++++++++++------- tests/TEST_movefile_enospc | 48 ++++++++++++++++++- tests/tests.cpp | 77 +++++++++++++++++++----------- 6 files changed, 189 insertions(+), 50 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..61581043 100644 --- a/src/fs_copyfile.cpp +++ b/src/fs_copyfile.cpp @@ -33,11 +33,20 @@ #include "fs_rename.hpp" #include "fs_unlink.hpp" #include "fs_xattr.hpp" +#include "to_neg_errno.hpp" #include "scope_guard/scope_guard.hpp" #include #include +#include + +#ifdef __linux__ +#include +#endif +#if defined(__linux__) || defined(__FreeBSD__) +#include +#endif static @@ -57,6 +66,36 @@ _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. + fs::unlink(tmppath_); + return 0; +} + s64 fs::copyfile(const int src_fd_, const struct stat &src_st_, @@ -155,7 +194,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_movefile_and_open.cpp b/src/fs_movefile_and_open.cpp index 29cd8360..7ba3d9e5 100644 --- a/src/fs_movefile_and_open.cpp +++ b/src/fs_movefile_and_open.cpp @@ -27,6 +27,7 @@ #include "fs_findonfs.hpp" #include "fs_getfl.hpp" #include "fs_has_space.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,14 +61,14 @@ _cleanup_flags(const int flags_) return rv; } -// Copying onto the source directory would rename the copy over the -// file and then unlink it. Match by device and inode so another path -// to the same directory, such as a bind mount, is caught too. A -// destination that can't be stat'd is dropped as well. +// A duplicate on any branch could be exposed when the source is unlinked. +// Check even branches that the create policy cannot select. static int -_drop_src_branch(const fs::path &src_branch_, - std::vector *dst_branches_) +_destination_candidates(const fs::path &src_branch_, + const fs::path &fusepath_, + const Branches::Ptr &branches_, + Branches::Ptr *candidates_) { int rv; struct stat src_st; @@ -75,17 +77,32 @@ _drop_src_branch(const fs::path &src_branch_, if(rv < 0) return rv; - std::erase_if(*dst_branches_, - [&](const Branch *branch_) - { - struct stat st; + for(const Branch &branch : *branches_) + { + struct stat st; - if(fs::stat(branch_->path,&st) < 0) - return true; + rv = fs::stat(branch.path.c_str(),&st); + if(rv < 0) + return rv; + if((st.st_dev == src_st.st_dev) && + (st.st_ino == src_st.st_ino)) + continue; - return ((st.st_dev == src_st.st_dev) && - (st.st_ino == src_st.st_ino)); - }); + 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; } @@ -106,6 +123,7 @@ _movefile_and_open(const Policy::Create &createFunc_, 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 @@ -115,10 +133,13 @@ _movefile_and_open(const Policy::Create &createFunc_, if(rv < 0) return rv; - rv = createFunc_(branches_,fusepath_,dst_branch); + rv = ::_destination_candidates(src_branch,fusepath_,branches_,&candidates); if(rv < 0) return rv; - rv = ::_drop_src_branch(src_branch,&dst_branch); + if(!candidates) + return -ENOSPC; + + rv = createFunc_(candidates,fusepath_,dst_branch); if(rv < 0) return rv; if(dst_branch.empty()) @@ -144,7 +165,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 060b10bc..3677de7f 100755 --- a/tests/TEST_movefile_enospc +++ b/tests/TEST_movefile_enospc @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import contextlib +import errno import os import shutil import subprocess @@ -142,7 +143,52 @@ def test_second_relocation(): return check_relocated(branches, pool, bytes(expected)) -TESTS = (test_partial_append, test_second_relocation) +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(): diff --git a/tests/tests.cpp b/tests/tests.cpp index 1356fc13..bb6390f0 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -3681,10 +3681,12 @@ _file_contents(const fs::path &path_) return contents.str(); } -// moveonenospc's create policy can 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, so such a move must be refused. +// 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() { @@ -3712,55 +3714,74 @@ test_fs_movefile_and_open_same_branch() std::filesystem::create_directory(other,ec); if(!ec) std::filesystem::create_directory_symlink(src,alias,ec); - if(!ec) - std::ofstream(src / "file",std::ios::binary) << data; - fd = ::open((src / "file").c_str(),O_RDWR); - if(!TEST_CHECK(!ec && (fd >= 0) && (::fstat(fd,&before) == 0))) + TEST_CHECK(!ec); + if(ec) { - if(fd >= 0) - ::close(fd); std::filesystem::remove_all(tmp_dir); return; } - // ff picks the first branch. Branches resolves symlinks while - // parsing, so the first path is set afterwards. - auto move = [&](const std::string &list_, - const fs::path &first_) + 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(list_) == 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); }; - for(const auto &first : {src,alias}) + // Every branch is the source: refused, file left alone. + if(reset()) { - rv = move(src.string() + ":" + other.string(),first); + rv = move(src,alias); TEST_CHECK(rv == -ENOSPC); - TEST_MSG("first branch: %s; rv: %d",first.c_str(),rv); + 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); - TEST_CHECK(!std::filesystem::exists(other / "file")); + ::close(fd); } - // Control: a different first branch still relocates. - rv = move(other.string() + ":" + src.string(),other); - TEST_CHECK(rv >= 0); - TEST_MSG("rv: %d",rv); - if(rv >= 0) - ::close(rv); - TEST_CHECK(!std::filesystem::exists(src / "file")); - TEST_CHECK(_file_contents(other / "file") == data); + // 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); + } - ::close(fd); std::filesystem::remove_all(tmp_dir); }