qos: match on cmdline, and never throttle critical dependencies

Two gaps found while using this against a real media server.

Some programs do very different jobs under one name. Plex runs credits
detection with the same 'Plex Transcoder' binary that serves playback,
reading the same file, so neither comm nor path separates them. Adds a
cmdline match field, and quoting so a pattern can contain spaces --
without which 'Plex Transcoder' cannot be written down at all.

Adds a 'critical' class flag for services playback synchronously waits
on. Plex's EasyAudioEncoder is the case: a transcode of EAC3 audio
writes to EAE and blocks. Such a helper looks like background work, so
a governor protecting playback will throttle or suspend it and hang the
stream waiting behind it. A critical class is never delayed.

Also fixes qos.max-sleepers auto-sizing, which read the requested
thread count rather than the resolved one and so capped at 1.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Grioghar 2026-09-09 17:21:57 -05:00
parent 34e57dbb8a
commit 5f6275baea
19 changed files with 2608 additions and 194 deletions

314
tools/mergerfs.qos-bench Executable file
View file

@ -0,0 +1,314 @@
#!/usr/bin/env python3
"""
Measure the throughput of each branch in a mergerfs pool and emit the
`capacity` lines a QoS ruleset needs to turn percentage rates into
numbers.
A percentage rate ("give the scanner 10% of this disk") is meaningless
until something knows what 100% is. This measures it.
Defaults are chosen to be safe to run against a pool that is in use:
* Reads only. No file is created or modified unless --allow-write is
given, and nothing is ever written into the pool itself.
* O_DIRECT, so the measurement neither reads stale numbers out of the
page cache nor evicts anything the running services still want.
The system-wide cache is never dropped.
* Idle I/O priority and nice 19, so a benchmark that collides with
playback yields rather than competes. Note this also means the
number produced is a floor when the pool is busy -- for a true
ceiling, measure when it is quiet.
* Short samples (3s per branch by default).
"""
import argparse
import ctypes
import errno
import mmap
import os
import random
import sys
import time
BLOCK = 4 * 1024 * 1024 # O_DIRECT reads must be sector aligned
MIN_PROBE_SIZE = 256 * 1024 * 1024
MAX_SCAN_ENTRIES = 20000
IOPRIO_WHO_PROCESS = 1
IOPRIO_CLASS_IDLE = 3
IOPRIO_CLASS_SHIFT = 13
def be_polite():
"""Drop to idle I/O priority and nice 19."""
try:
os.nice(19)
except OSError:
pass
try:
libc = ctypes.CDLL("libc.so.6", use_errno=True)
libc.syscall(251, IOPRIO_WHO_PROCESS, 0,
IOPRIO_CLASS_IDLE << IOPRIO_CLASS_SHIFT)
except Exception:
pass
def human(n):
for unit in ("B", "K", "M", "G", "T"):
if n < 1024 or unit == "T":
return f"{n:.0f}{unit}" if unit == "B" else f"{n:.1f}{unit}"
n /= 1024.0
def branches_of(mountpoint):
"""Read the branch list out of a live mergerfs mount."""
try:
raw = os.getxattr(os.path.join(mountpoint, ".mergerfs"),
"user.mergerfs.branches")
except OSError as e:
sys.exit(f"{mountpoint}: cannot read branch list: {e}")
out = []
for spec in raw.decode().split(":"):
# Each entry is <path>=<mode>; mode is irrelevant here.
out.append(spec.split("=", 1)[0])
return out
def find_probe_file(branch, min_size):
"""
Find one file big enough to read a sample from.
Walks breadth-first with a hard cap on entries examined; on a 14TB
disk of media the first large file turns up almost immediately, and
the cap keeps a pathological layout from turning this into a full
tree walk.
"""
seen = 0
queue = [branch]
while queue:
d = queue.pop(0)
try:
with os.scandir(d) as it:
for entry in it:
seen += 1
if seen > MAX_SCAN_ENTRIES:
return None
try:
if entry.is_symlink():
continue
if entry.is_dir():
queue.append(entry.path)
elif entry.is_file():
if entry.stat().st_size >= min_size:
return entry.path
except OSError:
continue
except OSError:
continue
return None
def measure_read(path, duration, block=BLOCK):
"""
Sequential O_DIRECT read from a random aligned offset.
Returns bytes/sec, or None if the file could not be read directly.
"""
try:
fd = os.open(path, os.O_RDONLY | os.O_DIRECT)
except OSError as e:
if e.errno in (errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP):
return None
raise
try:
size = os.fstat(fd).st_size
if size < block * 2:
return None
# Start somewhere other than the front of the file so repeated
# runs do not all measure the same tracks.
span = size - block
start = random.randrange(0, max(1, span // block)) * block
buf = mmap.mmap(-1, block) # mmap is page aligned
total = 0
offset = start
deadline = time.monotonic() + duration
t0 = time.monotonic()
while time.monotonic() < deadline:
if offset + block > size:
offset = 0
n = os.preadv(fd, [buf], offset)
if n <= 0:
break
total += n
offset += block
elapsed = time.monotonic() - t0
buf.close()
if elapsed <= 0 or total == 0:
return None
return total / elapsed
finally:
os.close(fd)
def measure_write(branch, duration, block=BLOCK):
"""Sequential O_DIRECT write to a temp file on the branch."""
path = os.path.join(branch, f".mergerfs-qos-bench.{os.getpid()}")
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_DIRECT, 0o600)
except OSError as e:
print(f" write: cannot create probe file: {e}", file=sys.stderr)
return None
try:
buf = mmap.mmap(-1, block)
buf.write(os.urandom(65536) * (block // 65536))
total = 0
deadline = time.monotonic() + duration
t0 = time.monotonic()
while time.monotonic() < deadline:
n = os.pwritev(fd, [buf], total)
if n <= 0:
break
total += n
elapsed = time.monotonic() - t0
buf.close()
if elapsed <= 0 or total == 0:
return None
return total / elapsed
finally:
os.close(fd)
try:
os.unlink(path)
except OSError:
pass
def main():
ap = argparse.ArgumentParser(
description="Measure per-branch throughput for a mergerfs QoS ruleset.")
ap.add_argument("target",
help="a mergerfs mountpoint, or one or more branch paths")
ap.add_argument("extra", nargs="*",
help="additional branch paths")
ap.add_argument("-d", "--duration", type=float, default=3.0,
help="seconds to sample each branch (default: 3)")
ap.add_argument("-o", "--output",
help="write the capacity block to this file instead of stdout")
ap.add_argument("--write", action="store_true",
help="also measure write throughput (creates a temp file "
"on each branch)")
ap.add_argument("--allow-write", action="store_true",
help="permit creating a probe file when no existing file "
"is large enough to read from")
ap.add_argument("--min-size", type=int, default=MIN_PROBE_SIZE,
help="smallest file usable as a read probe, in bytes")
ap.add_argument("--full-speed", action="store_true",
help="do not lower this process's priority; measures the "
"true ceiling but competes with live traffic")
args = ap.parse_args()
if not args.full_speed:
be_polite()
# A single argument that is a mergerfs mount means "discover the
# branches yourself".
if not args.extra and os.path.exists(os.path.join(args.target, ".mergerfs")):
branches = branches_of(args.target)
print(f"# discovered {len(branches)} branches via {args.target}",
file=sys.stderr)
else:
branches = [args.target] + args.extra
results = {}
for branch in branches:
if not os.path.isdir(branch):
print(f"{branch}: not a directory, skipping", file=sys.stderr)
continue
print(f"{branch}:", file=sys.stderr, flush=True)
probe = find_probe_file(branch, args.min_size)
created = None
if probe is None:
if not args.allow_write:
print(f" no file >= {human(args.min_size)} found; "
f"skipping (use --allow-write to create a probe file)",
file=sys.stderr)
continue
created = os.path.join(branch, f".mergerfs-qos-probe.{os.getpid()}")
try:
with open(created, "wb") as f:
chunk = os.urandom(1 << 20)
for _ in range(args.min_size >> 20):
f.write(chunk)
f.flush()
os.fsync(f.fileno())
probe = created
except OSError as e:
print(f" cannot create probe file: {e}", file=sys.stderr)
continue
try:
rd = measure_read(probe, args.duration)
if rd is None:
print(" read: O_DIRECT unavailable or file too small",
file=sys.stderr)
else:
print(f" read: {human(rd)}/s (probe: {probe})",
file=sys.stderr)
results[branch] = rd
if args.write:
wr = measure_write(branch, args.duration)
if wr is not None:
print(f" write: {human(wr)}/s", file=sys.stderr)
finally:
if created:
try:
os.unlink(created)
except OSError:
pass
if not results:
sys.exit("no branches could be measured")
lines = ["# generated by mergerfs.qos-bench on "
+ time.strftime("%Y-%m-%d %H:%M:%S"),
"# read throughput, O_DIRECT, "
f"{args.duration:g}s sample per branch"]
if not args.full_speed:
lines.append("# measured at idle priority: treat as a floor if the "
"pool was busy")
for branch, rate in results.items():
lines.append(f"capacity {branch} {int(rate)}")
total = sum(results.values())
lines.append(f"capacity default {int(total / len(results))}")
block = "\n".join(lines) + "\n"
if args.output:
with open(args.output, "w") as f:
f.write(block)
print(f"\nwrote {args.output}", file=sys.stderr)
else:
sys.stdout.write(block)
if __name__ == "__main__":
main()

324
tools/mergerfs.qos-playback-test Executable file
View file

@ -0,0 +1,324 @@
#!/usr/bin/env python3
"""
Prove that playback survives competing load -- or show exactly where it
does not.
A rate limit that looks right in a config file is worth nothing if a
film still stutters. This models a player: it reads a real file out of
the pool at a fixed bitrate through a jitter buffer, and counts the
moments the buffer ran dry, which is what a viewer experiences as a
stutter. It can start and stop competing bulk load partway through, so
one run shows three things at once:
1. baseline -- what the buffer does with the pool to itself
2. contended -- whether bulk load empties it, and how far pressure
had to rise to stop that
3. recovery -- whether the yielding classes climb back to full speed
once playback ends
Both the player and the load generator rename themselves, so a ruleset
can classify them by name:
class playback protect ioprio=rt:0
class bulk yield=100 floor=5% ioprio=idle
match comm = qos-playback -> playback
match comm = qos-bulk -> bulk
"""
import argparse
import ctypes
import os
import statistics
import sys
import threading
import time
CHUNK = 1 << 20
PR_SET_NAME = 15
def set_comm(name):
"""Rename this thread so mergerfs QoS rules can match on comm."""
try:
libc = ctypes.CDLL("libc.so.6", use_errno=True)
libc.prctl(PR_SET_NAME, ctypes.c_char_p(name.encode()[:15]), 0, 0, 0)
except Exception:
pass
def human(n):
for unit in ("B", "K", "M", "G"):
if n < 1024 or unit == "G":
return f"{n:.1f}{unit}"
n /= 1024.0
def parse_size(s):
s = s.strip()
mult = 1
if s and s[-1] in "kKmMgG":
mult = {"k": 1024, "m": 1024 ** 2, "g": 1024 ** 3}[s[-1].lower()]
s = s[:-1]
return int(float(s) * mult)
class Player:
"""
Reads `path` at `bitrate`, keeping a jitter buffer topped up.
The buffer is the whole point: a player does not care how fast a
read was, only whether the next frame was there in time. Every
moment the buffer hits zero is a stutter.
"""
def __init__(self, path, bitrate, buffer_secs):
self.path = path
self.bitrate = bitrate
self.target = int(bitrate * buffer_secs)
self.underruns = 0
self.min_buffer = self.target
self.latencies = []
self.bytes_read = 0
self.stop = threading.Event()
self.samples = [] # (t, buffer_bytes)
def run(self):
set_comm("qos-playback")
fd = os.open(self.path, os.O_RDONLY)
size = os.fstat(fd).st_size
offset = 0
start = time.monotonic()
# Prefilled, as a player would be after it starts.
fetched = self.target
in_underrun = False
try:
while not self.stop.is_set():
now = time.monotonic()
elapsed = now - start
consumed = elapsed * self.bitrate
buffer = fetched - consumed
self.min_buffer = min(self.min_buffer, buffer)
self.samples.append((elapsed, buffer))
if buffer <= 0:
# The buffer is empty: the viewer is looking at a
# spinner. Count it once per drain, not once per
# loop iteration.
if not in_underrun:
self.underruns += 1
in_underrun = True
else:
in_underrun = False
if buffer >= self.target:
# Buffer is full; a real player would idle here
# rather than race ahead.
time.sleep(0.005)
continue
if offset + CHUNK > size:
offset = 0
t0 = time.monotonic()
data = os.pread(fd, CHUNK, offset)
dt = time.monotonic() - t0
if not data:
offset = 0
continue
self.latencies.append(dt)
fetched += len(data)
self.bytes_read += len(data)
offset += len(data)
finally:
os.close(fd)
class Bulk:
"""A greedy reader, standing in for a download or a library scan."""
def __init__(self, path):
self.path = path
self.bytes_read = 0
self.stop = threading.Event()
def run(self):
set_comm("qos-bulk")
fd = os.open(self.path, os.O_RDONLY)
size = os.fstat(fd).st_size
offset = 0
try:
while not self.stop.is_set():
if offset + CHUNK > size:
offset = 0
data = os.pread(fd, CHUNK, offset)
if not data:
offset = 0
continue
self.bytes_read += len(data)
offset += len(data)
finally:
os.close(fd)
def read_pressure(mountpoint):
"""Pull the governor's view out of the live mount."""
if not mountpoint:
return {}
try:
raw = os.getxattr(os.path.join(mountpoint, ".mergerfs"),
"user.mergerfs.qos.stats").decode()
except OSError:
return {}
out = {}
for line in raw.splitlines():
if line.startswith("resource "):
name = line.split()[1].rstrip(":")
fields = dict(f.split("=", 1) for f in line.split() if "=" in f)
out[name] = fields
return out
def main():
ap = argparse.ArgumentParser(
description="Measure whether playback survives competing pool load.")
ap.add_argument("file", help="a media file inside the pool to play")
ap.add_argument("--bulk-file", action="append", default=[],
help="file for a competing bulk reader (repeatable)")
ap.add_argument("-b", "--bitrate", default="25M",
help="playback bitrate, e.g. 25M (default: 25M)")
ap.add_argument("--buffer", type=float, default=5.0,
help="jitter buffer in seconds (default: 5)")
ap.add_argument("-d", "--duration", type=float, default=60.0,
help="total run time in seconds (default: 60)")
ap.add_argument("--bulk-start", type=float, default=10.0,
help="when to start the bulk load (default: 10s)")
ap.add_argument("--bulk-stop", type=float, default=None,
help="when to stop it (default: 10s before the end)")
ap.add_argument("-m", "--mount",
help="mergerfs mountpoint, to report governor pressure")
args = ap.parse_args()
bitrate = parse_size(args.bitrate)
bulk_stop = (args.bulk_stop if args.bulk_stop is not None
else max(args.bulk_start, args.duration - 10.0))
if not args.bulk_file:
args.bulk_file = [args.file]
# Check up front: a missing file would otherwise surface as a
# traceback from a worker thread while the run carried on
# reporting zero bulk load, which reads like a passing test.
for path in [args.file] + args.bulk_file:
if not os.path.isfile(path):
sys.exit(f"{path}: not a file")
player = Player(args.file, bitrate, args.buffer)
pthread = threading.Thread(target=player.run, daemon=True)
print(f"playing {args.file} at {human(bitrate)}/s "
f"with a {args.buffer:g}s buffer for {args.duration:g}s")
print(f"bulk load: {len(args.bulk_file)} reader(s), "
f"{args.bulk_start:g}s -> {bulk_stop:g}s\n")
print(f"{'t':>6} {'phase':<10} {'buffer':>9} {'play':>10} {'bulk':>10} "
f"{'pressure':>9} {'under':>6}")
pthread.start()
bulks = []
bthreads = []
started = False
stopped = False
t0 = time.monotonic()
last_play = 0
last_bulk = 0
last_t = 0.0
while True:
now = time.monotonic() - t0
if now >= args.duration:
break
if (not started) and (now >= args.bulk_start):
for bf in args.bulk_file:
b = Bulk(bf)
t = threading.Thread(target=b.run, daemon=True)
bulks.append(b)
bthreads.append(t)
t.start()
started = True
if started and (not stopped) and (now >= bulk_stop):
for b in bulks:
b.stop.set()
stopped = True
time.sleep(1.0)
now = time.monotonic() - t0
dt = max(1e-9, now - last_t)
play_total = player.bytes_read
bulk_total = sum(b.bytes_read for b in bulks)
play_rate = (play_total - last_play) / dt
bulk_rate = (bulk_total - last_bulk) / dt
last_play, last_bulk, last_t = play_total, bulk_total, now
buffer = player.samples[-1][1] if player.samples else 0
press = read_pressure(args.mount)
# Report the most-pressured resource; that is the one doing the
# protecting.
pval = "-"
if press:
vals = []
for f in press.values():
try:
vals.append(float(f.get("pressure", 0)))
except ValueError:
pass
if vals:
pval = f"{max(vals):.2f}"
phase = ("baseline" if not started
else ("recovery" if stopped else "contended"))
print(f"{now:6.0f} {phase:<10} {human(max(0,buffer)):>9} "
f"{human(play_rate)+'/s':>10} {human(bulk_rate)+'/s':>10} "
f"{pval:>9} {player.underruns:>6}")
player.stop.set()
for b in bulks:
b.stop.set()
pthread.join(timeout=5)
print()
lat = sorted(player.latencies)
if lat:
def pct(p):
return lat[min(len(lat) - 1, int(len(lat) * p))] * 1000
print(f"read latency: median {statistics.median(lat)*1000:.1f}ms "
f"p95 {pct(0.95):.1f}ms p99 {pct(0.99):.1f}ms "
f"max {lat[-1]*1000:.1f}ms")
print(f"buffer low-water: {human(max(0,player.min_buffer))} "
f"of {human(player.target)}")
print(f"underruns (stutters): {player.underruns}")
# A stutter is the only failure that matters here.
sys.exit(1 if player.underruns else 0)
if __name__ == "__main__":
main()