Initial import of the existing CephFS subvolume migration prototype, including the native libcephfs transport, rsync backend, local Ceph lab environment and integration tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
269 lines
12 KiB
Python
269 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Space-conscious, application-side many-small-files migration benchmark."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import stat
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
|
|
def ceph(cluster, *args):
|
|
return subprocess.check_output([
|
|
"ceph", "-c", f"/clusters/{cluster}/ceph.conf", "-k",
|
|
f"/clusters/{cluster}/ceph.client.admin.keyring", *args], text=True).strip()
|
|
|
|
|
|
def volume(cluster, *args):
|
|
return ceph(cluster, "fs", "subvolume", *args, "--group_name", "migration")
|
|
|
|
|
|
def snap(cluster, *args):
|
|
return volume(cluster, "snapshot", *args)
|
|
|
|
|
|
def relative(i, count):
|
|
return f"flat/f{i:08d}" if i < count // 2 else f"tree/b{i % 50:02d}/f{i:08d}"
|
|
|
|
|
|
def payload(i, version):
|
|
return hashlib.sha256(f"{i}:{version}".encode()).digest() * 4
|
|
|
|
|
|
def posix_acl():
|
|
entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff),
|
|
(16, 4, 0xffffffff), (32, 0, 0xffffffff)]
|
|
return struct.pack("<I", 2) + b"".join(struct.pack("<HHI", *e) for e in entries)
|
|
|
|
|
|
def stop_child(process):
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=10)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait()
|
|
|
|
|
|
def attrs(p):
|
|
return {k: os.getxattr(p, k, follow_symlinks=False)
|
|
for k in os.listxattr(p, follow_symlinks=False) if not k.startswith("ceph.")}
|
|
|
|
|
|
def compare(source, target, label="live"):
|
|
print(f"verifying {label}", file=sys.stderr, flush=True)
|
|
forward, backward = {}, {}
|
|
checked = 0
|
|
|
|
def visit(a, b):
|
|
nonlocal checked
|
|
x, y = os.lstat(a), os.lstat(b)
|
|
if (x.st_mode, x.st_uid, x.st_gid, x.st_mtime_ns) != (
|
|
y.st_mode, y.st_uid, y.st_gid, y.st_mtime_ns):
|
|
raise AssertionError(f"metadata mismatch: {a}")
|
|
if attrs(a) != attrs(b):
|
|
raise AssertionError(f"xattr mismatch: {a}")
|
|
if stat.S_ISDIR(x.st_mode):
|
|
with os.scandir(a) as entries:
|
|
names = {e.name for e in entries if e.name != ".snap"}
|
|
with os.scandir(b) as entries:
|
|
other = {e.name for e in entries if e.name != ".snap"}
|
|
if names != other:
|
|
raise AssertionError(f"directory inventory mismatch: {a}")
|
|
for name in names:
|
|
visit(os.path.join(a, name), os.path.join(b, name))
|
|
else:
|
|
if forward.setdefault(x.st_ino, y.st_ino) != y.st_ino:
|
|
raise AssertionError(f"hardlink split: {a}")
|
|
if backward.setdefault(y.st_ino, x.st_ino) != x.st_ino:
|
|
raise AssertionError(f"unrelated files hardlinked: {a}")
|
|
if stat.S_ISREG(x.st_mode):
|
|
if x.st_size != y.st_size or x.st_size != 128:
|
|
raise AssertionError(f"size mismatch: {a}")
|
|
if Path(a).read_bytes() != Path(b).read_bytes():
|
|
raise AssertionError(f"content mismatch: {a}")
|
|
checked += 1
|
|
elif stat.S_ISLNK(x.st_mode):
|
|
if os.readlink(a) != os.readlink(b):
|
|
raise AssertionError(f"symlink mismatch: {a}")
|
|
else:
|
|
raise AssertionError(f"unexpected file type: {a}")
|
|
visit(source, target)
|
|
print(f"verified {label}: {checked} regular file paths", file=sys.stderr, flush=True)
|
|
return checked
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument("action", choices=["setup", "mutate", "verify", "cleanup", "run"])
|
|
p.add_argument("name", nargs="?")
|
|
p.add_argument("--count", type=int, default=10000)
|
|
p.add_argument("--phase", choices=["initial", "catchup", "final"])
|
|
p.add_argument("--binary", default=os.environ.get("CEPHMIG_BENCH_BINARY", "/usr/local/bin/cephmig-native"))
|
|
p.add_argument("--timeout", type=int, default=1800)
|
|
args = p.parse_args()
|
|
name = args.name or "smallfiles-" + str(uuid.uuid4())
|
|
if not name.startswith("smallfiles-") or str(uuid.UUID(name[11:])) != name[11:]:
|
|
raise ValueError("not a smallfiles fixture name")
|
|
work = Path("/state") / name
|
|
config, journal = work / "config.json", work / "job.json"
|
|
if args.action == "setup":
|
|
if not 100 <= args.count <= 50000 or args.count % 100:
|
|
raise ValueError("count must be a multiple of 100, from 100 to 50000")
|
|
print(f"creating fixture {name}, count={args.count}", file=sys.stderr)
|
|
# A conservative allowance for object allocation, metadata and snapshot
|
|
# history, plus an untouched reserve. This is a guard, not a capacity model.
|
|
required = (1 << 30) + args.count * (64 << 10)
|
|
for cluster in ("source", "target"):
|
|
capacity = json.loads(ceph(cluster, "df", "--format", "json"))
|
|
if capacity["stats"]["total_avail_bytes"] < required:
|
|
raise RuntimeError(f"{cluster}: insufficient estimated space budget including reserve; "
|
|
"reduce --count; no fixture created")
|
|
work.mkdir(mode=0o700)
|
|
for cluster in ("source", "target"):
|
|
volume(cluster, "create", "cephfs", name)
|
|
roots = {c: f"/mnt/{c}-fs" + volume(c, "getpath", "cephfs", name)
|
|
for c in ("source", "target")}
|
|
(work / "fixture.json").write_text(json.dumps(dict(roots=roots, count=args.count)))
|
|
c = json.loads(Path("/lab/migration.example.json").read_text())
|
|
c.update(backend="native", workers=4, bandwidth_kib=0)
|
|
for endpoint in ("source", "target"):
|
|
c[endpoint]["subvolume"] = name
|
|
c[endpoint].pop("mount", None)
|
|
config.write_text(json.dumps(c))
|
|
root = Path(roots["source"])
|
|
(root / "flat").mkdir()
|
|
(root / "tree").mkdir()
|
|
(root / "links").mkdir()
|
|
for i in range(50):
|
|
(root / "tree" / f"b{i:02d}").mkdir()
|
|
os.setxattr(root / "tree" / "b00", "system.posix_acl_default", posix_acl())
|
|
for i in range(args.count):
|
|
f = root / relative(i, args.count)
|
|
f.write_bytes(payload(i, 0))
|
|
if i == 0:
|
|
os.chown(f, 12345, 23456)
|
|
os.setxattr(f, "system.posix_acl_access", posix_acl())
|
|
if i % 100 == 4:
|
|
os.setxattr(f, "user.remove", b"original")
|
|
if i < 100:
|
|
os.link(f, root / "links" / f"hard{i:03d}")
|
|
os.symlink("../" + relative(i, args.count), root / "links" / f"soft{i:03d}")
|
|
snap("source", "create", "cephfs", name, "baseline")
|
|
print(name)
|
|
return
|
|
if args.name is None:
|
|
raise ValueError("existing fixture name is required")
|
|
fixture = json.loads((work / "fixture.json").read_text())
|
|
count, roots = fixture["count"], fixture["roots"]
|
|
if args.action == "mutate":
|
|
root = Path(roots["source"])
|
|
for i in range(count):
|
|
f = root / relative(i, count)
|
|
if i % 100 == 0:
|
|
previous = f.stat()
|
|
f.write_bytes(payload(i, 1))
|
|
os.utime(f, ns=(previous.st_atime_ns, previous.st_mtime_ns))
|
|
elif i % 100 == 1:
|
|
f.unlink()
|
|
elif i % 100 == 2:
|
|
f.rename(f.with_name(f.name + "-renamed"))
|
|
elif i % 100 == 3:
|
|
os.chmod(f, 0o640)
|
|
os.setxattr(f, "user.generation", b"1")
|
|
elif i % 100 == 4:
|
|
os.removexattr(f, "user.remove")
|
|
for i in range(count // 100):
|
|
(root / "flat" / f"new{i:08d}").write_bytes(payload(i, 2))
|
|
elif args.action == "run":
|
|
if args.phase is None:
|
|
raise ValueError("--phase required")
|
|
if args.timeout <= 0 or not os.path.isabs(args.binary):
|
|
raise ValueError("positive timeout and absolute binary path required")
|
|
command = [args.binary,
|
|
"finalize" if args.phase == "final" else "sync",
|
|
"--config", str(config), "--state", str(journal)]
|
|
if args.phase == "final":
|
|
command.append("--writers-stopped")
|
|
started = time.monotonic()
|
|
wall_started = time.time()
|
|
last_progress = started
|
|
peak_rss = 0
|
|
with (work / f"{args.phase}.stdout.json").open("w") as out, (
|
|
work / f"{args.phase}.log").open("w") as log:
|
|
process = subprocess.Popen(command, stdout=out, stderr=log)
|
|
while process.poll() is None:
|
|
try:
|
|
for line in Path(f"/proc/{process.pid}/status").read_text().splitlines():
|
|
if line.startswith(("VmRSS:", "VmHWM:")):
|
|
peak_rss = max(peak_rss, int(line.split()[1]))
|
|
except FileNotFoundError:
|
|
pass
|
|
now = time.monotonic()
|
|
if now - started > args.timeout:
|
|
stop_child(process)
|
|
raise RuntimeError("benchmark phase timed out; fixture retained")
|
|
if abs((time.time() - wall_started) - (now - started)) > 5:
|
|
stop_child(process)
|
|
raise RuntimeError("host suspend or clock jump detected; discard timing and rerun")
|
|
if now - last_progress >= 30:
|
|
print(f"{args.phase}: elapsed={now - started:.0f}s "
|
|
f"native_peak_rss={peak_rss / 1024:.1f} MiB",
|
|
file=sys.stderr, flush=True)
|
|
last_progress = now
|
|
time.sleep(0.1)
|
|
elapsed = time.monotonic() - started
|
|
if process.returncode:
|
|
print((work / f"{args.phase}.log").read_text(), file=sys.stderr)
|
|
raise RuntimeError(f"migration exited {process.returncode}")
|
|
state = json.loads(journal.read_text())
|
|
if not all(x["done"] for x in state["snapshots"]):
|
|
raise AssertionError("unfinished snapshot")
|
|
if args.phase == "final" and (state["phase"] != "ready-for-cutover" or
|
|
state["snapshots"][-1]["transfer"]["bytes_copied"] != 0):
|
|
raise AssertionError("finalization must finish without rewriting unchanged data")
|
|
result = dict(phase=args.phase, seconds=round(elapsed, 3),
|
|
native_peak_rss_kib=peak_rss,
|
|
rounds=[dict(name=x["name"], **x["transfer"]) for x in state["snapshots"]])
|
|
(work / f"{args.phase}.metrics.json").write_text(json.dumps(result, indent=2))
|
|
print(json.dumps(result), flush=True)
|
|
elif args.action == "verify":
|
|
state = json.loads(journal.read_text())
|
|
started = time.monotonic()
|
|
checked = compare(roots["source"], roots["target"])
|
|
if checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4:
|
|
raise AssertionError("unexpected file count or incomplete migration")
|
|
snapshots = []
|
|
for s in state["snapshots"]:
|
|
a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath",
|
|
"cephfs", name, s["name"], "migration") for c in ("source", "target")]
|
|
snapshot_checked = compare(a, b, s["name"])
|
|
if snapshot_checked != count + 100:
|
|
raise AssertionError(f"unexpected snapshot file count: {s['name']}")
|
|
snapshots.append(dict(name=s["name"], files_checked=snapshot_checked))
|
|
result = dict(live_files_checked=checked, snapshots=snapshots,
|
|
seconds=round(time.monotonic() - started, 3))
|
|
(work / "verification.json").write_text(json.dumps(result, indent=2))
|
|
print(json.dumps(result))
|
|
elif args.action == "cleanup":
|
|
for cluster in ("source", "target"):
|
|
for s in json.loads(snap(cluster, "ls", "cephfs", name)):
|
|
snap(cluster, "rm", "cephfs", name, s["name"])
|
|
volume(cluster, "rm", "cephfs", name, "--force")
|
|
claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest()
|
|
try:
|
|
os.unlink("/mnt/target-fs/.cephmig/claims/" + claim)
|
|
except FileNotFoundError:
|
|
pass
|
|
shutil.rmtree(work)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|