Files
CephfsMig/dev/native-fixture.py
T
Sebastian UnterschützandClaude Opus 5.5 330a3ec12c feat!: remove the rsync backend
The native libcephfs backend is the only transfer path. The rsync
transport, the mounted-filesystem access and its helpers (mount check,
path resolution below a mount, mount claim, quota and hardlink repair
through the mount) are removed, together with the rsync lab test and
the client image that only added rsync.

The claim and release tests now exercise the native claim through a
local test file system with real flock locks.

BREAKING CHANGE: "backend": "rsync" and the endpoint field "mount" are
rejected. "backend" is optional and only accepts "native"; jobs created
with "native" resume without it. Journals of rsync jobs cannot be
resumed. Builds without the build tag ceph only support doctor and
status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:03:22 +01:00

333 lines
14 KiB
Python

#!/usr/bin/env python3
"""Independent application-side fixtures; only uses the lab's existing FUSE client."""
import hashlib
import json
import os
import pathlib
import shutil
import stat
import struct
import subprocess
import sys
import time
import uuid
import cephfs
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 snapshot(cluster, *args):
return volume(cluster, "snapshot", *args)
def claim_path():
claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest()
return "/mnt/target-fs/.cephmig/claims/" + claim
def snapshot_names(cluster):
return {x["name"] for x in json.loads(snapshot(cluster, "ls", "cephfs", name))}
def 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 populate(root):
os.mkdir(root + "/d")
with open(root + "/large", "wb") as f:
# Nonzero data throughout, so sparse-file optimizations cannot hide a full copy.
chunk = bytes(range(256)) * 4096
for _ in range(64):
f.write(chunk)
pathlib.Path(root + "/data").write_bytes(b"version-A")
os.chown(root + "/data", 12345, 23456)
os.chmod(root + "/data", 0o640)
os.link(root + "/data", root + "/d/hardlink")
pathlib.Path(root + "/split-a").write_bytes(b"unchanged")
os.link(root + "/split-a", root + "/d/split-b")
os.symlink("../data", root + "/d/symlink")
os.symlink("missing", root + "/dangling")
os.link(root + "/dangling", root + "/d/symlink-hardlink", follow_symlinks=False)
os.symlink("/etc/passwd", root + "/external")
os.symlink("data", root + "/transition")
os.mkfifo(root + "/fifo", 0o600)
os.link(root + "/fifo", root + "/d/fifo-hardlink")
with open(root + "/sparse", "wb") as f:
f.truncate(16 << 20)
pathlib.Path(root + "/deleted-later").write_text("historical")
pathlib.Path(root + "/name with spaces\nand newline").write_text("name")
os.setxattr(root + "/data", "user.cephmig", b"preserve")
os.setxattr(root + "/data", "user.empty", b"")
os.setxattr(root + "/data", "system.posix_acl_access", acl())
os.setxattr(root + "/d", "system.posix_acl_default", acl())
os.setxattr(root + "/d", "ceph.quota.max_bytes", b"33554432")
os.setxattr(root + "/d", "ceph.quota.max_files", b"1000")
os.setxattr(root, "ceph.quota.max_bytes", b"268435456")
# A subtree no round changes; sync rounds skip it by its rctime.
os.makedirs(root + "/static/deep/deeper")
pathlib.Path(root + "/static/deep/deeper/file").write_bytes(b"static" * 1000)
os.link(root + "/static/deep/deeper/file", root + "/static/alias")
os.setxattr(root + "/static/deep", "user.static", b"kept")
os.symlink("deep/deeper/file", root + "/static/link")
def edit_large(root, offset, data):
p = root + "/large"
old = os.stat(p)
with open(p, "r+b") as f:
f.seek(offset)
f.write(data)
# Content changes must be detected even when size and mtime are unchanged.
os.utime(p, ns=(old.st_atime_ns, old.st_mtime_ns))
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(src, dst):
source_links, target_links = {}, {}
def visit(a, b):
x, y = os.lstat(a), os.lstat(b)
assert (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), (a, x, y)
assert attrs(a) == attrs(b), (a, attrs(a), attrs(b))
if not stat.S_ISDIR(x.st_mode):
assert source_links.setdefault(x.st_ino, y.st_ino) == y.st_ino, a
assert target_links.setdefault(y.st_ino, x.st_ino) == x.st_ino, a
if stat.S_ISDIR(x.st_mode):
for key in ("ceph.quota.max_bytes", "ceph.quota.max_files"):
def quota(p):
try:
return os.getxattr(p, key)
except OSError as e:
if e.errno != 61:
raise
return b"0"
assert quota(a) == quota(b), (a, key)
names = set(os.listdir(a)) - {".snap"}
assert names == set(os.listdir(b)) - {".snap"}, (a, names, os.listdir(b))
for name in names:
visit(a + "/" + name, b + "/" + name)
elif stat.S_ISREG(x.st_mode):
assert x.st_size == y.st_size, a
def digest(p):
h = hashlib.sha256()
with open(p, "rb") as f:
while chunk := f.read(4 << 20):
h.update(chunk)
return h.digest()
assert digest(a) == digest(b), a
elif stat.S_ISLNK(x.st_mode):
assert os.readlink(a) == os.readlink(b), a
else:
assert x.st_rdev == y.st_rdev, a
visit(src, dst)
def mount(cluster):
fs = cephfs.LibCephFS(conffile=f"/clusters/{cluster}/ceph.conf",
conf={"keyring": f"/clusters/{cluster}/ceph.client.admin.keyring"})
fs.mount(filesystem_name=b"cephfs")
return fs
def compare_times(src, dst, atime):
"""Compare times through libcephfs; FUSE does not expose the birth time.
The access time is only compared for immutable snapshots, because the FUSE
reads in compare() update it in the live trees."""
keys = ("atime", "mtime", "ctime", "btime") if atime else ("mtime", "ctime", "btime")
mask = cephfs.CEPH_STATX_BASIC_STATS | cephfs.CEPH_STATX_BTIME
fa, fb = mount("source"), mount("target")
def ceph_path(p, cluster):
prefix = f"/mnt/{cluster}-fs"
assert p.startswith(prefix + "/"), p
return p[len(prefix):].encode()
def visit(a, b):
x = fa.statx(a, mask, cephfs.AT_SYMLINK_NOFOLLOW)
y = fb.statx(b, mask, cephfs.AT_SYMLINK_NOFOLLOW)
assert {k: x[k] for k in keys} == {k: y[k] for k in keys}, (a, x, y)
if not stat.S_ISDIR(x["mode"]):
return 1
d = fa.opendir(a)
names = []
while entry := fa.readdir(d):
if entry.d_name not in (b".", b"..", b".snap"):
names.append(entry.d_name)
fa.closedir(d)
return 1 + sum(visit(a + b"/" + n, b + b"/" + n) for n in names)
try:
return visit(ceph_path(src, "source"), ceph_path(dst, "target"))
finally:
fa.unmount()
fb.unmount()
action = sys.argv[1]
if action == "setup":
name = "native-itest-" + str(uuid.uuid4())
else:
name = sys.argv[2]
assert name.startswith("native-itest-") and len(name) == 49 and "/" not in name
work = "/state/" + name
state = work + "/job.json"
config = work + "/config.json"
fixture = work + "/fixture.json"
if action == "setup":
os.mkdir(work, 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")}
pathlib.Path(fixture).write_text(json.dumps(roots))
c = json.load(open("/lab/migration.example.json"))
c.update(backend="native", workers=2, bandwidth_kib=2048)
for endpoint in ("source", "target"):
c[endpoint]["subvolume"] = name
pathlib.Path(config).write_text(json.dumps(c))
src = roots["source"]
populate(src)
volume("source", "metadata", "set", "cephfs", name, "owner", "application")
snapshot("source", "create", "cephfs", name, "history-1")
snapshot("source", "metadata", "set", "cephfs", name, "history-1", "app", "first")
edit_large(src, 20 << 20, b"B" * 4096)
pathlib.Path(src + "/data").write_bytes(b"version-B")
os.unlink(src + "/deleted-later")
p = src + "/d/split-b"
old = os.stat(p)
old_attrs = attrs(p)
os.unlink(p)
pathlib.Path(p).write_bytes(b"unchanged")
for k in attrs(p):
if k not in old_attrs:
os.removexattr(p, k)
for k, v in old_attrs.items():
os.setxattr(p, k, v)
os.chmod(p, old.st_mode & 0o7777)
os.utime(p, ns=(old.st_atime_ns, old.st_mtime_ns))
os.unlink(src + "/transition")
os.mkdir(src + "/transition")
old = os.lstat(src + "/d/fifo-hardlink")
os.unlink(src + "/d/fifo-hardlink")
os.mkfifo(src + "/d/fifo-hardlink", 0o600)
os.utime(src + "/d/fifo-hardlink", ns=(old.st_atime_ns, old.st_mtime_ns))
pathlib.Path(src + "/transition/child").write_bytes(b"child")
os.setxattr(src + "/d", "ceph.quota.max_bytes", b"50331648")
snapshot("source", "create", "cephfs", name, "history-2")
snapshot("source", "metadata", "set", "cephfs", name, "history-2", "app", "second")
pathlib.Path(src + "/data").write_bytes(b"version-C")
os.setxattr(src + "/d", "ceph.quota.max_files", b"2000")
print(name)
elif action == "unthrottle":
c = json.load(open(config))
c.update(workers=4, bandwidth_kib=0)
pathlib.Path(config).write_text(json.dumps(c))
elif action == "mutate":
roots = json.load(open(fixture))
src, dst = roots["source"], roots["target"]
edit_large(src, 20 << 20, bytes(4 << 20))
edit_large(src, 70 << 20, b"growth" * 1024)
os.setxattr(src + "/data", "user.cephmig", b"updated")
os.removexattr(src + "/data", "user.empty")
os.chmod(src + "/data", 0o660)
os.unlink(src + "/d/split-b")
os.link(src + "/split-a", src + "/d/split-b")
shutil.rmtree(src + "/transition")
os.symlink("data", src + "/transition")
pathlib.Path(dst + "/obsolete").write_bytes(b"prune")
volume("source", "metadata", "rm", "cephfs", name, "owner")
volume("source", "metadata", "set", "cephfs", name, "project", "new-value")
elif action in ("verify", "final"):
roots = json.load(open(fixture))
compare(roots["source"], roots["target"])
compare_times(roots["source"], roots["target"], atime=False)
s = json.load(open(state))
listed = {c: snapshot_names(c) for c in ("source", "target")}
# Only the newest round snapshot remains as base; older ones are removed.
kept = [x["name"] for x in s["snapshots"] if x["owned"] and not x.get("removed")]
assert kept == [s["live_snapshot"]], (kept, s["live_snapshot"])
for c in ("source", "target"):
assert {n for n in listed[c] if n.startswith("cephmig-")} == set(kept), (c, listed[c])
for snap in s["snapshots"]:
assert snap["done"], snap
if snap.get("removed"):
continue
a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath",
"cephfs", name, snap["name"], "migration") for c in ("source", "target")]
compare(a, b)
assert compare_times(a, b, atime=True) > 10
assert snapshot("source", "metadata", "ls", "cephfs", name, snap["name"]) == snapshot(
"target", "metadata", "ls", "cephfs", name, snap["name"])
owned = [x for x in s["snapshots"] if x["owned"]]
# Intermediate rounds skip the untouched subtree; finalize never skips.
assert all(x["transfer"].get("skipped_subtrees", 0) >= 1 for x in owned if not x.get("final")), owned
assert all(x["transfer"].get("skipped_subtrees", 0) == 0 for x in owned if x.get("final")), owned
h2 = next(x for x in s["snapshots"] if x["name"] == "history-2")["transfer"]
assert h2["mode"] == "snapdiff" and h2["blockdiff_files"] > 0, h2
assert h2["bytes_copied"] < 64 << 20, h2
assert volume("source", "metadata", "ls", "cephfs", name) == volume(
"target", "metadata", "ls", "cephfs", name)
if action == "final":
assert s["phase"] == "ready-for-cutover" and len(s["snapshots"]) == 5, s
assert s["snapshots"][-1]["transfer"]["bytes_copied"] == 0, s["snapshots"][-1]
print(json.dumps({"phase": s["phase"], "rounds": len(s["snapshots"]), "history_2": h2}))
elif action == "cleaned":
roots = json.load(open(fixture))
compare(roots["source"], roots["target"])
compare_times(roots["source"], roots["target"], atime=False)
s = json.load(open(state))
assert s["phase"] == "ready-for-cutover" and not s.get("live_snapshot"), s
assert all(x.get("removed") for x in s["snapshots"] if x["owned"]), s
application = {x["name"] for x in s["snapshots"] if not x["owned"]}
assert application == {"history-1", "history-2"}, application
for c in ("source", "target"):
assert snapshot_names(c) == application, (c, snapshot_names(c))
assert not os.path.exists(claim_path()), "claim not released"
print(json.dumps({"remaining_snapshots": sorted(application)}))
elif action == "busy":
# An unrelated source subvolume remains writable throughout migration/finalization.
p = "/mnt/source/" + name
count = 0
try:
with open(p, "wb", buffering=0) as f:
while not os.path.exists(work + "/stop-busy"):
f.seek(0)
f.write(str(count).encode())
os.fsync(f.fileno())
count += 1
pathlib.Path(work + "/busy-count").write_text(str(count))
time.sleep(0.1)
finally:
os.unlink(p)
elif action == "cleanup":
for cluster in ("source", "target"):
for snap in json.loads(snapshot(cluster, "ls", "cephfs", name)):
snapshot(cluster, "rm", "cephfs", name, snap["name"])
volume(cluster, "rm", "cephfs", name, "--force")
try:
os.unlink(claim_path())
except FileNotFoundError:
pass # cleanup released it
shutil.rmtree(work)
else:
raise ValueError(action)