fix: relocate from the fd's current branch on repeated ENOSPC

- 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 and failed with ENOSPC.
- Find the source branch from the fd at the start of each move, as
  before e216a81a. findonfs now matches inode as well as device, so
  branches on one filesystem are told apart, and tries the stored
  branch first. No match leaves the write's ENOSPC in place.
- Drop destinations that are the source directory, matched by device
  and inode so another path to it counts. The copy was renamed over
  the file and then unlinked, deleting it while the write reported
  success. A first move could already pick the source (EDQUOT with
  free space); finding the real source let later moves do it too.
  With no destination left the write keeps its error.
- TEST_movefile_enospc adds a handle that has to move twice.
  tests.cpp covers a move onto the source branch by its own path
  and by an alias.
This commit is contained in:
Antonio SJ Musumeci 2026-11-18 23:45:00 -05:00
parent 9d12bcf235
commit b934e8bd59
5 changed files with 282 additions and 59 deletions

View file

@ -24,35 +24,44 @@
#include "fs_lstat.hpp"
#include "fs_path.hpp"
#include <string>
static
bool
_is_fd_file(const fs::path &basepath_,
const fs::path &fusepath_,
const struct stat &fdst_)
{
int rv;
struct stat st;
rv = fs::lstat(basepath_ / fusepath_,&st);
if(rv < 0)
return false;
return ((st.st_dev == fdst_.st_dev) &&
(st.st_ino == fdst_.st_ino));
}
static
int
_findonfs(const Branches::Ptr &branches_,
const fs::path &fusepath_,
const int fd_,
std::string *basepath_)
fs::path *basepath_)
{
int rv;
dev_t dev;
struct stat st;
fs::path fullpath;
rv = fs::fstat(fd_,&st);
if(rv < 0)
return rv;
dev = st.st_dev;
if(::_is_fd_file(*basepath_,fusepath_,st))
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(not ::_is_fd_file(branch.path,fusepath_,st))
continue;
*basepath_ = branch.path;
@ -66,9 +75,9 @@ _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_)
{
return ::_findonfs(branches_,fusepath_,fd_,basepath_);
}

View file

@ -19,15 +19,17 @@
#pragma once
#include "branches.hpp"
#include <string>
#include "fs_path.hpp"
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.
int
findonfs(const Branches::Ptr &branches,
const std::string &fusepath,
const fs::path &fusepath,
const int fd,
std::string *basepath);
fs::path *basepath);
}

View file

@ -59,6 +59,37 @@ _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.
static
int
_drop_src_branch(const fs::path &src_branch_,
std::vector<Branch*> *dst_branches_)
{
int rv;
struct stat src_st;
rv = fs::stat(src_branch_,&src_st);
if(rv < 0)
return rv;
std::erase_if(*dst_branches_,
[&](const Branch *branch_)
{
struct stat st;
if(fs::stat(branch_->path,&st) < 0)
return true;
return ((st.st_dev == src_st.st_dev) &&
(st.st_ino == src_st.st_ino));
});
return 0;
}
static
int
_movefile_and_open(const Policy::Create &createFunc_,
@ -77,9 +108,17 @@ _movefile_and_open(const Policy::Create &createFunc_,
fs::path dst_filepath;
std::vector<Branch*> 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);
if(rv < 0)
return rv;
rv = createFunc_(branches_,fusepath_,dst_branch);
if(rv < 0)
return rv;
rv = ::_drop_src_branch(src_branch,&dst_branch);
if(rv < 0)
return rv;
if(dst_branch.empty())

View file

@ -1,5 +1,6 @@
#!/usr/bin/env python3
import contextlib
import os
import shutil
import subprocess
@ -14,24 +15,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 +61,102 @@ 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))
TESTS = (test_partial_append, test_second_relocation)
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="")

View file

@ -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,101 @@ 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'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.
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);
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)))
{
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_)
{
Branches branches;
branches.minfreespace = 0;
TEST_CHECK(branches.from_string(list_) == 0);
Branches::Ptr ptr = branches;
ptr->front().path = first_;
return fs::movefile_and_open(ff,ptr,src,"file",fd);
};
for(const auto &first : {src,alias})
{
rv = move(src.string() + ":" + other.string(),first);
TEST_CHECK(rv == -ENOSPC);
TEST_MSG("first branch: %s; rv: %d",first.c_str(),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"));
}
// 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);
::close(fd);
std::filesystem::remove_all(tmp_dir);
}
void
test_hashset_put_and_size()
{
@ -4372,6 +4468,7 @@ 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},
{"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},