mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
fix: keep readdir listings stable under fill errors
- func.readdir=cor appended entries in whichever order branch workers finished. Directory offsets are positions in that list, so a reader reopening an unchanged directory and seeking to a previously issued cookie (NFS does this) could see a duplicate and miss a later entry. Read branches concurrently into their own buffers, then merge and deduplicate them in configured branch order. The merge mutex is gone. - Growing a dirents buffer overwrote the only pointer with realloc's result while recording the new capacity, so an allocation failure leaked the buffer and the next fill wrote through NULL. Grow both vectors without changing pointer, length or capacity until the allocation succeeds, and return ENOMEM. - seq and cosr ignored that failure and served a listing with entries missing. Every policy now returns the error, and libfuse resets the handle's buffer whenever a fill fails, so a later request at a nonzero offset re-enumerates instead of serving a partial or stale listing as success. cosr closes the directories its workers opened when it gives up early. - Document the fill-error contract, which doesn't promise that every branch was read: seq and cosr can treat a branch read error as the end of the directory. Document cor's memory use, and refer to func.getattr, not fuse.getattr. - TEST_readdir_cor_cookie_replay compares cor listings, offsets and inodes with seq and replays cookies on fresh handles. TEST_dirents_allocation injects allocation failures into the dirents code. TEST_readdir_cor_enomem fails one allocation in a mounted daemon for cor and seq and checks the same handle then serves the exact suffix. Performance: cor copies each entry twice and merges serially after the parallel reads. Listing 100,000 entries over 4 tmpfs branches took the same time before and after (81-83 ms per listing for cor:4 and seq). Peak daemon memory for cor:4 dropped from 27.4 MB to 18.7 MB.
This commit is contained in:
parent
b367b593ba
commit
eea1c1bc09
15 changed files with 1026 additions and 79 deletions
230
tests/TEST_dirents_allocation
Executable file
230
tests/TEST_dirents_allocation
Executable file
|
|
@ -0,0 +1,230 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Deterministic allocation-failure regression for the fuse_dirents layer.
|
||||
|
||||
Compiles the real vendored/libfuse/lib/fuse_dirents.cpp with a small C++
|
||||
harness and -Wl,--wrap=realloc/--wrap=free, failing one exact call: the
|
||||
initial reservation (NULL old pointer), the next data-buffer growth
|
||||
(>= 32KiB quantum), or the next offset-table growth (< 32KiB). No mount,
|
||||
no branches; disposable work dir under tests/.test_tmp. A failed call
|
||||
must return -ENOMEM once and leave the added entries intact, verified by
|
||||
name, inode and cookie (d->off == index + 1), never by pointers,
|
||||
capacities or padding bytes; a disarmed retry must complete to exactly
|
||||
the never-failed sequence, and a failed init must leave nothing behind.
|
||||
Exit codes: 0 pass, 1 fail, 77 skip (non-Linux or no C++ compiler).
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
SKIP = 77
|
||||
|
||||
HARNESS = r"""
|
||||
#include "fuse_dirents.hpp"
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Data grows in 32KiB quanta; offset-table reallocs stay far below it,
|
||||
so the allocation size discriminates the two vectors. Mode: 1 fails
|
||||
a NULL old pointer (init), 2 the next data growth, 3 the next table
|
||||
growth; each fires once at the Nth matching call. */
|
||||
#define DATA_QUANTUM (1024 * 32)
|
||||
#define NENTRIES 1500
|
||||
|
||||
extern "C" {
|
||||
void *__real_realloc(void *, size_t);
|
||||
void __real_free(void *);
|
||||
}
|
||||
|
||||
static int fail_mode, fail_nth, fail_count;
|
||||
static long live_blocks;
|
||||
static char msg[256];
|
||||
|
||||
static void arm(int mode, int nth) {
|
||||
fail_mode = mode;
|
||||
fail_nth = nth;
|
||||
fail_count = 0;
|
||||
}
|
||||
|
||||
static bool ok(bool cond, const char *what) {
|
||||
if(!cond && !msg[0])
|
||||
snprintf(msg, sizeof(msg), "%s", what);
|
||||
return cond;
|
||||
}
|
||||
|
||||
static int should_fail(void *p, size_t n) {
|
||||
int match;
|
||||
if(fail_mode == 1)
|
||||
match = (p == NULL);
|
||||
else if(fail_mode == 2)
|
||||
match = (p && n >= DATA_QUANTUM);
|
||||
else if(fail_mode == 3)
|
||||
match = (p && n < DATA_QUANTUM);
|
||||
else
|
||||
return 0;
|
||||
if(!match || --fail_nth)
|
||||
return 0;
|
||||
fail_count++;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* A failed realloc leaves the old block alive (no count change); a
|
||||
successful NULL-pointer realloc births one; nonnull moves are net
|
||||
zero. libc internals do not route through these wrappers. */
|
||||
extern "C" void *__wrap_realloc(void *p, size_t n) {
|
||||
void *q;
|
||||
if(should_fail(p, n))
|
||||
return NULL;
|
||||
q = __real_realloc(p, n);
|
||||
if(q && !p)
|
||||
live_blocks++;
|
||||
return q;
|
||||
}
|
||||
|
||||
extern "C" void __wrap_free(void *p) {
|
||||
if(p)
|
||||
live_blocks--;
|
||||
__real_free(p);
|
||||
}
|
||||
|
||||
static bool check_entries(fuse_dirents_t *d, int count, const char *what) {
|
||||
int i;
|
||||
char want[16];
|
||||
if(!ok((int)kv_size(d->offs) == count + 1 && kv_A(d->offs, 0) == 0, what))
|
||||
return false;
|
||||
for(i = 0; i < count; i++) {
|
||||
const fuse_dirent_t *de =
|
||||
(const fuse_dirent_t *)&kv_A(d->data, kv_A(d->offs, i));
|
||||
snprintf(want, sizeof(want), "e%07d", i);
|
||||
if(!ok(de->ino == (uint64_t)i + 1 && de->off == (uint64_t)i + 1 &&
|
||||
de->namelen == 8 && !memcmp(de->name, want, 8), what))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static int add_entry(fuse_dirents_t *d, int idx) {
|
||||
char name[16];
|
||||
alignas(fs::dirent64) char storage[64];
|
||||
fs::dirent64 *de = (fs::dirent64 *)storage;
|
||||
snprintf(name, sizeof(name), "e%07d", idx);
|
||||
memset(storage, 0, sizeof(storage));
|
||||
de->ino = (uint64_t)idx + 1;
|
||||
de->reclen = (uint16_t)(offsetof(fs::dirent64, name) + 9);
|
||||
de->type = DT_REG;
|
||||
memcpy(de->name, name, 9);
|
||||
return fuse_dirents_add(d, de, 8);
|
||||
}
|
||||
|
||||
/* Arm the injector, add until one add fails, verify the survived prefix
|
||||
and that a disarmed retry reaches exactly the never-failed sequence. */
|
||||
static bool growth_scenario(int mode, const char *what) {
|
||||
fuse_dirents_t d;
|
||||
int i, failed_at = -1;
|
||||
if(fuse_dirents_init(&d))
|
||||
return ok(false, "clean init failed");
|
||||
arm(mode, 1);
|
||||
for(i = 0; i < NENTRIES; i++)
|
||||
if(add_entry(&d, i)) { failed_at = i; break; }
|
||||
fail_mode = 0;
|
||||
if(!ok(fail_count == 1, "injected growth failure did not fire exactly once") ||
|
||||
!ok(failed_at > 0, what) ||
|
||||
!check_entries(&d, failed_at, what))
|
||||
return false;
|
||||
for(; i < NENTRIES; i++)
|
||||
if(add_entry(&d, i))
|
||||
return ok(false, "retry add after the failed growth failed");
|
||||
if(!check_entries(&d, NENTRIES, what))
|
||||
return false;
|
||||
fuse_dirents_free(&d);
|
||||
return ok(live_blocks == 0, "dirents allocation leaked");
|
||||
}
|
||||
|
||||
static bool init_failure(void) {
|
||||
fuse_dirents_t d;
|
||||
arm(1, 1);
|
||||
if(!ok(fuse_dirents_init(&d) == -ENOMEM,
|
||||
"init did not return -ENOMEM on its failed initial allocation") ||
|
||||
!ok(fail_count == 1, "init injector did not fire exactly once"))
|
||||
return false;
|
||||
fail_mode = 0;
|
||||
fuse_dirents_free(&d);
|
||||
if(!ok(live_blocks == 0, "failed init left an allocation behind"))
|
||||
return false;
|
||||
if(fuse_dirents_init(&d))
|
||||
return ok(false, "init after a failed init failed");
|
||||
fuse_dirents_free(&d);
|
||||
return ok(live_blocks == 0, "dirents allocation leaked");
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
static char stdout_buf[4096];
|
||||
setvbuf(stdout, stdout_buf, _IOFBF, sizeof(stdout_buf));
|
||||
if(!growth_scenario(2, "no add failed under the armed data-growth injector") ||
|
||||
!growth_scenario(3, "no add failed under the armed offset-growth injector") ||
|
||||
!init_failure()) {
|
||||
printf("FAIL: %s\n", msg);
|
||||
return 1;
|
||||
}
|
||||
printf("PASS\n");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
if not sys.platform.startswith("linux"):
|
||||
print("Linux-only allocation regression; skipping on " + sys.platform)
|
||||
return SKIP
|
||||
compiler = next((shutil.which(c) for c in ("g++", "c++", "clang++")
|
||||
if shutil.which(c)), None)
|
||||
if compiler is None:
|
||||
print("no C++ compiler found; skipping")
|
||||
return SKIP
|
||||
|
||||
tests_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
repo = os.path.dirname(tests_dir)
|
||||
fuse_dirents_cpp = os.path.join(repo, "vendored", "libfuse", "lib",
|
||||
"fuse_dirents.cpp")
|
||||
if not os.path.isfile(fuse_dirents_cpp):
|
||||
print("missing " + fuse_dirents_cpp)
|
||||
return 1
|
||||
|
||||
tmp_parent = os.path.join(tests_dir, ".test_tmp")
|
||||
os.makedirs(tmp_parent, exist_ok=True)
|
||||
workdir = tempfile.mkdtemp(prefix="dirents_allocation_",
|
||||
dir=tmp_parent)
|
||||
try:
|
||||
harness_cpp = os.path.join(workdir, "harness.cpp")
|
||||
binary = os.path.join(workdir, "test_dirents_allocation")
|
||||
with open(harness_cpp, "w", encoding="ascii") as stream:
|
||||
stream.write(HARNESS)
|
||||
compiled = subprocess.run(
|
||||
[compiler, "-std=c++20", "-O2", "-fno-builtin",
|
||||
"-D_FILE_OFFSET_BITS=64",
|
||||
"-I" + os.path.join(repo, "vendored", "libfuse", "include"),
|
||||
"-I" + os.path.join(repo, "src"),
|
||||
"-I" + os.path.join(repo, "vendored"),
|
||||
"-Wl,--wrap=realloc", "-Wl,--wrap=free",
|
||||
harness_cpp, fuse_dirents_cpp, "-o", binary],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if compiled.returncode != 0:
|
||||
print("compilation failed:\n" + compiled.stdout)
|
||||
return 1
|
||||
run = subprocess.run(
|
||||
[binary], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
sys.stdout.write(run.stdout)
|
||||
return run.returncode
|
||||
finally:
|
||||
shutil.rmtree(workdir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
200
tests/TEST_readdir_cor_cookie_replay
Executable file
200
tests/TEST_readdir_cor_cookie_replay
Executable file
|
|
@ -0,0 +1,200 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import sys
|
||||
|
||||
from posix_parity import fail
|
||||
from posix_parity import mergerfs_mount
|
||||
from posix_parity import mount_mergerfs
|
||||
from posix_parity import unmount_mergerfs
|
||||
|
||||
|
||||
if not sys.platform.startswith("linux"):
|
||||
print("This Linux dirent ABI test is unsupported on " + sys.platform)
|
||||
raise SystemExit(77)
|
||||
|
||||
|
||||
class Dirent(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("d_ino", ctypes.c_ulong),
|
||||
("d_off", ctypes.c_long),
|
||||
("d_reclen", ctypes.c_ushort),
|
||||
("d_type", ctypes.c_ubyte),
|
||||
("d_name", ctypes.c_char * 256),
|
||||
]
|
||||
|
||||
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
libc.opendir.argtypes = [ctypes.c_char_p]
|
||||
libc.opendir.restype = ctypes.c_void_p
|
||||
libc.readdir.argtypes = [ctypes.c_void_p]
|
||||
libc.readdir.restype = ctypes.POINTER(Dirent)
|
||||
libc.seekdir.argtypes = [ctypes.c_void_p, ctypes.c_long]
|
||||
libc.seekdir.restype = None
|
||||
libc.closedir.argtypes = [ctypes.c_void_p]
|
||||
libc.closedir.restype = ctypes.c_int
|
||||
|
||||
|
||||
def opendir_or_raise(path):
|
||||
ctypes.set_errno(0)
|
||||
dp = libc.opendir(os.fsencode(path))
|
||||
if not dp:
|
||||
err = ctypes.get_errno()
|
||||
raise OSError(err, os.strerror(err), path)
|
||||
return dp
|
||||
|
||||
|
||||
def snapshot(ent):
|
||||
name = bytes(ent.d_name).split(b"\0", 1)[0]
|
||||
return (
|
||||
os.fsdecode(name),
|
||||
int(ent.d_type),
|
||||
int(ent.d_ino),
|
||||
int(ent.d_off),
|
||||
)
|
||||
|
||||
|
||||
def read_one(dp):
|
||||
ctypes.set_errno(0)
|
||||
entp = libc.readdir(dp)
|
||||
if entp:
|
||||
return snapshot(entp.contents)
|
||||
err = ctypes.get_errno()
|
||||
if err:
|
||||
raise OSError(err, os.strerror(err))
|
||||
return None
|
||||
|
||||
|
||||
def read_all(dp):
|
||||
entries = []
|
||||
while True:
|
||||
entry = read_one(dp)
|
||||
if entry is None:
|
||||
return entries
|
||||
entries.append(entry)
|
||||
|
||||
|
||||
def close_dir(dp):
|
||||
if libc.closedir(dp) != 0:
|
||||
err = ctypes.get_errno()
|
||||
raise OSError(err, os.strerror(err))
|
||||
|
||||
|
||||
def read_listing(path):
|
||||
dp = opendir_or_raise(path)
|
||||
try:
|
||||
return read_all(dp)
|
||||
finally:
|
||||
close_dir(dp)
|
||||
|
||||
|
||||
def replay_cookie(path, prefix_length):
|
||||
dp = opendir_or_raise(path)
|
||||
try:
|
||||
prefix = [read_one(dp) for _ in range(prefix_length)]
|
||||
if any(entry is None for entry in prefix):
|
||||
raise RuntimeError("directory ended before the requested replay prefix")
|
||||
cookie = prefix[-1][3]
|
||||
finally:
|
||||
close_dir(dp)
|
||||
|
||||
dp = opendir_or_raise(path)
|
||||
try:
|
||||
ctypes.set_errno(0)
|
||||
libc.seekdir(dp, cookie)
|
||||
err = ctypes.get_errno()
|
||||
if err:
|
||||
raise OSError(err, os.strerror(err))
|
||||
suffix = read_all(dp)
|
||||
finally:
|
||||
close_dir(dp)
|
||||
|
||||
return prefix, cookie, suffix
|
||||
|
||||
|
||||
def first_difference(actual, expected):
|
||||
for index, (got, want) in enumerate(zip(actual, expected)):
|
||||
if got != want:
|
||||
return f"entry {index}: got {got!r}, expected {want!r}"
|
||||
if len(actual) != len(expected):
|
||||
return f"entry count {len(actual)}, expected {len(expected)}"
|
||||
return "unknown difference"
|
||||
|
||||
|
||||
def make_name(prefix, index):
|
||||
return f"{prefix}_{index:05d}_" + "x" * 64
|
||||
|
||||
|
||||
def populate(branches):
|
||||
shared = [make_name("shared", index) for index in range(16)]
|
||||
counts = [4000, 7, 5, 3]
|
||||
|
||||
for branch_index, (branch, count) in enumerate(zip(branches, counts)):
|
||||
dirpath = os.path.join(branch, "dir")
|
||||
os.mkdir(dirpath)
|
||||
names = shared + [make_name(f"branch{branch_index}", index) for index in range(count)]
|
||||
for name in names:
|
||||
with open(os.path.join(dirpath, name), "wb") as stream:
|
||||
stream.write(f"branch{branch_index}\n".encode("ascii"))
|
||||
|
||||
return shared
|
||||
|
||||
|
||||
def main():
|
||||
options = "defaults,use_ino,category.create=mfs,cache.readdir=false"
|
||||
|
||||
try:
|
||||
with mergerfs_mount(
|
||||
num_branches=4,
|
||||
options=options + ",func.readdir=seq",
|
||||
) as (mount, branches):
|
||||
shared = populate(branches)
|
||||
dirpath = os.path.join(mount, "dir")
|
||||
|
||||
expected = read_listing(dirpath)
|
||||
expected_unique = 2 + 16 + 4000 + 7 + 5 + 3
|
||||
if len(expected) != expected_unique:
|
||||
return fail(
|
||||
f"seq fixture has {len(expected)} entries, expected {expected_unique}"
|
||||
)
|
||||
if len({entry[0] for entry in expected}) != len(expected):
|
||||
return fail("seq fixture contains duplicate names")
|
||||
with open(os.path.join(dirpath, shared[0]), "rb") as stream:
|
||||
if stream.read() != b"branch0\n":
|
||||
return fail("duplicate name does not resolve to the first branch")
|
||||
|
||||
unmount_mergerfs(mount)
|
||||
mount_mergerfs(branches, mount, options + ",func.readdir=cor:4")
|
||||
for attempt in range(4):
|
||||
actual = read_listing(dirpath)
|
||||
if actual != expected:
|
||||
return fail(
|
||||
f"cor listing {attempt} differs from seq: "
|
||||
+ first_difference(actual, expected)
|
||||
)
|
||||
|
||||
split_points = [1, 2, 3, 17, 64, 255, 511, 1024, 1536, 2048, 3072]
|
||||
split_points += [len(expected) - 1, len(expected)]
|
||||
for prefix_length in split_points:
|
||||
prefix, cookie, suffix = replay_cookie(dirpath, prefix_length)
|
||||
resumed = prefix + suffix
|
||||
if resumed != expected:
|
||||
return fail(
|
||||
f"fresh-handle replay at cookie {cookie} after "
|
||||
f"{prefix_length} entries differs: "
|
||||
+ first_difference(resumed, expected)
|
||||
)
|
||||
|
||||
return 0
|
||||
except RuntimeError as exc:
|
||||
if "binary not found" in str(exc) or "fusermount" in str(exc):
|
||||
print(str(exc), end="")
|
||||
return 77
|
||||
return fail(str(exc))
|
||||
except OSError as exc:
|
||||
return fail(f"readdir COR cookie replay failed: {exc}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
183
tests/TEST_readdir_cor_enomem
Executable file
183
tests/TEST_readdir_cor_enomem
Executable file
|
|
@ -0,0 +1,183 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Mounted ENOMEM regression for func.readdir=cor and func.readdir=seq.
|
||||
|
||||
The dirents-level failures are covered by TEST_dirents_allocation; this
|
||||
test drives the real daemon, once per policy. A fill that fails partway
|
||||
must be reported as ENOMEM and leave no partial or stale listing cached,
|
||||
so the next read on the SAME handle re-enumerates and serves the exact
|
||||
reference suffix from the requested cookie. Helpers come from the
|
||||
tracked cookie-replay regression via runpy. Only the daemon gets an
|
||||
LD_PRELOAD failing one realloc: old pointer nonnull (not an initial
|
||||
reservation), new size 64KiB (the second 32KiB data quantum of the
|
||||
handle's dirents buffer), on the 'fuse.read' thread, and only while a
|
||||
marker file exists, armed after a clean reference listing and consumed
|
||||
on fire so the recovery fill succeeds. seq is targeted by the same
|
||||
injector because read-thread-count=1 with process-thread-count=-1 runs
|
||||
every request synchronously on 'fuse.read', where seq performs its
|
||||
whole fill and grows the handle buffer in the same 32KiB quanta (its
|
||||
branch scratch buffer is posix_memalign'ed, so it cannot steal the
|
||||
realloc); cor merges into the same buffer there, while its branch
|
||||
scratch buffers grow on 'readdir.cor' workers. Fails (not skips) if the
|
||||
injector never fires or the errno is not ENOMEM.
|
||||
Exit codes: 0 pass, 1 fail, 77 skip.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
SKIP = 77
|
||||
|
||||
HERE = os.path.dirname(os.path.realpath(__file__))
|
||||
_cookie = runpy.run_path(os.path.join(HERE, "TEST_readdir_cor_cookie_replay"))
|
||||
(close_dir, fail, first_difference, libc, mergerfs_mount,
|
||||
opendir_or_raise, populate, read_all, read_one, read_listing) = (
|
||||
_cookie[name] for name in ("close_dir", "fail", "first_difference",
|
||||
"libc", "mergerfs_mount", "opendir_or_raise",
|
||||
"populate", "read_all", "read_one",
|
||||
"read_listing"))
|
||||
|
||||
# Synchronous read thread: both policies grow the handle's shared
|
||||
# dirents buffer there. seq fills it directly on the request thread;
|
||||
# cor merges into it there, not on the readdir.cor branch workers.
|
||||
OPTIONS_TEMPLATE = ("defaults,use_ino,category.create=mfs,cache.readdir=false,"
|
||||
"read-thread-count=1,process-thread-count=-1,"
|
||||
"func.readdir={policy}")
|
||||
|
||||
PRELOAD_C = r"""
|
||||
#define _GNU_SOURCE
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern void *__libc_realloc(void *,size_t);
|
||||
|
||||
/* The open directory handle's dirents buffer grows in 32KiB quanta on
|
||||
the synchronous read thread; its 64KiB growth carries a non-NULL old
|
||||
pointer, unlike the opendir-time init reservation. Both policies
|
||||
grow it there: seq fills it directly, cor merges into it. */
|
||||
#define MERGED_GROWTH ((size_t)(64 * 1024))
|
||||
|
||||
void *
|
||||
realloc(void *ptr_,size_t size_)
|
||||
{
|
||||
if((ptr_ != NULL) && (size_ == MERGED_GROWTH))
|
||||
{
|
||||
const char *marker = getenv("MERGERFS_TEST_COR_ENOMEM_MARKER");
|
||||
char name[16];
|
||||
|
||||
if((marker != NULL) &&
|
||||
(pthread_getname_np(pthread_self(),name,sizeof(name)) == 0) &&
|
||||
(strcmp(name,"fuse.read") == 0) &&
|
||||
(access(marker,F_OK) == 0))
|
||||
{
|
||||
unlink(marker);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
return __libc_realloc(ptr_,size_);
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
if not sys.platform.startswith("linux"):
|
||||
print("Linux-only cor ENOMEM regression; skipping on " + sys.platform)
|
||||
return SKIP
|
||||
if not hasattr(libc, "__libc_realloc"):
|
||||
print("glibc is required for the daemon allocator hook")
|
||||
return SKIP
|
||||
compiler = shutil.which("cc") or shutil.which("gcc")
|
||||
if compiler is None:
|
||||
print("no C compiler for the preload; skipping")
|
||||
return SKIP
|
||||
|
||||
tmp_parent = os.path.join(HERE, ".test_tmp")
|
||||
os.makedirs(tmp_parent, exist_ok=True)
|
||||
tmpdir = tempfile.mkdtemp(prefix="mergerfs_cor_enomem_", dir=tmp_parent)
|
||||
preload = os.path.join(tmpdir, "cor_enomem_preload.so")
|
||||
marker = os.path.join(tmpdir, "cor_enomem_armed")
|
||||
preload_env = os.environ.get("LD_PRELOAD")
|
||||
try:
|
||||
src = os.path.join(tmpdir, "cor_enomem_preload.c")
|
||||
with open(src, "w", encoding="ascii") as stream:
|
||||
stream.write(PRELOAD_C)
|
||||
built = subprocess.run(
|
||||
[compiler, "-O2", "-fPIC", "-shared", src, "-o", preload],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
if built.returncode != 0:
|
||||
return fail("preload compilation failed:\n" + built.stdout)
|
||||
|
||||
os.environ["LD_PRELOAD"] = preload
|
||||
os.environ["MERGERFS_TEST_COR_ENOMEM_MARKER"] = marker
|
||||
try:
|
||||
for policy in ("cor:4", "seq"):
|
||||
rv = injected_run(marker, policy)
|
||||
if rv != 0:
|
||||
return rv
|
||||
return 0
|
||||
except RuntimeError as exc:
|
||||
if ("binary not found" in str(exc)) or ("fusermount" in str(exc)):
|
||||
print(str(exc), end="")
|
||||
return SKIP
|
||||
return fail(str(exc))
|
||||
except OSError as exc:
|
||||
return fail("cor ENOMEM regression failed: %s" % exc)
|
||||
finally:
|
||||
if preload_env is None:
|
||||
os.environ.pop("LD_PRELOAD", None)
|
||||
else:
|
||||
os.environ["LD_PRELOAD"] = preload_env
|
||||
os.environ.pop("MERGERFS_TEST_COR_ENOMEM_MARKER", None)
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def injected_run(marker, policy):
|
||||
options = OPTIONS_TEMPLATE.format(policy=policy)
|
||||
with mergerfs_mount(num_branches=4, options=options) as (mount, branches):
|
||||
dirpath = os.path.join(mount, "dir")
|
||||
populate(branches)
|
||||
|
||||
truth = read_listing(dirpath)
|
||||
if len(truth) < 4:
|
||||
return fail("reference listing has only %d entries" % len(truth))
|
||||
if len({entry[0] for entry in truth}) != len(truth):
|
||||
return fail("reference listing contains duplicate names")
|
||||
mid = len(truth) // 2
|
||||
cookie = truth[mid][3]
|
||||
expected_suffix = truth[(mid + 1):]
|
||||
|
||||
with open(marker, "w", encoding="ascii"):
|
||||
pass
|
||||
|
||||
dp = opendir_or_raise(dirpath)
|
||||
try:
|
||||
libc.seekdir(dp, cookie)
|
||||
try:
|
||||
first = read_one(dp)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.ENOMEM:
|
||||
return fail("injected failure reported errno %s, "
|
||||
"expected ENOMEM" % exc.errno)
|
||||
else:
|
||||
return fail("injector never fired: the seeked readdir "
|
||||
"returned %r" % (first,))
|
||||
suffix = read_all(dp)
|
||||
finally:
|
||||
close_dir(dp)
|
||||
|
||||
if suffix != expected_suffix:
|
||||
return fail("after ENOMEM the same handle served a wrong "
|
||||
"suffix: " + first_difference(suffix, expected_suffix))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue