mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
fix: relocate every handle of a file together, after removing the source
- Relocating only the writer left other opens on the old inode. A later write through one of them could succeed and disappear after close and reopen through the pool. Every handle of a kernel node, including opens made after a rename through mergerfs, now belongs to one group. Prepare a replacement descriptor for each handle and switch the group together. An open of the file while a relocation runs waits and gets the moved file. - Only a node that can be relocated gets a group: one first opened while moveonenospc is enabled and without a kernel passthrough ID, which stays on the original file and can't be switched. Every other node's handles take no lock. Enabling moveonenospc at runtime therefore applies to files opened afterwards. - The switch dup2s each replacement onto the handle's own descriptor number, so a handle's fd never changes while it is open. Operations that change the file hold the group's lock shared and wait for a move. Reads, flush and fsync take no lock and continue on the original, which the copy matches. fgetattr and statx take a second lock, which a move holds only from the source unlink until the switch, so they never report the unlinked original. - A copy is not a committed move. Prepare all bindings first, then remove the source; if that fails keep every handle on the original, clean up the provisional copy when it still denotes this copy, and return only bytes actually written. A handle whose descriptor number is at or above the descriptor limit refuses the move, the only way dup2 could fail after the removal. - The source was removed before its copy reached disk, so a crash could leave the name without its data. fsync the copy and the directories leading to it before removing the source, and the source's directory after, so on a filesystem that can sync them a crash leaves the original or a complete copy and never brings the original back over the copy. A failed sync after the removal is logged; the move has completed by then. fs::copyfile is split into stage and publish steps for this; the staged descriptor pins the copy for preparation and cleanup. - chmod, chown, utimes and xattr changes reach mergerfs by path and don't wait for a move. Compare ctime as well as size and mtime, so a change during the copy makes it retry and one after it refuses the move, rather than being lost with the source. - The kernel can reach one file through more than one node: a hardlink whose other name was removed while both were open, a rename made directly on a branch while the file was open, or overlapping branches. A move cannot switch another node's handles, which would keep writing to the original, so it is refused while any other node has the file open. The mover checks the canonical descriptor of every open node. That check and the descriptor limit run after the cheaper checks, so a full pool doesn't pay for them, and before the copy, so a lasting refusal doesn't cost a copy per write; they run again just before the unlink. An open through another node that races the move's last step is not coordinated with it; moveonenospc.md documents this. - Also refuse to relocate a file with more than one link or an entry in the rename-exdev staging tree. Each handle keeps a valid path after the move. - New shared acquisitions wait while a relocation is pending, so a stream of writes to allocated blocks can't starve the mover. - That wait uses std::atomic wait and notify_all, which libstdc++ first provides in GCC 11, so GCC 11 is now the oldest GCC that builds mergerfs. GCC 10 accepts -std=c++20 and concepts, so install-build-pkgs and run-rpmbuild also probe for the atomic operations: such a compiler is rejected up front, or run-rpmbuild moves on to a newer toolset. build.md names the minimum. - moveonenospc kept its enable bit and policy in two fields, which setxattr changed separately while requests read them. Keep one atomic policy pointer where null means disabled, and read it once per relocation. tests.cpp covers enabling, disabling and an invalid value keeping the previous setting. - The relocation moves out of fuse_write.cpp into moveonenospc.cpp, where one function holds every reason to refuse a move. fs::movefile_and_open no longer opens anything and becomes fs::movefile, which asks the caller's hooks whether to move and to switch its handles. - Document the group behaviour, durability and refusals in moveonenospc.md. - TEST_movefile_enospc covers preexisting, secondary and read-only handles, a hardlinked file, a file open through another node, enabling moveonenospc while a file is open, repeated relocation with a handle opened between moves, steady writers, concurrent relocation, reads and fstat during a copy, a mode change during the copy, and failed source removal with and without a written prefix, checking held handles and close/reopen contents. Its fixtures truncate the filler before unlinking it: a scanner holding the file open kept its space allocated, which made the hardlink case fail intermittently. Performance: a file that can't be relocated, because moveonenospc was disabled when it was first opened or it has a passthrough ID, takes no locks and allocates nothing; writes no longer take the per-handle lock they used to. For a relocatable file, reads, flush and fsync take no lock. Writes and other operations that change the file take the group's lock shared, about two uncontended atomic operations, and fgetattr and statx take the second lock, on its own cache line, the same way. An ENOSPC write takes the lock exclusively only when a move is possible. Opening and closing files adds no syscall; the first open of a relocatable file allocates its group. A relocation adds an fstat per open file to find other nodes of the file. While a file is being relocated, operations that change it and new opens of it wait for the copy, as the writer already did; reads and fstat continue.
This commit is contained in:
parent
93ccc160df
commit
c49989b75f
38 changed files with 2324 additions and 496 deletions
|
|
@ -73,7 +73,11 @@ check_cxx20()
|
|||
test_src="$test_dir/check.cpp"
|
||||
test_bin="$test_dir/check"
|
||||
|
||||
# Accepting -std=c++20 is not enough: src/rwlock.hpp needs C++20
|
||||
# atomic waiting, which GCC 10 lacks.
|
||||
cat > "$test_src" <<'EOF'
|
||||
#include <atomic>
|
||||
|
||||
template <typename T>
|
||||
concept Incrementable = requires(T value) { value + 1; };
|
||||
|
||||
|
|
@ -81,6 +85,11 @@ static_assert(Incrementable<int>);
|
|||
|
||||
int main()
|
||||
{
|
||||
std::atomic<int> value{0};
|
||||
|
||||
value.notify_all();
|
||||
value.wait(1);
|
||||
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
|
|
|
|||
|
|
@ -20,9 +20,13 @@ if [ $# -lt 1 ]; then
|
|||
exit 1
|
||||
fi
|
||||
|
||||
# Accepting -std=c++20 is not enough: src/rwlock.hpp needs C++20 atomic
|
||||
# waiting, which GCC 10 lacks.
|
||||
cxx20_ok()
|
||||
{
|
||||
printf 'int main(){return 0;}\n' | \
|
||||
printf '%s\n' \
|
||||
'#include <atomic>' \
|
||||
'int main(){std::atomic<int> v{0}; v.notify_all(); v.wait(1); return 0;}' | \
|
||||
"${CXX:-g++}" -std=c++20 -x c++ -fsyntax-only - >/dev/null 2>&1
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,18 +29,74 @@ will:
|
|||
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. If another entry
|
||||
appears at the destination during the copy, the move fails without
|
||||
overwriting that entry or removing the source.
|
||||
overwriting that entry or removing the source. The copy, its name and
|
||||
any directories created for it are flushed to disk before the source
|
||||
is removed, and the removal is flushed too. On a filesystem that can
|
||||
sync files and directories, a crash therefore leaves either the
|
||||
original or a complete copy; a removal that could not be synced is
|
||||
logged. Before source removal, mergerfs opens the destination
|
||||
separately for every open handle with that handle's access flags.
|
||||
Writes and other changes made through an open handle (truncation,
|
||||
allocation, `ioctl`) and new opens of the file wait while the move is
|
||||
prepared. Reads and `fsync` continue against the original, which the
|
||||
copy matches, until each handle switches. Changes made by path, which
|
||||
is how the kernel sends `chmod`, `chown`, `utimes` and xattr changes
|
||||
even for an open file, do not wait: if one reaches the original after
|
||||
it was copied, the move is refused and the write keeps its error.
|
||||
Once the original name has been removed successfully, every handle
|
||||
switches to the new copy together.
|
||||
Every handle opened through the file's name, including opens made
|
||||
after a rename through mergerfs, is switched together, and an open of
|
||||
the file while a move is in flight waits and gets the moved file.
|
||||
After the move each handle adopts the path the relocation used, so a
|
||||
later move can be triggered by any of them. A handle whose own
|
||||
recorded path no longer resolves to the file on any branch cannot
|
||||
itself trigger a relocation; its write keeps the original error
|
||||
until another handle of the file relocates it.
|
||||
3. Retry only the unwritten portion of the request, so a partially
|
||||
completed append is not duplicated.
|
||||
|
||||
If at any point something fails the progress so far will be cleaned up
|
||||
as appropriate and the original error returned. If part of the write
|
||||
already reached the file the bytes written are returned instead, as a
|
||||
short write, as with a local filesystem. The exception is data the
|
||||
kernel is flushing from its page cache (`cache.writeback` or dirty
|
||||
`mmap` pages), including writeback on a direct-I/O handle. The kernel
|
||||
cannot act on a short write for those pages, so the error is returned
|
||||
and reaches `fsync`, `msync` or `close`.
|
||||
If at any point something fails the provisional destination will be
|
||||
cleaned up, provided it still identifies the object created by this move.
|
||||
The original error is returned and every handle remains on the original.
|
||||
In particular, failure to remove the source name does not switch even the
|
||||
writing handle and does not acknowledge the unwritten suffix. If part of
|
||||
the write already reached the file the bytes written are returned
|
||||
instead, as a short write, as with a local filesystem. The exception is
|
||||
data the kernel is flushing from its page cache (`cache.writeback` or
|
||||
dirty `mmap` pages), including writeback on a direct-I/O handle. The
|
||||
kernel cannot act on a short write for those pages, so the error is
|
||||
returned and reaches `fsync`, `msync` or `close`.
|
||||
|
||||
A file is never relocated when it has more than one link: a copy plus
|
||||
source removal would leave the other names on the original inode, so the
|
||||
names would describe different files afterwards. The move is also
|
||||
refused while the file is open through another name, which the kernel
|
||||
treats as another file: a hardlink whose other name was removed while
|
||||
both were open, a rename made directly on a branch while the file was
|
||||
open, or branches that reach the same file by two paths. Those handles
|
||||
could not be switched and would keep writing to the original. An open
|
||||
through such another name that happens during the last step of a move
|
||||
is not coordinated with it, and can end up on the original, losing its
|
||||
writes. With `moveonenospc`, avoid presenting one file under two names:
|
||||
[follow-symlinks](follow-symlinks.md) and branches that reach the same
|
||||
file by two paths both do that. Entries
|
||||
inside the `rename-exdev` staging namespace (the targets of
|
||||
published replacement symlinks, `.mergerfs_rename_exdev/`) are also never
|
||||
relocated: moving one would re-home the symlink's target and strand the
|
||||
published name. In all of these cases the write keeps its original error.
|
||||
|
||||
Whether a file can be relocated is decided when it is first opened, and
|
||||
holds until every handle to it has been closed. A file opened while
|
||||
`moveonenospc` is disabled, or opened with a kernel passthrough backing
|
||||
ID (see [passthrough.io](passthrough.md)), is never relocated, and its
|
||||
handles skip the coordination a relocation needs. Enabling
|
||||
`moveonenospc` at runtime therefore applies to files opened afterwards.
|
||||
|
||||
Source and destination identity checks reject replacements observed
|
||||
before cleanup or source removal. Removal itself is a pathname operation
|
||||
and cannot be atomic with those earlier checks; they do not synchronize
|
||||
with external changes to the branches racing the final unlink syscall.
|
||||
|
||||
If `moveonenospc` is disabled the underlying error will be returned,
|
||||
or the bytes written if part of the write succeeded.
|
||||
|
|
|
|||
|
|
@ -24,8 +24,13 @@ This performance does come at the cost of some functionality as
|
|||
`mergerfs` no longer has control over reads and writes which means all
|
||||
features related to read/write are affected.
|
||||
|
||||
* [moveonenospc](moveonenospc.md): Does not work because errors are
|
||||
not reported back to `mergerfs`.
|
||||
* [moveonenospc](moveonenospc.md): A file opened with a passthrough
|
||||
backing ID is never relocated, as the kernel keeps reading and
|
||||
writing the original file through that ID. A file gets the ID from
|
||||
its first open, when no handle has it open yet, and keeps it until
|
||||
all of its handles are closed. With `passthrough.io=rw` that is every
|
||||
file; with `ro` or `wo`, a file first opened read-only or write-only.
|
||||
A file first opened any other way is relocated as usual.
|
||||
* nullrw: Since `mergerfs` no longer receives read/write requests
|
||||
there is no read or write to ignore.
|
||||
* [readahead](readahead.md): Still affects the `readahead` values of
|
||||
|
|
|
|||
|
|
@ -45,7 +45,8 @@ Distributions that enforce RPM signature checking reject the unsigned
|
|||
local build. When installing a locally built RPM that you built and
|
||||
trust, pass `--nosignature` to `rpm`.
|
||||
|
||||
mergerfs requires a C++20 compiler and the system `g++` on RHEL /
|
||||
mergerfs requires a C++20 compiler and standard library that support
|
||||
atomic waiting, such as GCC 11 or newer. The system `g++` on RHEL /
|
||||
Rocky 8 is too old. On RHEL / Rocky `install-build-pkgs` installs the
|
||||
newest GCC Toolset when it is newer than the system compiler, and the
|
||||
Rocky Linux container builds use it. When `CXX` is unset and the
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ int
|
|||
MoveOnENOSPC::from_string(const std::string_view s_)
|
||||
{
|
||||
int rv;
|
||||
bool enabled;
|
||||
std::string s;
|
||||
Policy::CreateImpl *tmp;
|
||||
|
||||
|
|
@ -33,7 +34,10 @@ MoveOnENOSPC::from_string(const std::string_view s_)
|
|||
if((rv == 0) && (enabled == true))
|
||||
s = "pfrd";
|
||||
ef((rv == 0) && (enabled == false))
|
||||
return (enabled = false,0);
|
||||
{
|
||||
_data = nullptr;
|
||||
return 0;
|
||||
}
|
||||
ef(rv != 0)
|
||||
s = s_;
|
||||
else
|
||||
|
|
@ -43,8 +47,7 @@ MoveOnENOSPC::from_string(const std::string_view s_)
|
|||
if(tmp == NULL)
|
||||
return -EINVAL;
|
||||
|
||||
policy = tmp;
|
||||
enabled = true;
|
||||
_data = tmp;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -52,7 +55,10 @@ MoveOnENOSPC::from_string(const std::string_view s_)
|
|||
std::string
|
||||
MoveOnENOSPC::to_string(void) const
|
||||
{
|
||||
if(enabled)
|
||||
return policy.name();
|
||||
const Policy::Create create = policy();
|
||||
|
||||
if(create)
|
||||
return create.name();
|
||||
|
||||
return "false";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
#include "policies.hpp"
|
||||
#include "tofrom_string.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
|
||||
|
||||
|
|
@ -29,8 +30,7 @@ class MoveOnENOSPC : public ToFromString
|
|||
{
|
||||
public:
|
||||
MoveOnENOSPC(const bool enabled_)
|
||||
: enabled(enabled_),
|
||||
policy(&Policies::Create::pfrd)
|
||||
: _data(enabled_ ? &Policies::Create::pfrd : nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
|
|
@ -39,6 +39,15 @@ public:
|
|||
std::string to_string() const final;
|
||||
|
||||
public:
|
||||
bool enabled;
|
||||
Policy::Create policy;
|
||||
// The enabled state and the create policy are one atomic value: null
|
||||
// means disabled. Readers get a consistent pair even when setxattr
|
||||
// changes the option while a request runs.
|
||||
Policy::Create
|
||||
policy() const
|
||||
{
|
||||
return Policy::Create(_data.load());
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic<Policy::CreateImpl*> _data;
|
||||
};
|
||||
|
|
|
|||
186
src/fileinfo.hpp
186
src/fileinfo.hpp
|
|
@ -39,6 +39,50 @@
|
|||
|
||||
See fuse_open.cpp and fuse_release.cpp for how FileInfo is used in the
|
||||
open/close flow.
|
||||
|
||||
SHARED STATE AND MOVEONENOSPC
|
||||
-----------------------------
|
||||
|
||||
Every handle of a kernel node that can be relocated - the canonical
|
||||
FileInfo and every later handle opened from it - shares one Shared
|
||||
object, its group. Its handle list lets moveonenospc prepare and then
|
||||
atomically switch every descriptor to the relocated copy.
|
||||
|
||||
Only a node that can be relocated has a group. That is decided once,
|
||||
at the node's first open, before its open_files entry is inserted:
|
||||
moveonenospc must be enabled and the node must have no kernel
|
||||
passthrough ID, which stays on the original file and cannot be
|
||||
switched. Every other node has no group and its handles take no lock,
|
||||
so they cost nothing; enabling moveonenospc at runtime applies to
|
||||
nodes first opened afterwards.
|
||||
|
||||
A move switches each handle with dup2 onto its existing descriptor
|
||||
number, so FileInfo::fd never changes while the handle is open and
|
||||
reads need no lock: they complete on the original, whose bytes the
|
||||
copy matches, or on the copy. Shared::lock is held shared by every
|
||||
operation that changes the file, and by opens, and exclusively by a
|
||||
move for its whole duration (lock_for_change()). Shared::attr_lock is
|
||||
held shared by fgetattr and statx, which also read the handle's branch
|
||||
and fusepath (lock_for_attr()), and exclusively by a move only from
|
||||
before the source unlink until every handle is switched. Both are
|
||||
writer preferring (see rwlock.hpp): a waiting move holds off new
|
||||
shared holders, so neither may be taken shared twice by one thread.
|
||||
Shared::handles_mutex protects the handle list and is acquired after
|
||||
lock when both are needed. Handles unregister before their descriptors
|
||||
are closed, so a mover cannot retain an object whose fd number was
|
||||
reused.
|
||||
|
||||
The kernel can reach one file through more than one node: a hardlink
|
||||
whose other name was removed while both were open, a rename made
|
||||
directly on a branch while the file was open, or overlapping branches.
|
||||
Those handles are in other groups, which a move cannot switch, so a
|
||||
move is refused while any other node has the file open (see
|
||||
moveonenospc.cpp).
|
||||
|
||||
Lock order, where several are held: a group is locked Shared::lock
|
||||
(shared or exclusive), then Shared::handles_mutex, then the
|
||||
open_files map's internal locks, then Shared::attr_lock. Nothing
|
||||
acquires them in another order.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
|
@ -46,31 +90,39 @@
|
|||
#include "assert.hpp"
|
||||
#include "branch.hpp"
|
||||
#include "fh.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_open_fd.hpp"
|
||||
#include "fs_path.hpp"
|
||||
#include "rwlock.hpp"
|
||||
|
||||
#include "base_types.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <vector>
|
||||
|
||||
|
||||
class FileInfo : public FH
|
||||
{
|
||||
public:
|
||||
static FileInfo *from_fh(const u64);
|
||||
struct Shared
|
||||
{
|
||||
// RWLock is cache-line aligned, so each lock has its own lines and
|
||||
// fgetattr's updates of attr_lock don't invalidate the line every
|
||||
// write reads.
|
||||
RWLock lock;
|
||||
RWLock attr_lock;
|
||||
std::mutex handles_mutex;
|
||||
std::vector<FileInfo*> handles;
|
||||
};
|
||||
|
||||
public:
|
||||
static FileInfo *from_fh(const u64 fh_);
|
||||
static u64 to_fh(const FileInfo*);
|
||||
|
||||
public:
|
||||
FileInfo(const int fd_,
|
||||
const Branch *branch_,
|
||||
const fs::path &fusepath_,
|
||||
const bool direct_io_)
|
||||
: FH(fusepath_),
|
||||
fd(fd_),
|
||||
branch(*branch_),
|
||||
direct_io(direct_io_)
|
||||
{
|
||||
}
|
||||
|
||||
// The first handle of a node. It has no group until make_movable().
|
||||
FileInfo(const int fd_,
|
||||
const Branch &branch_,
|
||||
const fs::path &fusepath_,
|
||||
|
|
@ -82,12 +134,99 @@ public:
|
|||
{
|
||||
}
|
||||
|
||||
FileInfo(const FileInfo *fi_)
|
||||
: FH(fi_->fusepath),
|
||||
fd(fi_->fd),
|
||||
branch(fi_->branch),
|
||||
direct_io(fi_->direct_io)
|
||||
// A later handle of canonical_'s node, opened from its descriptor
|
||||
// with flags_. The group lock is held shared while the descriptor is
|
||||
// opened and registered, so a move either includes the handle or
|
||||
// finished before it was opened.
|
||||
static
|
||||
int
|
||||
reopen(const FileInfo &canonical_,
|
||||
const fs::path &fusepath_,
|
||||
const int flags_,
|
||||
const bool direct_io_,
|
||||
FileInfo **fi_)
|
||||
{
|
||||
int fd;
|
||||
auto lk = canonical_.lock_for_change();
|
||||
|
||||
fd = fs::open_fd(canonical_.fd,flags_);
|
||||
if(fd < 0)
|
||||
return fd;
|
||||
|
||||
*fi_ = new FileInfo(fd,canonical_,fusepath_,direct_io_);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Unregisters the handle, then closes its descriptor. A mover holds
|
||||
// handles_mutex from preparation through commit, so it never uses a
|
||||
// handle whose descriptor was closed and its number reused.
|
||||
~FileInfo()
|
||||
{
|
||||
if(shared)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shared->handles_mutex);
|
||||
std::erase(shared->handles,this);
|
||||
}
|
||||
|
||||
fs::close(fd);
|
||||
}
|
||||
|
||||
// Held by every operation that changes the file, so a move never
|
||||
// copies a file still being changed. Nothing for a node without a
|
||||
// group.
|
||||
[[nodiscard]]
|
||||
std::shared_lock<RWLock>
|
||||
lock_for_change() const
|
||||
{
|
||||
if(shared)
|
||||
return std::shared_lock<RWLock>(shared->lock);
|
||||
return {};
|
||||
}
|
||||
|
||||
// Held by fgetattr and statx, which read branch and fusepath and must
|
||||
// not see the unlinked original during a move's switch. Nothing for a
|
||||
// node without a group.
|
||||
[[nodiscard]]
|
||||
std::shared_lock<RWLock>
|
||||
lock_for_attr() const
|
||||
{
|
||||
if(shared)
|
||||
return std::shared_lock<RWLock>(shared->attr_lock);
|
||||
return {};
|
||||
}
|
||||
|
||||
FileInfo(const FileInfo&) = delete;
|
||||
FileInfo& operator=(const FileInfo&) = delete;
|
||||
|
||||
private:
|
||||
friend class State;
|
||||
|
||||
// Gives the first handle of a node that can be relocated its group.
|
||||
// Called only by State::insert_open_file, just before the node's
|
||||
// open_files entry is inserted; see above.
|
||||
void
|
||||
make_movable()
|
||||
{
|
||||
shared = std::make_shared<Shared>();
|
||||
shared->handles.push_back(this);
|
||||
}
|
||||
|
||||
FileInfo(const int fd_,
|
||||
const FileInfo &canonical_,
|
||||
const fs::path &fusepath_,
|
||||
const bool direct_io_)
|
||||
: FH(fusepath_),
|
||||
fd(fd_),
|
||||
branch(canonical_.branch),
|
||||
direct_io(direct_io_),
|
||||
shared(canonical_.shared)
|
||||
{
|
||||
if(!shared)
|
||||
return;
|
||||
|
||||
std::lock_guard<std::mutex> lk(shared->handles_mutex);
|
||||
shared->handles.push_back(this);
|
||||
}
|
||||
|
||||
public:
|
||||
|
|
@ -97,16 +236,9 @@ public:
|
|||
int fd;
|
||||
Branch branch;
|
||||
u32 direct_io:1;
|
||||
// Serializes the fd state across concurrent writes on the same open
|
||||
// file. Concurrent writes happen with:
|
||||
// 1) writeback-cache + page-cache mode
|
||||
// 2) parallel_direct_writes + direct_io=true
|
||||
//
|
||||
// Common case (plain pwrite on stable fd) only needs a shared lock
|
||||
// since the kernel already serializes fd mutations. The danger is
|
||||
// the fs::dup2() rebinding when moveonenospc activates. Writers
|
||||
// take shared lock; move takes unique.
|
||||
std::shared_mutex mutex;
|
||||
// Null for a node that is never relocated. Set only before the node's
|
||||
// open_files entry is inserted, so readers need no lock.
|
||||
std::shared_ptr<Shared> shared;
|
||||
};
|
||||
|
||||
inline
|
||||
|
|
|
|||
|
|
@ -144,14 +144,13 @@ fs::copyfile(const int src_fd_,
|
|||
// * Does not handle non-regular files.
|
||||
|
||||
s64
|
||||
fs::copyfile(const int src_fd_,
|
||||
const fs::path &dst_filepath_,
|
||||
const fs::CopyFileFlags &flags_)
|
||||
fs::copyfile_stage(const int src_fd_,
|
||||
const fs::path &dst_filepath_,
|
||||
const bool cleanup_failure_,
|
||||
fs::StagedCopy *staged_)
|
||||
{
|
||||
s64 rv;
|
||||
int dst_fd;
|
||||
struct stat src_st = {};
|
||||
std::string dst_tmppath;
|
||||
struct sigaction old_act;
|
||||
struct sigaction new_act;
|
||||
|
||||
|
|
@ -164,6 +163,10 @@ fs::copyfile(const int src_fd_,
|
|||
|
||||
while(true)
|
||||
{
|
||||
int dst_fd;
|
||||
struct stat now_st;
|
||||
std::string dst_tmppath;
|
||||
|
||||
// For comparison after the copy to see if the file was
|
||||
// modified. This could be made more thorough by adding some
|
||||
// hashing but probably overkill. Also used to provide size and
|
||||
|
|
@ -177,7 +180,7 @@ fs::copyfile(const int src_fd_,
|
|||
std::tie(dst_fd,dst_tmppath) = fs::mktemp(dst_filepath_,O_RDWR);
|
||||
if(dst_fd < 0)
|
||||
return dst_fd;
|
||||
DEFER { fs::close(dst_fd); };
|
||||
MAKE_DEFER(close_dst) { fs::close(dst_fd); };
|
||||
|
||||
// If it fails or is unsupported... so be it. This will help
|
||||
// limit the possibility of the file being modified while the
|
||||
|
|
@ -190,26 +193,50 @@ fs::copyfile(const int src_fd_,
|
|||
rv = fs::copyfile(src_fd_,src_st,dst_fd);
|
||||
if(rv < 0)
|
||||
{
|
||||
if(flags_.cleanup_failure)
|
||||
if(cleanup_failure_)
|
||||
fs::unlink(dst_tmppath);
|
||||
return rv;
|
||||
}
|
||||
|
||||
rv = fs::file_changed(src_fd_,src_st);
|
||||
if(rv != FS_FILE_UNCHANGED)
|
||||
rv = fs::fstat(src_fd_,&now_st);
|
||||
if((rv < 0) || fs::file_changed(src_st,now_st))
|
||||
{
|
||||
fs::unlink(dst_tmppath);
|
||||
continue;
|
||||
}
|
||||
|
||||
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;
|
||||
close_dst.dismiss();
|
||||
staged_->fd = dst_fd;
|
||||
staged_->path = std::move(dst_tmppath);
|
||||
staged_->src_st = src_st;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
fs::copyfile_publish(const fs::StagedCopy &staged_,
|
||||
const fs::path &dst_filepath_)
|
||||
{
|
||||
return ::_publish_noreplace(staged_.path.c_str(),dst_filepath_.c_str());
|
||||
}
|
||||
|
||||
s64
|
||||
fs::copyfile(const int src_fd_,
|
||||
const fs::path &dst_filepath_,
|
||||
const fs::CopyFileFlags &flags_)
|
||||
{
|
||||
s64 rv;
|
||||
fs::StagedCopy staged;
|
||||
|
||||
rv = fs::copyfile_stage(src_fd_,dst_filepath_,flags_.cleanup_failure,&staged);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
DEFER { fs::close(staged.fd); };
|
||||
|
||||
rv = fs::rename(staged.path.c_str(),dst_filepath_.c_str());
|
||||
if((rv < 0) && (flags_.cleanup_failure))
|
||||
fs::unlink(staged.path);
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@
|
|||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#define FS_COPYFILE_NONE (0)
|
||||
#define FS_COPYFILE_CLEANUP_FAILURE (1 << 0)
|
||||
|
||||
|
|
@ -31,7 +33,16 @@ namespace fs
|
|||
struct CopyFileFlags
|
||||
{
|
||||
int cleanup_failure:1;
|
||||
bool no_replace:1 = false;
|
||||
};
|
||||
|
||||
// A copy at a temporary name beside its destination. While fd is
|
||||
// open it pins the copied object, whatever its name. src_st is the
|
||||
// source as it was when copied.
|
||||
struct StagedCopy
|
||||
{
|
||||
int fd = -1;
|
||||
std::string path;
|
||||
struct stat src_st = {};
|
||||
};
|
||||
|
||||
s64
|
||||
|
|
@ -39,6 +50,22 @@ namespace fs
|
|||
const struct stat &src_st,
|
||||
const int dst_fd);
|
||||
|
||||
// Copy src_fd to a temporary name beside dst_filepath, retrying
|
||||
// while the source changes during the copy. On success the caller
|
||||
// owns staged->fd and must publish or unlink staged->path. On
|
||||
// failure the temporary is removed when cleanup_failure is set.
|
||||
s64
|
||||
copyfile_stage(const int src_fd,
|
||||
const fs::path &dst_filepath,
|
||||
const bool cleanup_failure,
|
||||
StagedCopy *staged);
|
||||
|
||||
// Give a staged copy its final name, never replacing an existing
|
||||
// entry. The staged descriptor stays open.
|
||||
int
|
||||
copyfile_publish(const StagedCopy &staged,
|
||||
const fs::path &dst_filepath);
|
||||
|
||||
s64
|
||||
copyfile(const int src_fd,
|
||||
const fs::path &dst_filepath,
|
||||
|
|
|
|||
|
|
@ -18,37 +18,25 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "fs_fstat.hpp"
|
||||
|
||||
#define FS_FILE_CHANGED 0
|
||||
#define FS_FILE_UNCHANGED 1
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace fs
|
||||
{
|
||||
// Whether new_st_ describes another file than orig_st_, or the same
|
||||
// file with other contents or metadata. ctime catches attribute and
|
||||
// xattr changes, which leave size and mtime alone.
|
||||
static
|
||||
inline
|
||||
int
|
||||
file_changed(const int fd_,
|
||||
const struct stat &orig_st_)
|
||||
bool
|
||||
file_changed(const struct stat &orig_st_,
|
||||
const struct stat &new_st_)
|
||||
{
|
||||
int rv;
|
||||
struct stat new_st;
|
||||
|
||||
rv = fs::fstat(fd_,&new_st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
if(orig_st_.st_ino != new_st.st_ino)
|
||||
return FS_FILE_CHANGED;
|
||||
if(orig_st_.st_dev != new_st.st_dev)
|
||||
return FS_FILE_CHANGED;
|
||||
if(orig_st_.st_size != new_st.st_size)
|
||||
return FS_FILE_CHANGED;
|
||||
if(orig_st_.st_mtim.tv_sec != new_st.st_mtim.tv_sec)
|
||||
return FS_FILE_CHANGED;
|
||||
if(orig_st_.st_mtim.tv_nsec != new_st.st_mtim.tv_nsec)
|
||||
return FS_FILE_CHANGED;
|
||||
|
||||
return FS_FILE_UNCHANGED;
|
||||
return ((orig_st_.st_ino != new_st_.st_ino) ||
|
||||
(orig_st_.st_dev != new_st_.st_dev) ||
|
||||
(orig_st_.st_size != new_st_.st_size) ||
|
||||
(orig_st_.st_mtim.tv_sec != new_st_.st_mtim.tv_sec) ||
|
||||
(orig_st_.st_mtim.tv_nsec != new_st_.st_mtim.tv_nsec) ||
|
||||
(orig_st_.st_ctim.tv_sec != new_st_.st_ctim.tv_sec) ||
|
||||
(orig_st_.st_ctim.tv_nsec != new_st_.st_ctim.tv_nsec));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
342
src/fs_movefile.cpp
Normal file
342
src/fs_movefile.cpp
Normal file
|
|
@ -0,0 +1,342 @@
|
|||
/*
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "fs_movefile.hpp"
|
||||
|
||||
#include "base_types.h"
|
||||
#include "errno.hpp"
|
||||
#include "fs_clonepath.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_copyfile.hpp"
|
||||
#include "fs_file_unchanged.hpp"
|
||||
#include "fs_findonfs.hpp"
|
||||
#include "fs_fstat.hpp"
|
||||
#include "fs_fsync.hpp"
|
||||
#include "fs_getfl.hpp"
|
||||
#include "fs_has_space.hpp"
|
||||
#include "fs_is_same_file.hpp"
|
||||
#include "fs_lstat.hpp"
|
||||
#include "fs_open.hpp"
|
||||
#include "fs_open_fd.hpp"
|
||||
#include "fs_openat.hpp"
|
||||
#include "fs_path.hpp"
|
||||
#include "fs_stat.hpp"
|
||||
#include "fs_unlink.hpp"
|
||||
#include "policy.hpp"
|
||||
#include "syslog.hpp"
|
||||
|
||||
#include "scope_guard/scope_guard.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
// Compare what path_ names now with the object fd_ pins, leaving fd_'s
|
||||
// stat in *fd_st_. These checks reject races observed before unlink(2),
|
||||
// but the subsequent name-based unlink cannot itself be made atomic
|
||||
// with the lstat check.
|
||||
static
|
||||
int
|
||||
_check_path_identity(const fs::path &path_,
|
||||
const int fd_,
|
||||
struct stat *fd_st_)
|
||||
{
|
||||
int rv;
|
||||
|
||||
rv = fs::fstat(fd_,fd_st_);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
rv = fs::is_same_file(path_,*fd_st_);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
return ((rv == 1) ? 0 : -ESTALE);
|
||||
}
|
||||
|
||||
static
|
||||
void
|
||||
_remove_own_destination(const fs::path &path_,
|
||||
const int fd_)
|
||||
{
|
||||
// Skip cleanup when the path no longer names the staged object.
|
||||
struct stat st;
|
||||
|
||||
if(::_check_path_identity(path_,fd_,&st) < 0)
|
||||
return;
|
||||
|
||||
fs::unlink(path_);
|
||||
}
|
||||
|
||||
// fsync, treating a filesystem which cannot sync this object as
|
||||
// success: nothing more durable is available there.
|
||||
static
|
||||
int
|
||||
_sync(const int fd_)
|
||||
{
|
||||
const int rv = fs::fsync(fd_);
|
||||
|
||||
if((rv == -EINVAL) || (rv == -EROFS) ||
|
||||
(rv == -ENOTSUP) || (rv == -EOPNOTSUPP))
|
||||
return 0;
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
static
|
||||
int
|
||||
_sync_dir(const fs::path &path_)
|
||||
{
|
||||
int rv;
|
||||
int fd;
|
||||
|
||||
fd = fs::open_dir_ro(path_);
|
||||
if(fd < 0)
|
||||
return fd;
|
||||
|
||||
rv = ::_sync(fd);
|
||||
fs::close(fd);
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
// Make the published name durable: the branch root and every directory
|
||||
// down to the copy's, any of which clonepath may have just created.
|
||||
// Each is opened relative to its parent, so no path is rebuilt or
|
||||
// resolved again.
|
||||
static
|
||||
int
|
||||
_sync_dirs(const fs::path &branch_,
|
||||
const fs::path &fusedir_)
|
||||
{
|
||||
int rv;
|
||||
int fd;
|
||||
|
||||
fd = fs::open_dir_ro(branch_);
|
||||
if(fd < 0)
|
||||
return fd;
|
||||
|
||||
rv = ::_sync(fd);
|
||||
for(auto name = fusedir_.begin(); (rv == 0) && (name != fusedir_.end()); ++name)
|
||||
{
|
||||
const int child = fs::openat(fd,name->c_str(),O_RDONLY|O_DIRECTORY);
|
||||
|
||||
fs::close(fd);
|
||||
if(child < 0)
|
||||
return child;
|
||||
fd = child;
|
||||
rv = ::_sync(fd);
|
||||
}
|
||||
fs::close(fd);
|
||||
|
||||
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::Impl>(&branches_->minfreespace());
|
||||
(*candidates_)->reserve(branches_->size());
|
||||
}
|
||||
(*candidates_)->push_back(branch);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
fs::movefile(const Policy::Create &createFunc_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
const int origfd_,
|
||||
fs::MoveHooks &hooks_)
|
||||
{
|
||||
int rv;
|
||||
int srcfd;
|
||||
int origfd_flags;
|
||||
struct stat st;
|
||||
fs::path fusedir;
|
||||
fs::path src_branch;
|
||||
fs::path src_filepath;
|
||||
fs::path dst_filepath;
|
||||
fs::StagedCopy staged;
|
||||
Branches::Ptr candidates;
|
||||
std::vector<Branch*> dst_branch;
|
||||
|
||||
// `branchpath_` is where the handle last saw the file; findonfs
|
||||
// confirms it, or finds the branch the file is on now.
|
||||
src_branch = branchpath_;
|
||||
rv = fs::findonfs(branches_,fusepath_,origfd_,&src_branch,&st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
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())
|
||||
return -ENOSPC;
|
||||
|
||||
origfd_flags = fs::getfl(origfd_);
|
||||
if(origfd_flags < 0)
|
||||
return origfd_flags;
|
||||
|
||||
if(fs::has_space(dst_branch[0]->path,st.st_size) == false)
|
||||
return -ENOSPC;
|
||||
|
||||
rv = hooks_.check();
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
rv = fs::clonepath(src_branch,dst_branch[0]->path,fusedir);
|
||||
if(rv < 0)
|
||||
return -ENOSPC;
|
||||
|
||||
src_filepath = src_branch / fusepath_;
|
||||
dst_filepath = dst_branch[0]->path / fusepath_;
|
||||
|
||||
// The read/write copy fallback needs a readable, buffered descriptor.
|
||||
// Reopen the pinned inode so the application's I/O flags stay intact.
|
||||
srcfd = origfd_;
|
||||
if(((origfd_flags & O_ACCMODE) == O_WRONLY) || (origfd_flags & O_DIRECT))
|
||||
{
|
||||
srcfd = fs::open_fd(origfd_,O_RDONLY|O_NONBLOCK);
|
||||
if(srcfd < 0)
|
||||
return srcfd;
|
||||
}
|
||||
DEFER { if(srcfd != origfd_) fs::close(srcfd); };
|
||||
|
||||
rv = fs::copyfile_stage(srcfd,dst_filepath,true,&staged);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
// staged.fd pins the copy whatever its name: every handle is prepared
|
||||
// from it, and every cleanup can tell it from a replacement. Until the
|
||||
// source is removed, any failure removes the copy again: by its
|
||||
// temporary name, then once published by its final name.
|
||||
DEFER { fs::close(staged.fd); };
|
||||
MAKE_DEFER(unstage) { fs::unlink(staged.path); };
|
||||
|
||||
// The source is removed only once the copy and its name are durable,
|
||||
// so a crash can never leave the file's name without its data. This
|
||||
// also surfaces a destination that runs out of space only on flush.
|
||||
rv = ::_sync(staged.fd);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
rv = fs::copyfile_publish(staged,dst_filepath);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
unstage.dismiss();
|
||||
MAKE_DEFER(unpublish) { ::_remove_own_destination(dst_filepath,staged.fd); };
|
||||
|
||||
rv = ::_sync_dirs(dst_branch[0]->path,fusedir);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
rv = hooks_.prepare(staged.fd,dst_branch[0]->path);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
// Preparation may have taken time. Abort if the names no longer
|
||||
// describe the copy and the source.
|
||||
rv = ::_check_path_identity(dst_filepath,staged.fd,&st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
rv = ::_check_path_identity(src_filepath,srcfd,&st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
// A change made by path - chmod, chown, utimes, truncate, a new link
|
||||
// or an xattr change - doesn't wait for the group lock. One that
|
||||
// reached the source after it was copied would be lost with the
|
||||
// source; a new link would keep its name on the original.
|
||||
if(fs::file_changed(staged.src_st,st))
|
||||
return -EBUSY;
|
||||
|
||||
rv = fs::unlink(src_filepath);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
unpublish.dismiss();
|
||||
|
||||
// Irreversibility starts here. commit performs no open, allocation, or
|
||||
// pathname cleanup, and runs first so the handles switch without
|
||||
// waiting for the sync below. Make the removal durable as well, so a
|
||||
// crash cannot bring back the original to shadow the copy. The move
|
||||
// has completed, so a failure is logged rather than undone.
|
||||
hooks_.commit();
|
||||
|
||||
rv = ::_sync_dir(src_filepath.parent_path());
|
||||
if(rv < 0)
|
||||
SysLog::error("moveonenospc: moved {} from {} but could not sync"
|
||||
" the removal: {}",
|
||||
fusepath_.string(),src_branch.string(),strerror(-rv));
|
||||
|
||||
return 0;
|
||||
}
|
||||
73
src/fs_movefile.hpp
Normal file
73
src/fs_movefile.hpp
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "branches.hpp"
|
||||
#include "fs_path.hpp"
|
||||
#include "policy.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
|
||||
namespace fs
|
||||
{
|
||||
// The caller's part of a move: whether it may happen, and the
|
||||
// descriptors that follow the file. Every reason to refuse the move
|
||||
// belongs to check() and prepare(); movefile itself only gives up
|
||||
// when its copy no longer matches the source.
|
||||
class MoveHooks
|
||||
{
|
||||
public:
|
||||
// Runs once a destination with room is chosen, before anything is
|
||||
// created there: a full pool refuses without it, and a lasting
|
||||
// reason to refuse costs no copy. A negative errno refuses.
|
||||
virtual
|
||||
int
|
||||
check() = 0;
|
||||
|
||||
// Runs after publication, as late as possible before the source is
|
||||
// removed. dstfd pins the copy; use fs::open_fd(dstfd,flags) for
|
||||
// data descriptors. A negative errno refuses. It must not throw:
|
||||
// the published copy has to be removed again.
|
||||
virtual
|
||||
int
|
||||
prepare(const int dstfd,
|
||||
const fs::path &branchpath) noexcept = 0;
|
||||
|
||||
// Runs after a successful source unlink and cannot fail.
|
||||
virtual
|
||||
void
|
||||
commit() noexcept = 0;
|
||||
|
||||
protected:
|
||||
~MoveHooks() = default;
|
||||
};
|
||||
|
||||
// Copy the file origfd describes to a branch chosen by policy, then
|
||||
// remove the source. The copy is durable, under its final name,
|
||||
// before the source is removed. Returns 0 only after hooks.commit();
|
||||
// any earlier failure removes the copy and changes nothing else.
|
||||
int
|
||||
movefile(const Policy::Create &policy,
|
||||
const Branches::Ptr &branches,
|
||||
const fs::path &branchpath,
|
||||
const fs::path &fusepath,
|
||||
const int origfd,
|
||||
MoveHooks &hooks);
|
||||
}
|
||||
|
|
@ -1,207 +0,0 @@
|
|||
/*
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "fs_movefile_and_open.hpp"
|
||||
|
||||
#include "base_types.h"
|
||||
#include "errno.hpp"
|
||||
#include "fs_clonepath.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_copyfile.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"
|
||||
#include "fs_rename.hpp"
|
||||
#include "fs_stat.hpp"
|
||||
#include "fs_unlink.hpp"
|
||||
#include "policy.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
static
|
||||
int
|
||||
_cleanup_flags(const int flags_)
|
||||
{
|
||||
int rv;
|
||||
|
||||
rv = flags_;
|
||||
rv = (rv & ~O_TRUNC);
|
||||
rv = (rv & ~O_CREAT);
|
||||
rv = (rv & ~O_EXCL);
|
||||
|
||||
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::Impl>(&branches_->minfreespace());
|
||||
(*candidates_)->reserve(branches_->size());
|
||||
}
|
||||
(*candidates_)->push_back(branch);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static
|
||||
int
|
||||
_movefile_and_open(const Policy::Create &createFunc_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
int origfd_)
|
||||
{
|
||||
int rv;
|
||||
int dstfd_flags;
|
||||
int origfd_flags;
|
||||
struct stat st;
|
||||
fs::path fusedir;
|
||||
fs::path src_branch;
|
||||
fs::path src_filepath;
|
||||
fs::path dst_filepath;
|
||||
Branches::Ptr candidates;
|
||||
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,&st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
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())
|
||||
return -ENOSPC;
|
||||
|
||||
origfd_flags = fs::getfl(origfd_);
|
||||
if(origfd_flags < 0)
|
||||
return origfd_flags;
|
||||
|
||||
if(fs::has_space(dst_branch[0]->path,st.st_size) == false)
|
||||
return -ENOSPC;
|
||||
|
||||
rv = fs::clonepath(src_branch,dst_branch[0]->path,fusedir);
|
||||
if(rv < 0)
|
||||
return -ENOSPC;
|
||||
|
||||
src_filepath = src_branch / fusepath_;
|
||||
dst_filepath = dst_branch[0]->path / fusepath_;
|
||||
|
||||
rv = fs::copyfile(src_filepath,dst_filepath,
|
||||
{.cleanup_failure = true, .no_replace = true});
|
||||
if(rv < 0)
|
||||
return -ENOSPC;
|
||||
|
||||
dstfd_flags = ::_cleanup_flags(origfd_flags);
|
||||
rv = fs::open(dst_filepath,dstfd_flags);
|
||||
if(rv < 0)
|
||||
return -ENOSPC;
|
||||
|
||||
fs::unlink(src_filepath);
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
int
|
||||
fs::movefile_and_open(const Policy::Create &policy_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
const int origfd_)
|
||||
{
|
||||
return ::_movefile_and_open(policy_,
|
||||
branches_,
|
||||
branchpath_,
|
||||
fusepath_,
|
||||
origfd_);
|
||||
}
|
||||
|
||||
int
|
||||
fs::movefile_and_open_as_root(const Policy::Create &policy_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
const int origfd_)
|
||||
{
|
||||
return fs::movefile_and_open(policy_,
|
||||
branches_,
|
||||
branchpath_,
|
||||
fusepath_,
|
||||
origfd_);
|
||||
}
|
||||
|
|
@ -69,6 +69,10 @@ FUSE::copy_file_range(const fuse_req_ctx_t *ctx_,
|
|||
if(not dst_fi)
|
||||
return -EBADF;
|
||||
|
||||
// Only the destination changes. The source is only read, which needs
|
||||
// no lock: moveonenospc switches descriptors with dup2.
|
||||
auto lk = dst_fi->lock_for_change();
|
||||
|
||||
return ::_copy_file_range(src_fi->fd,
|
||||
src_off_,
|
||||
dst_fi->fd,
|
||||
|
|
|
|||
|
|
@ -52,7 +52,6 @@
|
|||
#include "errno.hpp"
|
||||
#include "fileinfo.hpp"
|
||||
#include "fs_acl.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_clonepath.hpp"
|
||||
#include "fs_open.hpp"
|
||||
#include "fs_open_as.hpp"
|
||||
|
|
@ -262,8 +261,6 @@ _create(const fuse_req_ctx_t *ctx_,
|
|||
mode_t mode_,
|
||||
fuse_file_info_t *ffi_)
|
||||
{
|
||||
auto &of = state.open_files;
|
||||
|
||||
::_config_to_ffi_flags(ctx_->pid,ffi_);
|
||||
if(cfg.cache_writeback)
|
||||
::_tweak_flags_cache_writeback(&ffi_->flags);
|
||||
|
|
@ -318,9 +315,9 @@ _create(const fuse_req_ctx_t *ctx_,
|
|||
break;
|
||||
}
|
||||
|
||||
bool inserted = of.try_emplace(ctx_->nodeid,
|
||||
backing_id,
|
||||
fi);
|
||||
bool inserted = state.insert_open_file(ctx_->nodeid,
|
||||
backing_id,
|
||||
fi);
|
||||
|
||||
// Really. This should never happen. FUSE should not be allowing a
|
||||
// create for an existing nodeid. mergerfs doesn't reuse nodeids. It
|
||||
|
|
@ -330,7 +327,6 @@ _create(const fuse_req_ctx_t *ctx_,
|
|||
const char *msg = "nodeid already exists in open_files map";
|
||||
|
||||
FUSE::passthrough_close(backing_id);
|
||||
fs::close(fi->fd);
|
||||
delete fi;
|
||||
ffi_->fh = 0;
|
||||
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ FUSE::fallocate(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -EBADF;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_fallocate(fi->fd,
|
||||
mode_,
|
||||
offset_,
|
||||
|
|
|
|||
|
|
@ -59,5 +59,6 @@ FUSE::fchmod(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -ENOENT;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_fchmod(fi->fd,mode_);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,5 +63,6 @@ FUSE::fchown(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -ENOENT;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_fchown(fi->fd,uid_,gid_);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ _fgetattr(const FileInfo *fi_,
|
|||
struct stat *st_)
|
||||
{
|
||||
int rv;
|
||||
auto lk = fi_->lock_for_attr();
|
||||
|
||||
rv = fs::fstat(fi_->fd,st_);
|
||||
if(rv < 0)
|
||||
|
|
|
|||
|
|
@ -63,5 +63,8 @@ FUSE::fsync(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -EBADF;
|
||||
|
||||
// No group lock: a move makes its copy durable before removing the
|
||||
// original, so syncing either one is enough, and dup2 keeps fi->fd
|
||||
// valid across the switch.
|
||||
return ::_fsync(fi->fd,isdatasync_);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,5 +59,6 @@ FUSE::ftruncate(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -ENOENT;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_ftruncate(fi->fd,size_);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,5 +61,6 @@ FUSE::futimens(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -ENOENT;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_futimens(fi->fd,ts_);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,6 +120,7 @@ _ioctl_file(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -EBADF;
|
||||
|
||||
auto lk = fi->lock_for_change();
|
||||
return ::_ioctl(fi->fd,cmd_,data_,out_bufsz_);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@
|
|||
1. First, we check if an entry already exists (using visit())
|
||||
2. If it exists, we increment ref_count and create a new per-handle
|
||||
FileInfo by re-opening the canonical file descriptor
|
||||
(FileInfo::reopen, which a moveonenospc relocation cannot miss)
|
||||
3. If it doesn't exist, we create a new FileInfo and try to insert it
|
||||
4. If insertion fails (another thread inserted first), we clean up
|
||||
and retry (because to use passthrough it MUST be the same
|
||||
|
|
@ -51,7 +52,7 @@
|
|||
THE RETRY LOOP
|
||||
--------------
|
||||
|
||||
The MAX_OPEN_RETRIES loop (lines ~294-380) handles the race where multiple
|
||||
The MAX_OPEN_RETRIES loop handles the race where multiple
|
||||
threads try to open the same file simultaneously:
|
||||
|
||||
Thread A: visit() -> no entry -> open file -> try_emplace() -> SUCCESS
|
||||
|
|
@ -295,7 +296,7 @@ _open_path(const fs::path &filepath_,
|
|||
if(fd < 0)
|
||||
return fd;
|
||||
|
||||
fi = new FileInfo(fd,branch_,fusepath_,ffi_->direct_io);
|
||||
fi = new FileInfo(fd,*branch_,fusepath_,ffi_->direct_io);
|
||||
|
||||
ffi_->fh = fi->to_fh();
|
||||
|
||||
|
|
@ -304,19 +305,16 @@ _open_path(const fs::path &filepath_,
|
|||
|
||||
static
|
||||
int
|
||||
_open_fd(const int fd_,
|
||||
const Branch *branch_,
|
||||
_open_fd(const FileInfo *canonical_,
|
||||
const fs::path &fusepath_,
|
||||
fuse_file_info_t *ffi_)
|
||||
{
|
||||
int fd;
|
||||
int rv;
|
||||
FileInfo *fi;
|
||||
|
||||
fd = fs::open_fd(fd_,ffi_->flags);
|
||||
if(fd < 0)
|
||||
return fd;
|
||||
|
||||
fi = new FileInfo(fd,branch_,fusepath_,ffi_->direct_io);
|
||||
rv = FileInfo::reopen(*canonical_,fusepath_,ffi_->flags,ffi_->direct_io,&fi);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
ffi_->fh = fi->to_fh();
|
||||
|
||||
|
|
@ -405,10 +403,7 @@ _open(const fuse_req_ctx_t *ctx_,
|
|||
// If the file is already open...
|
||||
if(fi)
|
||||
{
|
||||
rv = ::_open_fd(fi->fd,
|
||||
&fi->branch,
|
||||
fusepath_,
|
||||
ffi_);
|
||||
rv = ::_open_fd(fi,fusepath_,ffi_);
|
||||
|
||||
// If we fail to reopen the already open file we need to
|
||||
// treat it similarly to fuse_release. Since we increased
|
||||
|
|
@ -474,16 +469,15 @@ _open(const fuse_req_ctx_t *ctx_,
|
|||
break;
|
||||
}
|
||||
|
||||
bool inserted = of.try_emplace(ctx_->nodeid,
|
||||
backing_id,
|
||||
fi);
|
||||
bool inserted = state.insert_open_file(ctx_->nodeid,
|
||||
backing_id,
|
||||
fi);
|
||||
if(inserted)
|
||||
return 0;
|
||||
|
||||
// Failed to insert because another thread beat us to
|
||||
// it. Cleanup the resources and try it all again.
|
||||
FUSE::passthrough_close(backing_id);
|
||||
fs::close(fi->fd);
|
||||
delete fi;
|
||||
ffi_->fh = 0;
|
||||
|
||||
|
|
|
|||
|
|
@ -72,6 +72,8 @@ FUSE::read(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -EBADF;
|
||||
|
||||
// No group lock: moveonenospc switches the descriptor with dup2, so
|
||||
// fi->fd stays valid and reads the same bytes on either side of it.
|
||||
if(fi->direct_io)
|
||||
return ::_read_direct_io(fi->fd,buf_,size_,offset_);
|
||||
|
||||
|
|
|
|||
|
|
@ -45,7 +45,6 @@
|
|||
|
||||
#include "config.hpp"
|
||||
#include "fileinfo.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_fadvise.hpp"
|
||||
#include "fuse_passthrough.hpp"
|
||||
|
||||
|
|
@ -111,16 +110,9 @@ FUSE::release(cu64 nodeid_,
|
|||
});
|
||||
|
||||
FUSE::passthrough_close(backing_id);
|
||||
if(fh_fi_to_free)
|
||||
{
|
||||
fs::close(fh_fi_to_free->fd);
|
||||
delete fh_fi_to_free;
|
||||
}
|
||||
if(canonical_fi)
|
||||
{
|
||||
fs::close(canonical_fi->fd);
|
||||
delete canonical_fi;
|
||||
}
|
||||
// Deleting a handle unregisters it before closing its descriptor.
|
||||
delete fh_fi_to_free;
|
||||
delete canonical_fi;
|
||||
}
|
||||
|
||||
int
|
||||
|
|
|
|||
|
|
@ -218,6 +218,7 @@ _statx(const FileInfo *fi_,
|
|||
struct fuse_statx *st_)
|
||||
{
|
||||
int rv;
|
||||
auto lk = fi_->lock_for_attr();
|
||||
|
||||
rv = fs::statx(fi_->fd,
|
||||
"",
|
||||
|
|
|
|||
|
|
@ -18,24 +18,18 @@
|
|||
|
||||
#include "fuse_write.hpp"
|
||||
|
||||
#include "config.hpp"
|
||||
#include "errno.hpp"
|
||||
#include "fileinfo.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_dup2.hpp"
|
||||
#include "fs_movefile_and_open.hpp"
|
||||
#include "fs_pwrite.hpp"
|
||||
#include "fs_pwriten.hpp"
|
||||
#include "ioprio.hpp"
|
||||
#include "moveonenospc.hpp"
|
||||
#include "state.hpp"
|
||||
|
||||
#include "scope_guard/scope_guard.hpp"
|
||||
|
||||
#include "fuse.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
|
||||
|
||||
static
|
||||
bool
|
||||
|
|
@ -62,74 +56,33 @@ _written_or_err(const ssize_t written_,
|
|||
return (((written_ > 0) && short_ok_) ? written_ : err_);
|
||||
}
|
||||
|
||||
// Runs attempt_, which writes what hasn't landed yet and returns its
|
||||
// error, with fi_'s group lock shared. If it runs out of space and a
|
||||
// move could help, retries with the lock exclusive, as another handle
|
||||
// may have completed the move while this one waited, then relocates the
|
||||
// file and tries once more.
|
||||
template<typename AttemptFn>
|
||||
static
|
||||
int
|
||||
_move_and_pwrite(const char *buf_,
|
||||
const size_t count_,
|
||||
const off_t offset_,
|
||||
FileInfo *fi_,
|
||||
int err_)
|
||||
void
|
||||
_write_or_relocate(FileInfo *fi_,
|
||||
AttemptFn attempt_)
|
||||
{
|
||||
int err;
|
||||
ssize_t rv;
|
||||
ssize_t err;
|
||||
|
||||
if(cfg.moveonenospc.enabled == false)
|
||||
return err_;
|
||||
{
|
||||
auto slk = fi_->lock_for_change();
|
||||
err = attempt_();
|
||||
}
|
||||
|
||||
rv = fs::movefile_and_open_as_root(cfg.moveonenospc.policy,
|
||||
cfg.branches,
|
||||
fi_->branch.path,
|
||||
fi_->fusepath,
|
||||
fi_->fd);
|
||||
if(rv < 0)
|
||||
return err_;
|
||||
if(not ::_out_of_space(err))
|
||||
return;
|
||||
|
||||
err = fs::dup2(rv,fi_->fd);
|
||||
fs::close(rv);
|
||||
if(err < 0)
|
||||
return err_;
|
||||
auto ulk = moveonenospc::lock_for_move(fi_);
|
||||
if(not ulk.owns_lock())
|
||||
return;
|
||||
|
||||
return fs::pwrite(fi_->fd,buf_,count_,offset_);
|
||||
}
|
||||
|
||||
static
|
||||
int
|
||||
_move_and_pwriten(char const *buf_,
|
||||
size_t const count_,
|
||||
off_t const offset_,
|
||||
FileInfo *fi_,
|
||||
ssize_t const err_,
|
||||
ssize_t const written_,
|
||||
bool const short_ok_)
|
||||
{
|
||||
int err;
|
||||
ssize_t rv;
|
||||
|
||||
if(cfg.moveonenospc.enabled == false)
|
||||
return ::_written_or_err(written_,err_,short_ok_);
|
||||
|
||||
rv = fs::movefile_and_open_as_root(cfg.moveonenospc.policy,
|
||||
cfg.branches,
|
||||
fi_->branch.path,
|
||||
fi_->fusepath,
|
||||
fi_->fd);
|
||||
if(rv < 0)
|
||||
return ::_written_or_err(written_,err_,short_ok_);
|
||||
|
||||
err = fs::dup2(rv,fi_->fd);
|
||||
fs::close(rv);
|
||||
if(err < 0)
|
||||
return ::_written_or_err(written_,err_,short_ok_);
|
||||
|
||||
rv = fs::pwriten(fi_->fd,
|
||||
buf_ + written_,
|
||||
count_ - written_,
|
||||
offset_ + written_,
|
||||
&err);
|
||||
if(err < 0)
|
||||
return ::_written_or_err(written_ + rv,err,short_ok_);
|
||||
|
||||
return (written_ + rv);
|
||||
if(::_out_of_space(attempt_()) && (moveonenospc::relocate(fi_) == 0))
|
||||
attempt_();
|
||||
}
|
||||
|
||||
// When in direct_io mode write's return value should match that of
|
||||
|
|
@ -158,68 +111,45 @@ _write(const fuse_req_ctx_t *ctx_,
|
|||
if(not fi)
|
||||
return -EBADF;
|
||||
|
||||
// Concurrent writes can only happen if:
|
||||
// 1) writeback-cache is enabled and using page caching
|
||||
// 2) parallel_direct_writes is enabled and file has
|
||||
// `direct_io=true`
|
||||
|
||||
ssize_t rv;
|
||||
const bool short_ok = not ffi_->writepage;
|
||||
|
||||
// Writeback must complete or fail regardless of the handle's cache
|
||||
// mode. A direct handle therefore takes the full-write path whenever
|
||||
// this request is a kernel page-cache flush rather than an application
|
||||
// write, for which a positive short count remains valid.
|
||||
if(fi->direct_io && !ffi_->writepage)
|
||||
{
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> slk(fi->mutex);
|
||||
rv = fs::pwrite(fi->fd,buf_,count_,offset_);
|
||||
}
|
||||
ssize_t rv;
|
||||
|
||||
if(not ::_out_of_space(rv))
|
||||
return rv;
|
||||
::_write_or_relocate(fi,
|
||||
[&]()
|
||||
{
|
||||
rv = fs::pwrite(fi->fd,buf_,count_,offset_);
|
||||
return rv;
|
||||
});
|
||||
|
||||
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
|
||||
// Re-check under exclusive lock: another writer may have
|
||||
// already moved the file and retired. If so the pwrite should
|
||||
// now succeed without our own move call.
|
||||
rv = fs::pwrite(fi->fd,buf_,count_,offset_);
|
||||
if(::_out_of_space(rv))
|
||||
rv = ::_move_and_pwrite(buf_,count_,offset_,fi,rv);
|
||||
return rv;
|
||||
}
|
||||
else
|
||||
{
|
||||
int err;
|
||||
ssize_t written;
|
||||
|
||||
{
|
||||
std::shared_lock<std::shared_mutex> slk(fi->mutex);
|
||||
written = fs::pwriten(fi->fd,buf_,count_,offset_,&err);
|
||||
}
|
||||
int err;
|
||||
ssize_t written = 0;
|
||||
const bool short_ok = not ffi_->writepage;
|
||||
|
||||
if(err == 0)
|
||||
return written;
|
||||
if(not ::_out_of_space(err))
|
||||
return ::_written_or_err(written,err,short_ok);
|
||||
// Each attempt writes only the suffix which hasn't landed yet:
|
||||
// replaying a written prefix would duplicate it on O_APPEND handles.
|
||||
::_write_or_relocate(fi,
|
||||
[&]()
|
||||
{
|
||||
written += fs::pwriten(fi->fd,
|
||||
buf_ + written,
|
||||
count_ - written,
|
||||
offset_ + written,
|
||||
&err);
|
||||
return err;
|
||||
});
|
||||
|
||||
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
|
||||
// Re-check the remaining suffix under exclusive lock as another move
|
||||
// may have already run. Replaying a written prefix would duplicate
|
||||
// data on O_APPEND handles.
|
||||
written += fs::pwriten(fi->fd,
|
||||
buf_ + written,
|
||||
count_ - written,
|
||||
offset_ + written,
|
||||
&err);
|
||||
if(err == 0)
|
||||
return written;
|
||||
if(not ::_out_of_space(err))
|
||||
return ::_written_or_err(written,err,short_ok);
|
||||
if(err == 0)
|
||||
return written;
|
||||
|
||||
return ::_move_and_pwriten(buf_,count_,offset_,fi,err,written,short_ok);
|
||||
}
|
||||
return ::_written_or_err(written,err,short_ok);
|
||||
}
|
||||
|
||||
int
|
||||
|
|
|
|||
297
src/moveonenospc.cpp
Normal file
297
src/moveonenospc.cpp
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
/*
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#include "moveonenospc.hpp"
|
||||
|
||||
#include "config.hpp"
|
||||
#include "errno.hpp"
|
||||
#include "fs_close.hpp"
|
||||
#include "fs_dup2.hpp"
|
||||
#include "fs_fstat.hpp"
|
||||
#include "fs_getfl.hpp"
|
||||
#include "fs_is_same_file.hpp"
|
||||
#include "fs_movefile.hpp"
|
||||
#include "fs_open_fd.hpp"
|
||||
#include "rename_exdev_staging.hpp"
|
||||
#include "state.hpp"
|
||||
#include "syslog.hpp"
|
||||
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
#include <sys/resource.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
|
||||
// A move cannot switch the handles of another node of the same file
|
||||
// (see fileinfo.hpp): they would stay on the original and their writes
|
||||
// would be lost. Refuse while any other node has the file st_
|
||||
// describes open.
|
||||
//
|
||||
// An entry's canonical descriptor keeps its number while the entry
|
||||
// exists, so reading it needs no lock, and the entry can be neither
|
||||
// erased nor its canonical freed while it is being visited. This costs
|
||||
// an fstat per open file, paid only by a relocation, which already
|
||||
// copies the whole file.
|
||||
static
|
||||
int
|
||||
_open_through_other_node(const FileInfo::Shared *shared_,
|
||||
const struct stat &st_)
|
||||
{
|
||||
const bool no_other_node = state.open_files.cvisit_while([&](const auto &v_)
|
||||
{
|
||||
struct stat other;
|
||||
const FileInfo *fi = v_.second.fi;
|
||||
|
||||
if(fi->shared.get() == shared_)
|
||||
return true;
|
||||
if(fs::fstat(fi->fd,&other) < 0)
|
||||
return true;
|
||||
|
||||
return !fs::same_inode(other,st_);
|
||||
});
|
||||
|
||||
return (no_other_node ? 0 : -EBUSY);
|
||||
}
|
||||
|
||||
// One transaction for every handle of the trigger's node. Preparation
|
||||
// retains handles_mutex through commit: release() can erase the
|
||||
// node-map entry, but cannot unregister and free a handle whose pointer
|
||||
// is in entries. Locking is described in fileinfo.hpp.
|
||||
//
|
||||
// refusal() holds every reason to refuse the move. check() runs it
|
||||
// before the copy, so a lasting reason doesn't cost a copy on every
|
||||
// ENOSPC write, and prepare() again once every handle is prepared, as
|
||||
// late as possible before the unlink.
|
||||
struct RebindTransaction final : public fs::MoveHooks
|
||||
{
|
||||
struct Entry
|
||||
{
|
||||
FileInfo *fi;
|
||||
int fd;
|
||||
fs::path branchpath;
|
||||
// The trigger's fusepath, for a handle recorded under another name.
|
||||
fs::path fusepath;
|
||||
};
|
||||
|
||||
explicit
|
||||
RebindTransaction(const FileInfo *trigger_)
|
||||
: trigger(trigger_),
|
||||
shared(*trigger_->shared)
|
||||
{
|
||||
}
|
||||
|
||||
~RebindTransaction()
|
||||
{
|
||||
// Before commit these are provisional destination fds. Afterwards
|
||||
// they have been duplicated onto the handles' own descriptor
|
||||
// numbers. Closing them never touches the handles.
|
||||
for(Entry &entry : entries)
|
||||
if(entry.fd >= 0)
|
||||
fs::close(entry.fd);
|
||||
}
|
||||
|
||||
// Every reason to refuse the move. Caller holds handles_mutex.
|
||||
int
|
||||
refusal() const
|
||||
{
|
||||
int rv;
|
||||
struct stat st;
|
||||
struct rlimit rl;
|
||||
|
||||
// An entry staged by the rename-exdev fallback is reachable through a
|
||||
// published replacement symlink pointing into it, and staged trees
|
||||
// carry their own rollback bookkeeping: moving one would strand the
|
||||
// published name.
|
||||
if(rename_exdev::is_staged(trigger->fusepath))
|
||||
return -EPERM;
|
||||
|
||||
rv = fs::fstat(trigger->fd,&st);
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
// A move 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. A link made after
|
||||
// this check changes ctime, which movefile checks just before the
|
||||
// unlink.
|
||||
if(st.st_nlink != 1)
|
||||
return -EPERM;
|
||||
|
||||
// dup2 fails with EBADF when the target number is at or above the
|
||||
// soft descriptor limit, which can have been lowered since a handle
|
||||
// was opened.
|
||||
rv = ::getrlimit(RLIMIT_NOFILE,&rl);
|
||||
if(rv < 0)
|
||||
return -errno;
|
||||
for(const FileInfo *fi : shared.handles)
|
||||
if((rlim_t)fi->fd >= rl.rlim_cur)
|
||||
return -EMFILE;
|
||||
|
||||
return ::_open_through_other_node(&shared,st);
|
||||
}
|
||||
|
||||
int
|
||||
check() final
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shared.handles_mutex);
|
||||
|
||||
return refusal();
|
||||
}
|
||||
|
||||
// Preparation allocates after publication. Allocation failure takes
|
||||
// the mover's ordinary rollback path rather than letting an exception
|
||||
// strand a destination which blocks every later attempt.
|
||||
int
|
||||
prepare(const int dstfd_,
|
||||
const fs::path &branchpath_) noexcept final
|
||||
{
|
||||
try
|
||||
{
|
||||
return _prepare(dstfd_,branchpath_);
|
||||
}
|
||||
catch(const std::bad_alloc&)
|
||||
{
|
||||
return -ENOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
commit() noexcept final
|
||||
{
|
||||
// Only dup2 and allocation-free swaps remain after the irreversible
|
||||
// unlink. dup2 onto a descriptor that is open and below the limit
|
||||
// checked in prepare cannot fail on Linux or FreeBSD; should one
|
||||
// fail anyway that handle stays on the original and is counted so
|
||||
// relocate can report it.
|
||||
for(Entry &entry : entries)
|
||||
{
|
||||
if(fs::dup2(entry.fd,entry.fi->fd) < 0)
|
||||
{
|
||||
unswitched++;
|
||||
trigger_unswitched |= (entry.fi == trigger);
|
||||
continue;
|
||||
}
|
||||
entry.fi->branch.path.swap(entry.branchpath);
|
||||
if(!entry.fusepath.empty())
|
||||
entry.fi->fusepath.swap(entry.fusepath);
|
||||
}
|
||||
|
||||
attr_lock.unlock();
|
||||
handles_lock.unlock();
|
||||
}
|
||||
|
||||
// The handle whose write triggered the move; its pending request keeps
|
||||
// it alive.
|
||||
const FileInfo *trigger;
|
||||
FileInfo::Shared &shared;
|
||||
std::vector<Entry> entries;
|
||||
std::unique_lock<std::mutex> handles_lock;
|
||||
std::unique_lock<RWLock> attr_lock;
|
||||
unsigned unswitched = 0;
|
||||
bool trigger_unswitched = false;
|
||||
|
||||
private:
|
||||
int
|
||||
_prepare(const int dstfd_,
|
||||
const fs::path &branchpath_)
|
||||
{
|
||||
int flags;
|
||||
int fd;
|
||||
int rv;
|
||||
|
||||
handles_lock = std::unique_lock<std::mutex>(shared.handles_mutex);
|
||||
|
||||
entries.reserve(shared.handles.size());
|
||||
for(FileInfo *fi : shared.handles)
|
||||
{
|
||||
// Allocate and copy everything commit needs before the source
|
||||
// unlink. An entry with fd == -1 owns nothing on an error exit.
|
||||
entries.push_back({fi,-1,branchpath_,{}});
|
||||
|
||||
// The trigger's fusepath is the file's surviving name: the
|
||||
// relocation keeps it on the destination branch and removes the
|
||||
// source. A handle opened under a name since renamed away gets
|
||||
// its own copy of it here, as commit must not allocate.
|
||||
if(fi->fusepath != trigger->fusepath)
|
||||
entries.back().fusepath = trigger->fusepath;
|
||||
|
||||
flags = fs::getfl(fi->fd);
|
||||
if(flags < 0)
|
||||
return flags;
|
||||
fd = fs::open_fd(dstfd_,flags);
|
||||
if(fd < 0)
|
||||
return fd;
|
||||
entries.back().fd = fd;
|
||||
}
|
||||
|
||||
// A node that opened the file during the copy, or a link made since,
|
||||
// also refuses the move; the mover's failure path then removes the
|
||||
// published copy.
|
||||
rv = refusal();
|
||||
if(rv < 0)
|
||||
return rv;
|
||||
|
||||
// From the source unlink until commit the handles still describe
|
||||
// the original, which then reports st_nlink 0. Hold attribute
|
||||
// readers off for that window only.
|
||||
attr_lock = std::unique_lock<RWLock>(shared.attr_lock);
|
||||
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
std::unique_lock<RWLock>
|
||||
moveonenospc::lock_for_move(const FileInfo *fi_)
|
||||
{
|
||||
if(!fi_->shared || !cfg.moveonenospc.policy())
|
||||
return {};
|
||||
|
||||
return std::unique_lock<RWLock>(fi_->shared->lock);
|
||||
}
|
||||
|
||||
int
|
||||
moveonenospc::relocate(FileInfo *fi_)
|
||||
{
|
||||
int rv;
|
||||
|
||||
// The enable state and policy are one snapshot: setxattr can change
|
||||
// the option while this relocation runs.
|
||||
const Policy::Create policy = cfg.moveonenospc.policy();
|
||||
if(!policy)
|
||||
return -ENOSPC;
|
||||
|
||||
RebindTransaction transaction(fi_);
|
||||
|
||||
rv = fs::movefile(policy,
|
||||
cfg.branches,
|
||||
fi_->branch.path,
|
||||
fi_->fusepath,
|
||||
fi_->fd,
|
||||
transaction);
|
||||
if(transaction.unswitched != 0)
|
||||
SysLog::crit("moveonenospc: {} handle(s) of '{}' could not be switched"
|
||||
" to the relocated copy and still write to the unlinked original",
|
||||
transaction.unswitched,
|
||||
fi_->fusepath.string());
|
||||
// The retried write must not land in the unlinked original.
|
||||
if(transaction.trigger_unswitched)
|
||||
return -EIO;
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
|
@ -18,26 +18,27 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "branches.hpp"
|
||||
#include "fs_path.hpp"
|
||||
#include "policy.hpp"
|
||||
#include "fileinfo.hpp"
|
||||
#include "rwlock.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
|
||||
namespace fs
|
||||
// Relocation of a file whose write ran out of space. The handle group
|
||||
// and its locks are described in fileinfo.hpp.
|
||||
namespace moveonenospc
|
||||
{
|
||||
int
|
||||
movefile_and_open(const Policy::Create &policy,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath,
|
||||
const fs::path &fusepath,
|
||||
const int origfd);
|
||||
// fi's group lock taken exclusively, if a move could relieve its
|
||||
// ENOSPC: its node has a group and moveonenospc is still enabled.
|
||||
// Otherwise an empty lock, so a write that can't be relocated doesn't
|
||||
// hold off every handle's writes.
|
||||
std::unique_lock<RWLock>
|
||||
lock_for_move(const FileInfo *fi);
|
||||
|
||||
// Copy the file fi writes to onto a branch with room, remove the
|
||||
// source and switch every handle of fi's group to the copy. Call with
|
||||
// the lock above held. Returns 0 once fi writes to the copy, else a
|
||||
// negative errno.
|
||||
int
|
||||
movefile_and_open_as_root(const Policy::Create &policy,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath,
|
||||
const fs::path &fusepath,
|
||||
int origfd);
|
||||
relocate(FileInfo *fi);
|
||||
}
|
||||
|
|
@ -276,9 +276,18 @@ _postprocess_and_print_warnings()
|
|||
cfg.cache_writeback = false;
|
||||
}
|
||||
|
||||
if(cfg.moveonenospc.enabled == true)
|
||||
// A file opened with a passthrough backing ID is never relocated.
|
||||
if(cfg.moveonenospc.policy())
|
||||
{
|
||||
SysLog::warning("'moveonenospc' will not function when 'passthrough' is enabled");
|
||||
if(cfg.passthrough_io == PassthroughIO::ENUM::RO)
|
||||
SysLog::warning("'moveonenospc' will not relocate files first opened"
|
||||
" read-only while 'passthrough.io=ro'");
|
||||
else if(cfg.passthrough_io == PassthroughIO::ENUM::WO)
|
||||
SysLog::warning("'moveonenospc' will not relocate files first opened"
|
||||
" write-only while 'passthrough.io=wo'");
|
||||
else
|
||||
SysLog::warning("'moveonenospc' will not relocate files"
|
||||
" while 'passthrough.io=rw'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "fs_path.hpp"
|
||||
#include "str.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
// Branch-relative directory where the rename-exdev fallback stages an
|
||||
|
|
@ -27,4 +30,13 @@
|
|||
namespace rename_exdev
|
||||
{
|
||||
static const std::string STAGING_DIR = ".mergerfs_rename_exdev";
|
||||
|
||||
inline
|
||||
bool
|
||||
is_staged(const fs::path &fusepath_)
|
||||
{
|
||||
static const std::string prefix = STAGING_DIR + '/';
|
||||
|
||||
return str::startswith(fusepath_.native(),prefix);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
79
src/rwlock.hpp
Normal file
79
src/rwlock.hpp
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <shared_mutex>
|
||||
|
||||
|
||||
/*
|
||||
Writer-preferring reader/writer lock.
|
||||
|
||||
A pending exclusive acquisition gates new shared acquisitions, while
|
||||
existing shared holders drain. It is usable with std::unique_lock and
|
||||
std::shared_lock. As with other writer-preferring locks, the shared
|
||||
side must not be acquired recursively: a waiting writer would then
|
||||
deadlock against the same thread's first shared acquisition.
|
||||
*/
|
||||
class RWLock
|
||||
{
|
||||
public:
|
||||
RWLock() = default;
|
||||
RWLock(const RWLock&) = delete;
|
||||
RWLock& operator=(const RWLock&) = delete;
|
||||
|
||||
public:
|
||||
void
|
||||
lock()
|
||||
{
|
||||
_writers.fetch_add(1);
|
||||
_rwlock.lock();
|
||||
}
|
||||
|
||||
void
|
||||
unlock()
|
||||
{
|
||||
_rwlock.unlock();
|
||||
if(_writers.fetch_sub(1) == 1)
|
||||
_writers.notify_all();
|
||||
}
|
||||
|
||||
void
|
||||
lock_shared()
|
||||
{
|
||||
int writers;
|
||||
|
||||
while((writers = _writers.load()) != 0)
|
||||
_writers.wait(writers);
|
||||
|
||||
_rwlock.lock_shared();
|
||||
}
|
||||
|
||||
void
|
||||
unlock_shared()
|
||||
{
|
||||
_rwlock.unlock_shared();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_mutex _rwlock;
|
||||
// Exclusive lockers waiting for or holding _rwlock. On its own cache
|
||||
// line: shared lockers only read it, while they all write _rwlock.
|
||||
alignas(64) std::atomic<int> _writers = 0;
|
||||
};
|
||||
|
|
@ -18,10 +18,23 @@
|
|||
|
||||
#include "state.hpp"
|
||||
|
||||
#include "config.hpp"
|
||||
#include "errno.hpp"
|
||||
|
||||
State state;
|
||||
|
||||
bool
|
||||
State::insert_open_file(const u64 nodeid_,
|
||||
const int backing_id_,
|
||||
FileInfo * const fi_)
|
||||
{
|
||||
// A passthrough ID stays on the original file and cannot be switched.
|
||||
if(!fuse_backing_id_is_valid(backing_id_) && cfg.moveonenospc.policy())
|
||||
fi_->make_movable();
|
||||
|
||||
return open_files.try_emplace(nodeid_,backing_id_,fi_);
|
||||
}
|
||||
|
||||
// static
|
||||
// void
|
||||
// _register_getattr(State *state_)
|
||||
|
|
|
|||
|
|
@ -137,6 +137,16 @@ public:
|
|||
return fi;
|
||||
}
|
||||
|
||||
// Publishes fi_, the first handle of nodeid_, with the passthrough
|
||||
// backing ID its open was given. A node that can be relocated by
|
||||
// moveonenospc gets its group here, before any other thread can
|
||||
// reach fi_ (see fileinfo.hpp). False if another open inserted the
|
||||
// node first.
|
||||
bool
|
||||
insert_open_file(const u64 nodeid_,
|
||||
const int backing_id_,
|
||||
FileInfo * const fi_);
|
||||
|
||||
public:
|
||||
struct GetSet
|
||||
{
|
||||
|
|
|
|||
|
|
@ -4,21 +4,26 @@ 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):
|
||||
|
|
@ -30,9 +35,10 @@ class SubcaseSkip(Exception):
|
|||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def enospc_pool(options, extra_tmpfs=()):
|
||||
def enospc_pool(options, extra_tmpfs=(), destination_size=None):
|
||||
"""Mount mergerfs over `source`, the `extra_tmpfs` (name, size)
|
||||
branches and an unconstrained `destination`, in that order.
|
||||
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,
|
||||
|
|
@ -47,7 +53,10 @@ def enospc_pool(options, extra_tmpfs=()):
|
|||
mounted_tmpfs = []
|
||||
mounted = False
|
||||
try:
|
||||
for name, size in [("source", "1m")] + list(extra_tmpfs):
|
||||
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,
|
||||
|
|
@ -82,21 +91,8 @@ def enospc_pool(options, extra_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 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):
|
||||
|
|
@ -104,6 +100,157 @@ def read_file(path):
|
|||
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,
|
||||
|
|
@ -283,6 +430,738 @@ def test_occupied_destination():
|
|||
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
|
||||
|
|
@ -342,6 +1221,19 @@ TESTS = (test_partial_append,
|
|||
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)
|
||||
|
||||
|
||||
|
|
|
|||
130
tests/tests.cpp
130
tests/tests.cpp
|
|
@ -5,7 +5,8 @@
|
|||
#include "fs_clonepath.hpp"
|
||||
#include "fs_copyfile.hpp"
|
||||
#include "fs_inode.hpp"
|
||||
#include "fs_movefile_and_open.hpp"
|
||||
#include "fs_movefile.hpp"
|
||||
#include "fs_open_fd.hpp"
|
||||
#include "fs_statvfs_cache.hpp"
|
||||
#include "from_string.hpp"
|
||||
#include "fuse_link.hpp"
|
||||
|
|
@ -16,6 +17,7 @@
|
|||
#include "hashset.hpp"
|
||||
#include "num.hpp"
|
||||
#include "policies.hpp"
|
||||
#include "procfs.hpp"
|
||||
#include "rapidhash/rapidhash.h"
|
||||
#include "rnd.hpp"
|
||||
#include "scope_guard/scope_guard.hpp"
|
||||
|
|
@ -70,8 +72,11 @@ test_direct_handle_writepage_error()
|
|||
TEST_ASSERT(::setrlimit(RLIMIT_FSIZE,&limit) == 0);
|
||||
DEFER { ::setrlimit(RLIMIT_FSIZE,&saved); };
|
||||
|
||||
// The handle owns its descriptor; the file keeps its own.
|
||||
const int handle_fd = ::dup(fd);
|
||||
TEST_ASSERT(handle_fd >= 0);
|
||||
Branch branch;
|
||||
FileInfo fi(fd,branch,"file",true);
|
||||
FileInfo fi(handle_fd,branch,"file",true);
|
||||
fuse_req_ctx_t ctx = {};
|
||||
fuse_file_info_t ffi = {};
|
||||
ffi.fh = fi.to_fh();
|
||||
|
|
@ -1445,14 +1450,22 @@ test_config_moveonenospc()
|
|||
{
|
||||
MoveOnENOSPC m(false);
|
||||
|
||||
TEST_CHECK(!m.policy());
|
||||
TEST_CHECK(m.to_string() == "false");
|
||||
TEST_CHECK(m.from_string("mfs") == 0);
|
||||
TEST_CHECK(m.policy());
|
||||
TEST_CHECK(m.to_string() == "mfs");
|
||||
TEST_CHECK(m.from_string("mspmfs") == 0);
|
||||
TEST_CHECK(m.to_string() == "mspmfs");
|
||||
TEST_CHECK(m.from_string("true") == 0);
|
||||
TEST_CHECK(m.to_string() == "pfrd");
|
||||
TEST_CHECK(m.from_string("blah") == -EINVAL);
|
||||
// An invalid value must leave the previous setting in force.
|
||||
TEST_CHECK(m.policy());
|
||||
TEST_CHECK(m.to_string() == "pfrd");
|
||||
TEST_CHECK(m.from_string("false") == 0);
|
||||
TEST_CHECK(!m.policy());
|
||||
TEST_CHECK(m.to_string() == "false");
|
||||
}
|
||||
|
||||
void
|
||||
|
|
@ -4036,6 +4049,61 @@ test_fs_copyfile_source_changes_cleanup_tmpfiles()
|
|||
std::filesystem::remove_all(tmp_dir);
|
||||
}
|
||||
|
||||
// Opens a read-write descriptor of the copy and switches nothing.
|
||||
struct ReopenCopyHooks final : public fs::MoveHooks
|
||||
{
|
||||
int
|
||||
check() final
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
prepare(const int dstfd_,
|
||||
const fs::path &) noexcept final
|
||||
{
|
||||
fd = fs::open_fd(dstfd_,O_RDWR);
|
||||
return ((fd < 0) ? fd : 0);
|
||||
}
|
||||
|
||||
void
|
||||
commit() noexcept final
|
||||
{
|
||||
}
|
||||
|
||||
int fd = -1;
|
||||
};
|
||||
|
||||
// Move the file fd_ describes and return a read-write descriptor of
|
||||
// the copy, or a negative errno.
|
||||
static
|
||||
int
|
||||
_movefile_fd(const Policy::Create &policy_,
|
||||
const Branches::Ptr &branches_,
|
||||
const fs::path &branchpath_,
|
||||
const fs::path &fusepath_,
|
||||
const int fd_)
|
||||
{
|
||||
int rv;
|
||||
ReopenCopyHooks hooks;
|
||||
|
||||
// fs::open_fd reopens through /proc/self/fd on Linux.
|
||||
#ifdef __linux__
|
||||
procfs::init();
|
||||
DEFER { procfs::shutdown(); };
|
||||
#endif
|
||||
|
||||
rv = fs::movefile(policy_,branches_,branchpath_,fusepath_,fd_,hooks);
|
||||
if(rv < 0)
|
||||
{
|
||||
if(hooks.fd >= 0)
|
||||
::close(hooks.fd);
|
||||
return rv;
|
||||
}
|
||||
|
||||
return hooks.fd;
|
||||
}
|
||||
|
||||
static
|
||||
std::string
|
||||
_file_contents(const fs::path &path_)
|
||||
|
|
@ -4048,6 +4116,51 @@ _file_contents(const fs::path &path_)
|
|||
return contents.str();
|
||||
}
|
||||
|
||||
void
|
||||
test_fs_movefile_direct_io()
|
||||
{
|
||||
// A disk-backed /tmp and a tmpfs destination exercise the read/write
|
||||
// fallback when the filesystems cannot clone or use copy_file_range.
|
||||
if(::access("/dev/shm",W_OK|X_OK) < 0)
|
||||
return;
|
||||
char src_dir[] = "/tmp/mergerfs-test-direct-XXXXXX";
|
||||
char dst_dir[] = "/dev/shm/mergerfs-test-direct-XXXXXX";
|
||||
if(!TEST_CHECK(::mkdtemp(src_dir) != nullptr))
|
||||
return;
|
||||
DEFER { std::filesystem::remove_all(src_dir); };
|
||||
if(!TEST_CHECK(::mkdtemp(dst_dir) != nullptr))
|
||||
return;
|
||||
DEFER { std::filesystem::remove_all(dst_dir); };
|
||||
|
||||
const fs::path src = fs::path(src_dir) / "file";
|
||||
const fs::path dst = fs::path(dst_dir) / "file";
|
||||
const std::string data = "direct I/O relocation\n";
|
||||
std::ofstream(src,std::ios::binary) << data;
|
||||
const int fd = ::open(src.c_str(),O_RDWR|O_DIRECT);
|
||||
if((fd < 0) && ((errno == EINVAL) || (errno == EOPNOTSUPP)))
|
||||
return;
|
||||
if(!TEST_CHECK(fd >= 0))
|
||||
return;
|
||||
DEFER { ::close(fd); };
|
||||
|
||||
Branches branches;
|
||||
branches.minfreespace = 0;
|
||||
if(!TEST_CHECK(branches.from_string(std::string(src_dir) + ":" + dst_dir) == 0))
|
||||
return;
|
||||
const Policy::Create ff(&Policies::Create::ff);
|
||||
const int moved = ::_movefile_fd(ff,branches,src_dir,"file",fd);
|
||||
if(!TEST_CHECK(moved >= 0))
|
||||
{
|
||||
TEST_MSG("movefile: %d",moved);
|
||||
return;
|
||||
}
|
||||
::close(moved);
|
||||
TEST_CHECK(!std::filesystem::exists(src));
|
||||
TEST_CHECK(_file_contents(dst) == data);
|
||||
const int flags = ::fcntl(fd,F_GETFL);
|
||||
TEST_CHECK((flags >= 0) && (flags & O_DIRECT));
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -4055,7 +4168,7 @@ _file_contents(const fs::path &path_)
|
|||
// 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()
|
||||
test_fs_movefile_same_branch()
|
||||
{
|
||||
char tmp_template[] = "/tmp/mergerfs-test-movefile-same-XXXXXX";
|
||||
if(::mkdtemp(tmp_template) == nullptr)
|
||||
|
|
@ -4115,7 +4228,7 @@ test_fs_movefile_and_open_same_branch()
|
|||
ptr->front().path = first_;
|
||||
ptr->back().path = second_;
|
||||
|
||||
return fs::movefile_and_open(ff,ptr,src,"file",fd);
|
||||
return ::_movefile_fd(ff,ptr,src,"file",fd);
|
||||
};
|
||||
|
||||
// Every branch is the source: refused, file left alone.
|
||||
|
|
@ -4158,7 +4271,7 @@ test_fs_movefile_and_open_same_branch()
|
|||
// 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()
|
||||
test_fs_movefile_existing_path_policies()
|
||||
{
|
||||
char tmp_template[] = "/tmp/mergerfs-test-movefile-ep-XXXXXX";
|
||||
if(::mkdtemp(tmp_template) == nullptr)
|
||||
|
|
@ -4216,7 +4329,7 @@ test_fs_movefile_and_open_existing_path_policies()
|
|||
TEST_CHECK(branches.from_string(src.string() + ":" + other.string()) == 0);
|
||||
Branches::Ptr ptr = branches;
|
||||
|
||||
rv = fs::movefile_and_open(policy,ptr,src,relpath,fd);
|
||||
rv = ::_movefile_fd(policy,ptr,src,relpath,fd);
|
||||
TEST_CHECK(rv >= 0);
|
||||
TEST_MSG("policy: %s; path: %s; rv: %d",entry.name,relpath,rv);
|
||||
if(rv >= 0)
|
||||
|
|
@ -5080,8 +5193,9 @@ 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},
|
||||
{"fs_movefile_same_branch",test_fs_movefile_same_branch},
|
||||
{"fs_movefile_direct_io",test_fs_movefile_direct_io},
|
||||
{"fs_movefile_existing_path_policies",test_fs_movefile_existing_path_policies},
|
||||
{"direct_handle_writepage_error",test_direct_handle_writepage_error},
|
||||
{"readdir_factory_rejects_oversized_counts",test_readdir_factory_rejects_oversized_counts},
|
||||
{"statvfs_cache_failure_not_served_as_success",test_statvfs_cache_failure_not_served_as_success},
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue