From 330a3ec12c0674741a6d644e73c1fcc728bcbe42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Thu, 3 Dec 2026 22:03:22 +0100 Subject: [PATCH] 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 --- Makefile | 6 +- README.md | 37 ++-- cmd/cephmig/main.go | 8 +- dev/Dockerfile.client | 4 - dev/compose.yaml | 7 - dev/migration-test.sh | 221 ---------------------- dev/migration.example.json | 6 +- dev/native-fixture.py | 1 - dev/smallfiles.py | 1 - docs/lab.md | 5 +- docs/migration.md | 86 ++++----- docs/raw-transfer.md | 7 +- docs/verify-concept.md | 7 - internal/migration/access.go | 104 ++--------- internal/migration/ceph.go | 8 +- internal/migration/cleanup.go | 3 +- internal/migration/cleanup_test.go | 51 ----- internal/migration/config.go | 57 +----- internal/migration/config_test.go | 38 ++-- internal/migration/doc.go | 4 +- internal/migration/engine.go | 166 +---------------- internal/migration/hardlinks.go | 143 -------------- internal/migration/hardlinks_test.go | 137 -------------- internal/migration/linux.go | 235 ------------------------ internal/migration/native_access.go | 6 +- internal/migration/native_claim_test.go | 126 +++++++++++++ internal/migration/native_helpers.go | 3 + internal/migration/process_test.go | 27 +++ internal/migration/rsync.go | 82 --------- internal/migration/rsync_test.go | 172 ----------------- internal/migration/state_test.go | 27 --- 31 files changed, 263 insertions(+), 1522 deletions(-) delete mode 100644 dev/Dockerfile.client delete mode 100644 dev/migration-test.sh create mode 100644 internal/migration/native_claim_test.go create mode 100644 internal/migration/process_test.go delete mode 100644 internal/migration/rsync.go delete mode 100644 internal/migration/rsync_test.go diff --git a/Makefile b/Makefile index d9bebfe..7d3be15 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,10 @@ -.PHONY: build check doctor dev-config dev-up dev-down dev-status dev-smoke dev-shell dev-restart-check dev-migration-test dev-native-build dev-native-test dev-smallfiles-test dev-million-start dev-million-status dev-million-finish +.PHONY: build check doctor dev-config dev-up dev-down dev-status dev-smoke dev-shell dev-restart-check dev-native-build dev-native-test dev-smallfiles-test dev-million-start dev-million-status dev-million-finish build: go build -buildvcs=false -o bin/cephmig ./cmd/cephmig check: go vet ./... go test ./... - bash -n dev/cluster.sh dev/client.sh dev/smoke.sh dev/restart-check.sh dev/migration-test.sh dev/native-test.sh dev/smallfiles-test.sh dev/million-start.sh dev/million-finish.sh + bash -n dev/cluster.sh dev/client.sh dev/smoke.sh dev/restart-check.sh dev/native-test.sh dev/smallfiles-test.sh dev/million-start.sh dev/million-finish.sh python3 -c 'import ast,pathlib; [ast.parse(pathlib.Path(p).read_text()) for p in ("dev/native-fixture.py", "dev/smallfiles.py", "dev/million.py")]' doctor: go run ./cmd/cephmig doctor @@ -24,8 +24,6 @@ dev-shell: docker compose -f dev/compose.yaml exec client bash dev-restart-check: bash dev/restart-check.sh -dev-migration-test: build - docker compose -f dev/compose.yaml exec -T client timeout --kill-after=10s 600s bash /lab/migration-test.sh dev-native-build: docker compose -f dev/compose.yaml build native dev-native-test: dev-native-build diff --git a/README.md b/README.md index 1e27032..3433476 100644 --- a/README.md +++ b/README.md @@ -16,18 +16,15 @@ snapshot, verifies the target and creates a snapshot of the same name there. A journal on local disk records every step. For the last round, all writers are stopped briefly. -There are two backends: - -- **native** (recommended): the copier talks to both clusters directly - through libcephfs. It needs neither rsync nor a kernel or FUSE mount. - After the initial transfer it uses snapdiff and, where possible, blockdiff. -- **rsync**: copies between two mounted CephFS file systems. +The copier talks to both clusters directly through libcephfs. It needs no +kernel or FUSE mount. After the initial transfer it uses snapdiff and, where +possible, blockdiff. **Status:** prototype. The features are verified in the local lab. Load tests at the target size and a production cutover are still missing. > **Documented deviations:** native snapshot IDs and snapshot creation times -> are assigned anew at the target. The native backend takes mtime, atime, +> are assigned anew at the target. CephMig takes mtime, atime, > ctime and birth time (btime) of every file from the source; the ctime is > never lower than the mtime. The original snapshot creation times are kept > in the journal. @@ -38,7 +35,7 @@ tests at the target size and a production cutover are still missing. Requirements: - Linux, Go 1.25 or later and GNU Make -- for the native backend and the lab: Docker Engine with Docker Compose and +- for the copier and the lab: Docker Engine with Docker Compose and `/dev/fuse` on the Docker host - for the lab: up to 12 GiB RAM for the containers and about 8 GiB of disk space for the two OSDs, plus space for the images @@ -49,12 +46,13 @@ Get the source and build it: git clone ssh://git@git.zb-server.de:30022/Sebi/CephfsMig.git cd CephfsMig make doctor # checks Go, Docker and Docker Compose -make build # builds bin/cephmig (rsync backend only) +make build # builds bin/cephmig without libcephfs (doctor and status only) make check # go vet, Go tests and a syntax check of the test scripts ``` -The native backend needs CGO and the libcephfs headers, so it is built in a -container. The build also runs the Go tests with the race detector: +The copier needs CGO and the libcephfs headers (build tag `ceph`), so it is +built in a container. The build also runs the Go tests with the race +detector: ```sh make dev-native-build # builds the image cephmig-native:dev @@ -79,8 +77,8 @@ cephmig status --state FILE | `cleanup` | deletes the snapshots cephmig created and its claim on the target | | `status` | prints the journal | -All results are written to standard output as JSON. The state file must be -outside the CephFS mounts. +All results are written to standard output as JSON. The state file belongs +on local disk. Steps of a migration: @@ -145,16 +143,14 @@ The configuration is a JSON file, here "keyring": "/clusters/source/ceph.client.admin.keyring", "filesystem": "cephfs", "group": "migration", - "subvolume": "demo", - "mount": "/mnt/source-fs" + "subvolume": "demo" }, "target": { "config": "/clusters/target/ceph.conf", "keyring": "/clusters/target/ceph.client.admin.keyring", "filesystem": "cephfs", "group": "migration", - "subvolume": "demo", - "mount": "/mnt/target-fs" + "subvolume": "demo" }, "bandwidth_kib": 0 } @@ -162,8 +158,8 @@ The configuration is a JSON file, here Optional fields are `user` (Ceph client identity, e.g. `client.migration`), `workers` (0 to 64; 0 selects the default) and `full_scan` (`true` makes -every round read all metadata instead of skipping unchanged subtrees). `mount` is only needed for -the rsync backend: the mount of the file system root. +every round read all metadata instead of skipping unchanged subtrees). +`backend` may be omitted; its only value is `native`. ## Examples @@ -184,7 +180,6 @@ More tests: | Target | Content | |----------------------------|-----------------------------------------------------------| -| `make dev-migration-test` | migration with the rsync backend | | `make dev-smallfiles-test` | 10,000 small files (`FILES=2000` limits the number) | | `make dev-million-start` | one million files with four snapshot states | | `make dev-restart-check` | restart of the lab; FSIDs and data are preserved | @@ -200,7 +195,7 @@ and [docs/million-local.md](docs/million-local.md). │ ├── cephmig/ command-line program │ └── nativeprobe/ diagnostic tool for the libcephfs binding ├── internal/ -│ ├── migration/ migration workflow, journal, rsync and native transfer +│ ├── migration/ migration workflow, journal and native transfer │ ├── storage/ file system interface of the native copier │ └── cephfsnative/ CGO binding to libcephfs (build tag ceph) ├── dev/ lab: Compose files, Dockerfiles, test scripts diff --git a/cmd/cephmig/main.go b/cmd/cephmig/main.go index 982d12e..e3f1b14 100644 --- a/cmd/cephmig/main.go +++ b/cmd/cephmig/main.go @@ -72,7 +72,7 @@ func run(ctx context.Context, args []string, out, log io.Writer) error { flags := flag.NewFlagSet(args[0], flag.ContinueOnError) flags.SetOutput(log) configPath := flags.String("config", "", "JSON migration configuration") - statePath := flags.String("state", "", "persistent local state file (outside CephFS mounts)") + statePath := flags.String("state", "", "persistent state file on local disk") stopped := flags.Bool("writers-stopped", false, "confirm ALL source writers are stopped; keep them stopped until cutover completes") if err := flags.Parse(args[1:]); err != nil { if errors.Is(err, flag.ErrHelp) { @@ -121,12 +121,6 @@ func run(ctx context.Context, args []string, out, log io.Writer) error { return errors.New("--writers-stopped is only valid with finalize") } - if c.Backend != "native" && args[0] != "inspect" && args[0] != "cleanup" { - if _, err = exec.LookPath("rsync"); err != nil { - return fmt.Errorf("rsync is required: %w", err) - } - } - engine, closeEngine, err := migration.NewEngine(ctx, c, process, log) if err != nil { return err diff --git a/dev/Dockerfile.client b/dev/Dockerfile.client deleted file mode 100644 index 099db00..0000000 --- a/dev/Dockerfile.client +++ /dev/null @@ -1,4 +0,0 @@ -ARG CEPH_IMAGE=quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d -FROM ${CEPH_IMAGE} -ARG RSYNC_VERSION=3.5.0-3.el10_2 -RUN dnf install -y "rsync-${RSYNC_VERSION}" && dnf clean all diff --git a/dev/compose.yaml b/dev/compose.yaml index ef28ea1..cfa6a38 100644 --- a/dev/compose.yaml +++ b/dev/compose.yaml @@ -55,12 +55,6 @@ services: - ./:/lab:ro client: <<: *ceph - image: cephmig-client:dev - build: - context: . - dockerfile: Dockerfile.client - args: - CEPH_IMAGE: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d} # FUSE mounts remain in the container mount namespace. privileged: true entrypoint: [bash, /lab/client.sh] @@ -71,7 +65,6 @@ services: - source-config:/clusters/source:ro - target-config:/clusters/target:ro - ./:/lab:ro - - ../:/workspace:ro - migration-state:/state healthcheck: test: [CMD-SHELL, 'mountpoint -q /mnt/source && mountpoint -q /mnt/target && mountpoint -q /mnt/source-fs && mountpoint -q /mnt/target-fs'] diff --git a/dev/migration-test.sh b/dev/migration-test.sh deleted file mode 100644 index f82aee7..0000000 --- a/dev/migration-test.sh +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/env bash -set -Eeuo pipefail -mountpoint -q /mnt/source-fs -mountpoint -q /mnt/target-fs -id=$(cat /proc/sys/kernel/random/uuid) -name="itest-$id" -mkdir -p /state/test-runs -work=$(mktemp -d /state/test-runs/cephmig-itest.XXXXXX) -state="/state/$name.json" -config="$work/config.json" -binary=/workspace/bin/cephmig -ceph_real=$(command -v ceph) -rsync_real=$(command -v rsync) -source_ceph() { "$ceph_real" -c /clusters/source/ceph.conf -k /clusters/source/ceph.client.admin.keyring "$@"; } -target_ceph() { "$ceph_real" -c /clusters/target/ceph.conf -k /clusters/target/ceph.client.admin.keyring "$@"; } -completed=false -cleanup() { - if [[ $completed != true ]]; then - echo "FAIL: retained fixtures subvolume=$name state=$state config=$config" >&2 - return - fi - for cluster in source target; do - helper="$cluster"_ceph - while IFS= read -r snap; do - "$helper" fs subvolume snapshot rm cephfs "$name" "$snap" --group_name migration - done < <("$helper" fs subvolume snapshot ls cephfs "$name" --group_name migration | - python3 -c 'import json,sys; print("\n".join(x["name"] for x in json.load(sys.stdin)))') - "$helper" fs subvolume rm cephfs "$name" --group_name migration --force - done - target_fsid=$(target_ceph fsid) - claim=$(python3 - "$target_fsid" "$name" <<'PY' -import hashlib, sys -print(hashlib.sha256("\0".join([sys.argv[1], "cephfs", "migration", sys.argv[2]]).encode()).hexdigest()) -PY -) - rm -f "/mnt/target-fs/.cephmig/claims/$claim" "$state" "$state.lock" "$state.second" "$state.second.lock" - rm -rf "$work" -} -trap cleanup EXIT -source_ceph fs subvolume create cephfs "$name" --group_name migration -target_ceph fs subvolume create cephfs "$name" --group_name migration -src="/mnt/source-fs$(source_ceph fs subvolume getpath cephfs "$name" --group_name migration)" -dst="/mnt/target-fs$(target_ceph fs subvolume getpath cephfs "$name" --group_name migration)" -python3 - /lab/migration.example.json "$config" "$name" <<'PY' -import json,sys -c=json.load(open(sys.argv[1])) -c["backend"]="rsync" # Retained as an explicit regression/reference backend. -c["source"]["subvolume"]=c["target"]["subvolume"]=sys.argv[3] -with open(sys.argv[2],"w") as f: json.dump(c,f) -PY -python3 - "$src" <<'PY' -import os, struct, sys -root=sys.argv[1] -os.mkdir(root+"/d") -with open(root+"/data","wb") as f: f.write(b"version-A") -os.chmod(root+"/data",0o640) -os.chown(root+"/data",12345,23456) -os.link(root+"/data",root+"/d/hardlink") -os.symlink("../data",root+"/d/symlink") -os.symlink("nonexistent",root+"/dangling") -os.symlink("/etc/passwd",root+"/external") -os.mkfifo(root+"/fifo",0o600) -# A separate link group will be split in a later snapshot without changing bytes. -with open(root+"/split-a","wb") as f: f.write(b"unchanged") -os.link(root+"/split-a",root+"/d/split-b") -with open(root+"/sparse","wb") as f: f.truncate(16*1024*1024) -with open(root+"/deleted-later","w") as f: f.write("historical") -with open(root+"/name with spaces\nand newline","w") as f: f.write("name") -os.setxattr(root+"/data","user.cephmig",b"preserve") -entries=[(1,6,0xffffffff),(2,4,12345),(4,0,0xffffffff),(16,4,0xffffffff),(32,0,0xffffffff)] -acl=struct.pack(" "$src/data" -python3 - "$src" <<'PY' -import os,sys -os.setxattr(sys.argv[1]+"/d","ceph.quota.max_files",b"2000") -PY -"$binary" inspect --config "$config" > "$work/inspection.json" - -mkdir "$work/bin" -cat > "$work/bin/rsync" <<'SH' -#!/usr/bin/env bash -set -euo pipefail -if [[ -f $CEPHMIG_FAIL_COPY_ONCE && " $* " != *" --dry-run "* ]]; then - rm "$CEPHMIG_FAIL_COPY_ONCE" - "$CEPHMIG_REAL_RSYNC" "$@" - exit 23 -fi -exec "$CEPHMIG_REAL_RSYNC" "$@" -SH -cat > "$work/bin/ceph" <<'SH' -#!/usr/bin/env bash -set -euo pipefail -if [[ -f $CEPHMIG_CRASH_ONCE && - " $* " == *"/clusters/target/ceph.conf"* && - " $* " == *" fs subvolume snapshot create "* ]]; then - "$CEPHMIG_REAL_CEPH" "$@" - rm "$CEPHMIG_CRASH_ONCE" - kill -KILL "$PPID" - exit 0 -fi -exec "$CEPHMIG_REAL_CEPH" "$@" -SH -chmod +x "$work/bin/rsync" "$work/bin/ceph" -export CEPHMIG_REAL_RSYNC="$rsync_real" CEPHMIG_REAL_CEPH="$ceph_real" -export CEPHMIG_FAIL_COPY_ONCE="$work/fail-copy" CEPHMIG_CRASH_ONCE="$work/crash" -touch "$CEPHMIG_FAIL_COPY_ONCE" -if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/interrupted.json"; then - echo 'expected injected transfer failure' >&2; exit 1 -fi -python3 - "$state" <<'PY' -import json,sys -s=json.load(open(sys.argv[1])) -assert s["phase"]=="syncing" and not s["snapshots"][0]["done"] -PY -touch "$CEPHMIG_CRASH_ONCE" -if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/crashed.json"; then - echo 'expected injected process crash' >&2; exit 1 -fi -test ! -f "$CEPHMIG_CRASH_ONCE" -"$binary" sync --config "$config" --state "$state" > "$work/synced.json" -for snap in history-1 history-2; do - path=$(target_ceph fs subvolume snapshot getpath cephfs "$name" "$snap" migration) - value=$(cat "/mnt/target-fs$path/data") - if [[ $snap = history-1 ]]; then test "$value" = version-A; else test "$value" = version-B; fi - python3 - "/mnt/target-fs$path" "$snap" <<'PY' -import os,sys -root,snap=sys.argv[1:3] -linked=os.stat(root+"/split-a").st_ino==os.stat(root+"/d/split-b").st_ino -assert linked==(snap=="history-1"), (snap,linked) -PY -done -test "$(cat "$dst/data")" = version-C -if "$binary" sync --config "$config" --state "$state.second" > "$work/stolen.json"; then - echo 'second job adopted existing target' >&2; exit 1 -fi -printf 'version-D' > "$src/data" -printf extra > "$dst/obsolete" -source_ceph fs subvolume metadata rm cephfs "$name" owner --group_name migration -source_ceph fs subvolume metadata set cephfs "$name" project new-value --group_name migration -"$binary" sync --config "$config" --state "$state" > "$work/caught-up.json" -test "$(cat "$dst/data")" = version-D -test ! -e "$dst/obsolete" -if "$binary" finalize --config "$config" --state "$state" > "$work/refused.json"; then - echo 'finalization accepted missing writer-stop acknowledgement' >&2; exit 1 -fi -"$binary" finalize --config "$config" --state "$state" --writers-stopped > "$work/final.json" -"$binary" status --state "$state" > "$work/status.json" -"$binary" finalize --config "$config" --state "$state" --writers-stopped > "$work/idempotent.json" -python3 - "$src" "$dst" "$work/status.json" "$work/idempotent.json" <<'PY' -import json,os,stat,sys -src,dst=sys.argv[1:3] -s=json.load(open(sys.argv[3])); again=json.load(open(sys.argv[4])) -assert s==again and s["phase"]=="ready-for-cutover" -assert s["notes"] and "birthtimes" in s["notes"][0] -assert all(x["done"] for x in s["snapshots"]) -assert len(s["snapshots"])==5, s["snapshots"] -assert os.stat(dst+"/data").st_uid==12345 and os.stat(dst+"/data").st_gid==23456 -assert os.stat(dst+"/data").st_ino==os.stat(dst+"/d/hardlink").st_ino -assert os.stat(dst+"/split-a").st_ino!=os.stat(dst+"/d/split-b").st_ino -assert stat.S_ISFIFO(os.lstat(dst+"/fifo").st_mode) -assert os.readlink(dst+"/external")=="/etc/passwd" -for rel,key in [("data","user.cephmig"),("data","system.posix_acl_access"), - ("d","system.posix_acl_default"),("d","ceph.quota.max_bytes"), - ("d","ceph.quota.max_files"),(".","ceph.quota.max_bytes")]: - assert os.getxattr(src+"/"+rel,key)==os.getxattr(dst+"/"+rel,key),(rel,key) -# CephFS st_blocks reflects logical size and cannot prove physical sparseness. -assert os.stat(dst+"/sparse").st_size==16*1024*1024 -with open(dst+"/sparse","rb") as f: - while chunk:=f.read(65536): - assert not any(chunk) -PY -a=$(source_ceph fs subvolume metadata ls cephfs "$name" --group_name migration) -b=$(target_ceph fs subvolume metadata ls cephfs "$name" --group_name migration) -test "$a" = "$b" -for snap in history-1 history-2; do - a=$(source_ceph fs subvolume snapshot metadata ls cephfs "$name" "$snap" --group_name migration) - b=$(target_ceph fs subvolume snapshot metadata ls cephfs "$name" "$snap" --group_name migration) - test "$a" = "$b" -done -python3 /lab/snapshot-identity.py --config "$config" --snapshot history-1 -"$binary" cleanup --config "$config" --state "$state" > "$work/cleaned.json" -for side in source_ceph target_ceph; do - names=$("$side" fs subvolume snapshot ls cephfs "$name" --group_name migration | - python3 -c 'import json,sys; print(" ".join(sorted(x["name"] for x in json.load(sys.stdin))))') - test "$names" = "history-1 history-2" -done -test ! -e "/mnt/target-fs/.cephmig/claims/$(python3 -c 'import hashlib,sys; print(hashlib.sha256("\0".join(sys.argv[1:]).encode()).hexdigest())' "$(target_ceph fsid)" cephfs migration "$name")" -completed=true -echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization, snapshot cleanup' - diff --git a/dev/migration.example.json b/dev/migration.example.json index 52ce363..66e855a 100644 --- a/dev/migration.example.json +++ b/dev/migration.example.json @@ -5,16 +5,14 @@ "keyring": "/clusters/source/ceph.client.admin.keyring", "filesystem": "cephfs", "group": "migration", - "subvolume": "demo", - "mount": "/mnt/source-fs" + "subvolume": "demo" }, "target": { "config": "/clusters/target/ceph.conf", "keyring": "/clusters/target/ceph.client.admin.keyring", "filesystem": "cephfs", "group": "migration", - "subvolume": "demo", - "mount": "/mnt/target-fs" + "subvolume": "demo" }, "bandwidth_kib": 0 } diff --git a/dev/native-fixture.py b/dev/native-fixture.py index 01553b4..b68eb21 100644 --- a/dev/native-fixture.py +++ b/dev/native-fixture.py @@ -203,7 +203,6 @@ if action == "setup": c.update(backend="native", workers=2, bandwidth_kib=2048) for endpoint in ("source", "target"): c[endpoint]["subvolume"] = name - c[endpoint].pop("mount", None) pathlib.Path(config).write_text(json.dumps(c)) src = roots["source"] populate(src) diff --git a/dev/smallfiles.py b/dev/smallfiles.py index fd35de9..ab5e9cf 100644 --- a/dev/smallfiles.py +++ b/dev/smallfiles.py @@ -135,7 +135,6 @@ def main(): 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() diff --git a/docs/lab.md b/docs/lab.md index 5c0cdab..64a849a 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -7,7 +7,7 @@ independent Ceph clusters. Introduction and overview: [README](../README.md). The service `native` runs without privileged mode, without `/dev/fuse` and without CephFS mounts. The separate privileged `client` serves as an -independent application client and for the rsync comparison test. +independent application client that checks the results through FUSE. `make dev-smallfiles-test` checks 10,000 files of 128 bytes each by default, plus hardlinks and symlinks. Half of the files are in one large directory, @@ -43,8 +43,7 @@ snapshots live outside the current data UUID directory. No host devices are formatted and no ports are published on the host. The OSD data lives in Docker volumes. The replication factor 1 and the administrator keys in the test client are for the local lab only. The client -extends the pinned Ceph base image with a pinned rsync package version. The -journal can be stored permanently under `/state` in a dedicated Docker +uses the pinned Ceph base image unchanged. The journal can be stored permanently under `/state` in a dedicated Docker volume. ```sh diff --git a/docs/migration.md b/docs/migration.md index 6a7a0b9..5dac1e0 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -32,24 +32,24 @@ automated production client cutover are still missing. ## Commands -The native backend needs Linux, the Ceph CLI, libcephfs and a copier built -with CGO and `-tags ceph`. It needs no operating system mounts and no -privileged container. Preserving foreign UID/GID and protected xattrs requires -the corresponding client and process privileges; the lab uses root. The -optional reference path `backend: rsync` additionally needs rsync and source -and target file systems mounted at the file system root. +CephMig needs Linux, the Ceph CLI, libcephfs and a copier built with CGO and +`-tags ceph`. It needs no operating system mounts and no privileged +container. Preserving foreign UID/GID and protected xattrs requires the +corresponding client and process privileges; the lab uses root. An rsync +backend over mounted file systems existed earlier and was removed; a +configuration with `backend: rsync` or `mount` is rejected. The subvolumes must already exist. For a new job, the data tree, snapshots and custom metadata of the target must be empty. No application may write to the target. -The configuration in `dev/migration.example.json` selects `backend: native` -and applies to the lab service `native`. `mount` is not used there and may be -omitted. `workers` limits concurrent file copies (default 8, at most 64), +The configuration in `dev/migration.example.json` applies to the lab service +`native`. `backend` may be omitted; its only value is `native`. `workers` +limits concurrent file copies and verification checks (default 8, at most 64), `bandwidth_kib` limits the total payload bytes written per second. Both values may be changed when resuming. -The native `transfer` statistics in the journal report the mode, the base -snapshot, visited and copied files, and bytes written and read for -verification. `bytes_copied` counts payload writes without skipped zero +The `transfer` statistics in the journal report the mode, the base +snapshot, visited and copied files, bytes written and read for verification, +skipped subtrees and the duration of the round in seconds. `bytes_copied` counts payload writes without skipped zero ranges; it does not measure the total network traffic including protocol and verification. @@ -65,7 +65,7 @@ The read-only preflight compares the FSID from the CLI with the and reports the current data size and snapshot names. The data size is **not** a capacity forecast for all historical snapshots. -The backend has the following transfer commands: +The transfer commands are: ```sh cephmig sync --config /absolute/config.json --state /local-state/job.json @@ -79,9 +79,8 @@ cephmig cleanup --config /absolute/config.json --state /local-state/job.json `sync` processes known, unfinished states, newly discovered application snapshots and then a new source snapshot. Further changes are caught up by -running `sync` again. The native backend uses snapdiff and the Ceph inode -version, so it also detects data changes with the same size and mtime. The -rsync path uses checksums. +running `sync` again. CephMig uses snapdiff and the Ceph inode version, so it +also detects data changes with the same size and mtime. ### Skipping unchanged subtrees @@ -223,12 +222,12 @@ sequenceDiagram - Numeric UID/GID, mode, POSIX ACLs including default ACLs. - Timestamps of every file, directory and symlink: - | Timestamp | native | rsync | - | --- | --- | --- | - | mtime (last modification) | yes | yes | - | btime (creation) | yes | no | - | atime (last access) | yes | no | - | ctime (last status change) | yes¹ | no | + | Timestamp | preserved | + | --- | --- | + | mtime (last modification) | yes | + | btime (creation) | yes | + | atime (last access) | yes | + | ctime (last status change) | yes¹ | ¹ To the nanosecond, but never lower than the mtime: if the source mtime is newer than its ctime (mtime set into the future), the target gets @@ -259,9 +258,7 @@ sequenceDiagram This behaviour was measured in the lab and is not guaranteed by Ceph; the verification reports every deviation. The atime at the target subsequently - changes through normal reads of the application. rsync cannot transfer the - btime on Linux; the atime is not transferred because the checksum - verification through the mount can change the target atime. + changes through normal reads of the application. - User xattrs and other portable xattrs, including empty values and removals. - Hardlinks within the subvolume, symlinks and FIFOs. - Sparse file contents; the native path skips zero ranges or punches holes. @@ -292,8 +289,7 @@ visible in subdirectories are part of the parent subvolume snapshot. The earlier warning about separate subdirectory snapshots was too broad for this managed subvolume model. See [MDS check of the subvolume boundary](https://github.com/ceph/ceph/blob/main/src/mds/Server.cc). -With the rsync backend, ctime and atime are not preserved; with both -backends, original inode numbers and native snapshot IDs are assigned anew. +Original inode numbers and native snapshot IDs are assigned anew. Encrypted, normalized, case-insensitive or earmarked subvolumes are rejected. ## Resumption and verification @@ -351,22 +347,13 @@ content comparison after the cutover is proposed in snapshot created right after the verification is checked for metadata and links; the same immutable data is not read again. -The rsync verification reads file contents by checksum and also compares the -supported metadata. Quota values are checked separately. Resuming within a -state reuses the existing partial copies, but has to scan the tree again; -checkpoints currently exist per snapshot, not per file. For a hardlink -`EEXIST` reproduced in the lab, the transfer is retried exactly once, -idempotently; other errors are returned immediately. - In addition, the hardlink topology is verified in both directions: all source paths of the same inode must belong together at the target, and independent -source files must not accidentally share an inode at the target. This is -needed because [rsync -H](https://download.samba.org/pub/rsync/rsync.1) does -not resolve surplus existing target links in every case. Before copying, the -rsync path removes such surplus links in the exclusive target and rebuilds -them from the source snapshot. The native path creates full copies -atomically as new inodes and then sets the hardlink aliases. Old target -snapshots stay unchanged. Symlinked directories are not followed. +source files must not accidentally share an inode at the target. The copier +creates full copies atomically as new inodes and then sets the hardlink +aliases. Old target snapshots stay unchanged. Symlinked directories are not +followed. The verification walks the tree in order and checks directories +itself; all other entries are checked by up to `workers` goroutines. The verification mappings live in a temporary bbolt index next to the journal; write transactions are committed after 4,096 observations. The index @@ -389,7 +376,6 @@ automatically; that requires checking the original job ID. ```sh make check go test -race ./... -make dev-migration-test make dev-native-test ``` @@ -413,9 +399,10 @@ checks cover cancellation during the copy, SIGKILL right after snapshot creation, restart and idempotent completion. Meanwhile, an application keeps writing to another source subvolume. -Lab result of 2026-11-05 with Ceph 21.2.0: native integration test and rsync -regression passed; Go tests including the race detector and `go vet` for the -Ceph build passed. The native test completed five states with +Lab result of 2026-11-05 with Ceph 21.2.0: native integration test and the +regression test of the since removed rsync backend passed; Go tests +including the race detector and `go vet` for the Ceph build passed. The +native test completed five states with `ready-for-cutover` and additionally checked them through the application client. For the 4 KiB change in the 64 MiB file, 4 KiB were written for this file and 4,128 payload bytes for the whole second state including other @@ -429,13 +416,10 @@ python3 /lab/snapshot-identity.py \ --config /absolute/lab-config.json --snapshot existing-snapshot ``` -Go reads directory quotas in batches and keeps no list of all files. This -does **not** bound the memory of the external rsync process: large single -directories and hardlink groups can need considerable memory there. Every -state causes full scans and checksum reads. Changed large files can need -considerable additional target space for new snapshots. +Changed large files can need considerable additional target space for new +snapshots. -In the native path, file workers, data buffers and directory iteration are +File workers, data buffers and directory iteration are bounded; copy and compare buffers are at most 4 MiB and shrink for small files and short verification ranges. Unchanged owner, mode and timestamps do not trigger another `setattr` call; a target stat read just before is reused diff --git a/docs/raw-transfer.md b/docs/raw-transfer.md index 7957f28..5ff4bf1 100644 --- a/docs/raw-transfer.md +++ b/docs/raw-transfer.md @@ -36,8 +36,8 @@ target. ## Verified native alternative -The Go transport `backend: native` uses libcephfs without rsync and without a -kernel or FUSE mount. Metadata operations go through the target MDS; data +The Go transport uses libcephfs without rsync and without a kernel or FUSE +mount. Metadata operations go through the target MDS; data I/O is handled by the native Ceph client directly against RADOS. A raw import of the shared MDS metadata pool remains outside the migration. @@ -124,7 +124,8 @@ Snapdiff marks changed inodes; in addition, comparing the Ceph inode version ensures that data changes with the same size and mtime are not missed. Blockdiff is used from 16 MiB on, provided a confirmed base with matching source and target inodes exists. If the diff interfaces are unavailable, the -state is reconstructed fully and natively. There is no silent rsync fallback. +state is reconstructed fully and natively. There is no fallback to another +transfer method. Snapdiff cannot replace the metadata scan (see [skipping unchanged subtrees](migration.md#skipping-unchanged-subtrees)). diff --git a/docs/verify-concept.md b/docs/verify-concept.md index dcd5366..fb55f6d 100644 --- a/docs/verify-concept.md +++ b/docs/verify-concept.md @@ -117,13 +117,6 @@ the source snapshot after explicit confirmation; that is out of scope here. - **Source:** the source cluster and its final snapshot must stay available until `verify` is done. -## rsync backend - -The same command can run with the rsync backend through the mounts, for -example `rsync -a --checksum --dry-run --itemize-changes` between the two -snapshot directories plus the existing quota and hardlink checks. Times other -than mtime are not compared there, because rsync does not preserve them. - ## Tests - Unit tests with fake file systems: every kind of difference is reported, diff --git a/internal/migration/access.go b/internal/migration/access.go index f6b6520..cfa7087 100644 --- a/internal/migration/access.go +++ b/internal/migration/access.go @@ -5,11 +5,8 @@ import ( "errors" "fmt" "io" - "os" "path" - "path/filepath" "strings" - "syscall" ) func nativePath(p string) (string, error) { @@ -33,84 +30,22 @@ type Access interface { Release(context.Context, Config, string, string) error } -type mountedAccess struct{} - -func (mountedAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspection, error) { - return inspectMounted(ctx, c, x) -} - -func (mountedAccess) Empty(_ context.Context, p string) error { return emptyDirectory(p) } - -func (mountedAccess) Claim(_ context.Context, c Config, fsid, id string) (io.Closer, error) { - return claimTarget(c.Target.Mount, fsid, c.Target, id) -} - -func (mountedAccess) Release(_ context.Context, c Config, fsid, id string) error { - dir := filepath.Join(c.Target.Mount, ".cephmig", "claims") - p := filepath.Join(dir, claimName(fsid, c.Target)) - f, err := os.OpenFile(p, os.O_RDONLY|syscall.O_NOFOLLOW, 0) - if errors.Is(err, os.ErrNotExist) { - return nil - } - if err != nil { - return err - } - - b, err := io.ReadAll(io.LimitReader(f, 256)) - f.Close() - if err != nil { - return err - } - - if string(b) != id+"\n" { - return errors.New("target claim belongs to a different job; not removed") - } - - if err = os.Remove(p); err != nil { - return err - } - - for _, d := range []string{dir, filepath.Dir(dir)} { - if err := os.Remove(d); err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.ENOTEMPTY) && !errors.Is(err, syscall.EEXIST) { - return err - } - } - - return nil -} - -func (mountedAccess) Prepare(ctx context.Context, src, dst, scratch string) error { - if err := clearQuotas(ctx, dst); err != nil { - return err - } - - return hardlinkTopology(ctx, src, dst, scratch, true) -} - -func (mountedAccess) Apply(ctx context.Context, src, dst string) error { - return quotas(ctx, src, dst, false) -} - -func (mountedAccess) Verify(ctx context.Context, src, dst, scratch string) error { - if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil { - return err - } - - return quotas(ctx, src, dst, true) -} - -func (e Engine) access() Access { - if e.Access != nil { - return e.Access - } - - return mountedAccess{} -} +func (e Engine) access() Access { return e.Access } // Inspect checks both endpoints without changing them and reports what a // migration would transfer. func (e Engine) Inspect(ctx context.Context, c Config) (*Inspection, error) { - return e.access().Inspect(ctx, c, e.Exec) + if e.Access == nil { + return nil, errors.New("missing access") + } + + return e.Access.Inspect(ctx, c, e.Exec) +} + +// Transport copies a source tree to the target and verifies the copy. +type Transport interface { + Copy(context.Context, string, string) error + Verify(context.Context, string, string) error } // Round describes one snapshot transfer handed to a RoundTransport. @@ -149,16 +84,9 @@ type TransferStats struct { Seconds float64 `json:"seconds"` } -// NewEngine returns an Engine for c.Backend and a Closer that releases its -// connections. It never silently falls back from native I/O to mounted/rsync I/O. +// NewEngine returns an Engine with the native libcephfs backend and a Closer +// that releases its connections. Builds without the build tag ceph return an +// error. func NewEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) { - if c.Backend == "native" { - return openNativeEngine(ctx, c, x, log) - } - - return Engine{Exec: x, Log: log, Transport: Rsync{Exec: x, Log: log, BandwidthKiB: c.BandwidthKiB}}, nopCloser{}, nil + return openNativeEngine(ctx, c, x, log) } - -type nopCloser struct{} - -func (nopCloser) Close() error { return nil } diff --git a/internal/migration/ceph.go b/internal/migration/ceph.go index 36c3ecd..3751800 100644 --- a/internal/migration/ceph.go +++ b/internal/migration/ceph.go @@ -11,7 +11,6 @@ import ( type ceph struct { endpoint Endpoint exec Executor - native bool } func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) { @@ -64,12 +63,7 @@ func (c ceph) snapshotPath(ctx context.Context, name string) (string, error) { return "", err } - p := strings.TrimSpace(string(b)) - if c.native { - return nativePath(p) - } - - return dataPath(c.endpoint.Mount, p) + return nativePath(strings.TrimSpace(string(b))) } func (c ceph) names(ctx context.Context) ([]string, error) { diff --git a/internal/migration/cleanup.go b/internal/migration/cleanup.go index 712a478..6641956 100644 --- a/internal/migration/cleanup.go +++ b/internal/migration/cleanup.go @@ -108,8 +108,7 @@ func (e Engine) Cleanup(ctx context.Context, c Config, statePath string) error { defer claim.Close() } - native := c.Backend == "native" - src, dst := ceph{endpoint: c.Source, exec: e.Exec, native: native}, ceph{endpoint: c.Target, exec: e.Exec, native: native} + src, dst := ceph{endpoint: c.Source, exec: e.Exec}, ceph{endpoint: c.Target, exec: e.Exec} s.LiveSnapshot = "" if err = removeOwnedSnapshots(ctx, src, dst, abs, s, ""); err != nil { return err diff --git a/internal/migration/cleanup_test.go b/internal/migration/cleanup_test.go index 38de46e..1427a11 100644 --- a/internal/migration/cleanup_test.go +++ b/internal/migration/cleanup_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "io" - "os" "path/filepath" "slices" "testing" @@ -128,56 +127,6 @@ func TestStateRejectsInvalidRemoval(t *testing.T) { } } -func TestReleaseRemovesOnlyOwnClaim(t *testing.T) { - root := t.TempDir() - c := testConfig() - c.Target.Mount = root - other := c - other.Target.Subvolume = "other" - for _, x := range []struct { - c Config - id string - }{{c, "job-one"}, {other, "job-two"}} { - f, err := claimTarget(root, "fsid", x.c.Target, x.id) - if err != nil { - t.Fatal(err) - } - - f.Close() - } - - access := mountedAccess{} - if err := access.Release(context.Background(), c, "fsid", "job-two"); err == nil { - t.Fatal("removed the claim of a different job") - } - - if err := access.Release(context.Background(), c, "fsid", "job-one"); err != nil { - t.Fatal(err) - } - - claims := filepath.Join(root, ".cephmig", "claims") - if _, err := os.Stat(filepath.Join(claims, claimName("fsid", c.Target))); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("own claim still present: %v", err) - } - - if _, err := os.Stat(filepath.Join(claims, claimName("fsid", other.Target))); err != nil { - t.Fatalf("claim of another job removed: %v", err) - } - - if err := access.Release(context.Background(), other, "fsid", "job-two"); err != nil { - t.Fatal(err) - } - - if _, err := os.Stat(filepath.Join(root, ".cephmig")); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("empty claim directories kept: %v", err) - } - - // Releasing again is a no-op. - if err := access.Release(context.Background(), c, "fsid", "job-one"); err != nil { - t.Fatal(err) - } -} - func TestCleanedUp(t *testing.T) { s := testState() s.Phase = "ready-for-cutover" diff --git a/internal/migration/config.go b/internal/migration/config.go index 1ba93e2..8507ec4 100644 --- a/internal/migration/config.go +++ b/internal/migration/config.go @@ -11,8 +11,7 @@ import ( ) // Endpoint describes how to reach one side of a migration: the Ceph -// client identity and configuration, the subvolume and, for the rsync -// backend, the local mount of the CephFS filesystem root. +// client identity and configuration and the subvolume. type Endpoint struct { User string `json:"user,omitempty"` Config string `json:"config"` @@ -20,11 +19,10 @@ type Endpoint struct { Filesystem string `json:"filesystem"` Group string `json:"group"` Subvolume string `json:"subvolume"` - Mount string `json:"mount,omitempty"` } // Config is the JSON migration configuration read by ReadConfig. -// Backend selects "native" (libcephfs) or "rsync" (the default). +// Backend is optional; the only backend is "native" (libcephfs). type Config struct { Backend string `json:"backend,omitempty"` Workers int `json:"workers,omitempty"` @@ -77,8 +75,8 @@ func validName(s string) bool { // Validate checks names, paths, worker and bandwidth limits and reports // the first problem found. func (c Config) Validate() error { - if c.Backend != "" && c.Backend != "rsync" && c.Backend != "native" { - return errors.New("backend must be native or rsync") + if c.Backend != "" && c.Backend != "native" { + return errors.New(`backend must be "native"; the rsync backend was removed`) } if c.Workers < 0 || c.Workers > 64 { @@ -103,12 +101,7 @@ func (c Config) Validate() error { return fmt.Errorf("%s: invalid group", p.name) } - paths := []string{p.e.Config, p.e.Keyring} - if c.Backend != "native" || p.e.Mount != "" { - paths = append(paths, p.e.Mount) - } - - for _, path := range paths { + for _, path := range []string{p.e.Config, p.e.Keyring} { if !filepath.IsAbs(path) || filepath.Clean(path) != path { return fmt.Errorf("%s: paths must be absolute and clean: %q", p.name, path) } @@ -119,45 +112,5 @@ func (c Config) Validate() error { return errors.New("bandwidth_kib must be nonnegative and fit in bytes per second") } - if c.Backend != "native" && overlaps(c.Source.Mount, c.Target.Mount) { - return errors.New("source and target mounts must not overlap") - } - return nil } - -func beneath(root, path string) bool { - rel, err := filepath.Rel(root, path) - return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) -} - -func overlaps(a, b string) bool { return beneath(a, b) || beneath(b, a) } - -// dataPath resolves cephPath to a real directory below the filesystem mount -// root. No symlink component is permitted, including in the mount path. -func dataPath(root, cephPath string) (string, error) { - if !filepath.IsAbs(cephPath) || filepath.Clean(cephPath) != cephPath || cephPath == "/" { - return "", fmt.Errorf("invalid Ceph path %q", cephPath) - } - - p := filepath.Join(root, strings.TrimPrefix(cephPath, "/")) - resolved, err := filepath.EvalSymlinks(p) - if err != nil { - return "", err - } - - if resolved != p || !beneath(root, p) { - return "", fmt.Errorf("path escapes mount or contains symlinks: %q", p) - } - - st, err := os.Stat(p) - if err != nil { - return "", err - } - - if !st.IsDir() { - return "", fmt.Errorf("not a directory: %s", p) - } - - return p, nil -} diff --git a/internal/migration/config_test.go b/internal/migration/config_test.go index 7cfc18a..ae1e89d 100644 --- a/internal/migration/config_test.go +++ b/internal/migration/config_test.go @@ -9,15 +9,15 @@ import ( ) func testConfig() Config { - return Config{Source: Endpoint{Config: "/clusters/a/ceph.conf", Keyring: "/clusters/a/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "source", Mount: "/mnt/a"}, - Target: Endpoint{Config: "/clusters/b/ceph.conf", Keyring: "/clusters/b/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "target", Mount: "/mnt/b"}} + return Config{Source: Endpoint{Config: "/clusters/a/ceph.conf", Keyring: "/clusters/a/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "source"}, + Target: Endpoint{Config: "/clusters/b/ceph.conf", Keyring: "/clusters/b/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "target"}} } func TestConfigRejectsUnsafePathsAndNames(t *testing.T) { for name, modify := range map[string]func(*Config){ - "overlap": func(c *Config) { c.Target.Mount = "/mnt/a/nested" }, - "relative": func(c *Config) { c.Source.Mount = "relative" }, - "unclean": func(c *Config) { c.Source.Mount = "/mnt/a/../a" }, + "relative": func(c *Config) { c.Source.Config = "relative" }, + "unclean": func(c *Config) { c.Target.Keyring = "/clusters/b/../b/keyring" }, + "rsync-backend": func(c *Config) { c.Backend = "rsync" }, "flag-name": func(c *Config) { c.Target.Subvolume = "--force" }, "traversal": func(c *Config) { c.Source.Group = "../outside" }, "negative-rate": func(c *Config) { c.BandwidthKiB = -1 }, @@ -43,11 +43,16 @@ func TestConfigRejectsUnsafePathsAndNames(t *testing.T) { func TestNativeConfigAndResumeSettings(t *testing.T) { c := testConfig() c.Backend = "native" - c.Source.Mount, c.Target.Mount = "", "" if err := c.Validate(); err != nil { t.Fatal(err) } + implicit := c + implicit.Backend = "" + if !sameMigrationIdentity(c, implicit) { + t.Fatal(`backend "" and "native" differ in resume identity`) + } + changed := c changed.Workers, changed.BandwidthKiB = 32, 100000 if !sameMigrationIdentity(c, changed) { @@ -76,27 +81,6 @@ func TestStrictJSONConfig(t *testing.T) { } } -func TestDataPathRejectsEscapeAndSymlink(t *testing.T) { - root := t.TempDir() - if err := os.Mkdir(filepath.Join(root, "real"), 0700); err != nil { - t.Fatal(err) - } - - if err := os.Symlink(t.TempDir(), filepath.Join(root, "link")); err != nil { - t.Fatal(err) - } - - for _, path := range []string{"/../escape", "/real/../real", "relative", "/link", "/"} { - if _, err := dataPath(root, path); err == nil { - t.Fatalf("accepted %q", path) - } - } - - if got, err := dataPath(root, "/real"); err != nil || got != filepath.Join(root, "real") { - t.Fatalf("got %q, %v", got, err) - } -} - func TestPrivateDirectoriesNeverFollowsSymlink(t *testing.T) { root, outside := t.TempDir(), t.TempDir() if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil { diff --git a/internal/migration/doc.go b/internal/migration/doc.go index 3d168f3..444b847 100644 --- a/internal/migration/doc.go +++ b/internal/migration/doc.go @@ -4,6 +4,6 @@ // A migration is a sequence of rounds. Each round creates or picks a source // snapshot, copies it with a Transport, verifies the target and publishes a // target snapshot of the same name. Progress is recorded in a State journal so -// that every step can be resumed. Two backends exist: rsync over mounted -// filesystems and a native libcephfs transport (build tag ceph). +// that every step can be resumed. Data moves through libcephfs (build tag +// ceph); no mount and no rsync are needed. package migration diff --git a/internal/migration/engine.go b/internal/migration/engine.go index da0ab4a..ece5ea0 100644 --- a/internal/migration/engine.go +++ b/internal/migration/engine.go @@ -15,12 +15,11 @@ import ( "slices" "sort" "strings" - "syscall" "time" ) // Engine runs the snapshot-based migration workflow. Transport moves the -// data; Access, if nil, defaults to mounted filesystem access. +// data; Access reaches both clusters for everything else. Both are required. type Engine struct { Exec Executor Transport Transport @@ -88,80 +87,6 @@ func queryEndpoint(ctx context.Context, c ceph) (string, endpointInfo, error) { return fsid, info, nil } -func endpoint(ctx context.Context, c ceph) (string, endpointInfo, string, error) { - fsid, info, err := queryEndpoint(ctx, c) - if err != nil { - return "", info, "", err - } - - path, err := dataPath(c.endpoint.Mount, info.Path) - if err != nil { - return "", info, "", err - } - - mountedFSID, err := xattr(path, "ceph.cluster_fsid") - if err != nil { - return "", info, "", fmt.Errorf("cannot verify mount FSID: %w", err) - } - - if string(mountedFSID) != fsid { - return "", info, "", fmt.Errorf("mount belongs to a different cluster than the configured Ceph endpoint") - } - - return fsid, info, path, err -} - -func inspectMounted(ctx context.Context, c Config, x Executor) (*Inspection, error) { - if err := c.Validate(); err != nil { - return nil, err - } - - if err := checkMount(c.Source.Mount, false); err != nil { - return nil, err - } - - if err := checkMount(c.Target.Mount, true); err != nil { - return nil, err - } - - src, dst := ceph{endpoint: c.Source, exec: x}, ceph{endpoint: c.Target, exec: x} - sf, si, sp, err := endpoint(ctx, src) - if err != nil { - return nil, fmt.Errorf("source: %w", err) - } - - tf, _, tp, err := endpoint(ctx, dst) - if err != nil { - return nil, fmt.Errorf("target: %w", err) - } - - if sf == tf { - return nil, errors.New("source and target must be different clusters") - } - - var ss, ts syscall.Stat_t - if err = syscall.Stat(sp, &ss); err != nil { - return nil, err - } - - if err = syscall.Stat(tp, &ts); err != nil { - return nil, err - } - - if ss.Dev == ts.Dev { - return nil, errors.New("source and target are on the same mounted filesystem") - } - - names, err := src.names(ctx) - if err != nil { - return nil, err - } - - inspection := &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: sp, TargetPath: tp, SourceBytes: si.BytesUsed, SourceSnapshots: names} - inspection.Notes = []string{SnapshotIdentityNote} - return inspection, nil -} - func newID() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { @@ -171,25 +96,6 @@ func newID() (string, error) { return hex.EncodeToString(b[:]), nil } -func emptyDirectory(path string) error { - f, err := os.Open(path) - if err != nil { - return err - } - - defer f.Close() - entries, err := f.ReadDir(1) - if err != nil && !errors.Is(err, io.EOF) { - return err - } - - if len(entries) != 0 { - return fmt.Errorf("new migration requires empty target subvolume: %s", path) - } - - return nil -} - // claimName is the file name of the claim for the target subvolume ep in // the cluster fsid, below .cephmig/claims at the file system root. func claimName(fsid string, ep Endpoint) string { @@ -197,64 +103,6 @@ func claimName(fsid string, ep Endpoint) string { return hex.EncodeToString(key[:]) } -// claimTarget locks the target subvolume for the job id. The claim is outside -// the migrated tree and survives deletion of the local journal. O_EXCL prevents two different jobs from adopting the same target. -func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) { - dir := filepath.Join(root, ".cephmig", "claims") - if err := privateDirectories(dir); err != nil { - return nil, err - } - - resolved, err := filepath.EvalSymlinks(dir) - if err != nil || resolved != dir { - return nil, errors.New("claim directory contains symlinks") - } - - path := filepath.Join(dir, claimName(fsid, ep)) - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) - if err == nil { - if _, err = f.WriteString(id + "\n"); err == nil { - err = f.Sync() - } - - if closeErr := f.Close(); err == nil { - err = closeErr - } - if err != nil { - return nil, err - } - } else if !errors.Is(err, os.ErrExist) { - return nil, err - } - - st, err := os.Lstat(path) - if err != nil { - return nil, err - } - - if !st.Mode().IsRegular() { - return nil, errors.New("target claim is not a regular file") - } - - f, err = os.OpenFile(path, os.O_RDWR|syscall.O_NOFOLLOW, 0) - if err != nil { - return nil, err - } - - if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { - f.Close() - return nil, fmt.Errorf("target is being migrated by another process: %w", err) - } - - b, err := io.ReadAll(io.LimitReader(f, 256)) - if err != nil || string(b) != id+"\n" { - f.Close() - return nil, errors.New("target is claimed by a different job or claim is incomplete; preserve the original state file") - } - - return f, nil -} - func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, error) { var s Snapshot s.Name = name @@ -294,8 +142,8 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool return errors.New("migration requires root for numeric ownership, ACLs and xattrs") } - if e.Exec == nil || e.Transport == nil { - return errors.New("missing executor or transport") + if e.Exec == nil || e.Transport == nil || e.Access == nil { + return errors.New("missing executor, transport or access") } abs, err := filepath.Abs(statePath) @@ -303,10 +151,6 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool return err } - if c.Backend != "native" && (overlaps(filepath.Dir(abs), c.Source.Mount) || overlaps(filepath.Dir(abs), c.Target.Mount)) { - return errors.New("state directory must be outside the CephFS mounts") - } - if err = privateDirectories(filepath.Dir(abs)); err != nil { return err } @@ -327,7 +171,7 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool return err } - src, dst := ceph{endpoint: c.Source, exec: e.Exec, native: c.Backend == "native"}, ceph{endpoint: c.Target, exec: e.Exec, native: c.Backend == "native"} + src, dst := ceph{endpoint: c.Source, exec: e.Exec}, ceph{endpoint: c.Target, exec: e.Exec} s, err := LoadState(abs) if errors.Is(err, os.ErrNotExist) { if err = e.access().Empty(ctx, inspection.TargetPath); err != nil { @@ -590,6 +434,8 @@ func sameMigrationIdentity(a, b Config) bool { a.Workers, b.Workers = 0, 0 a.BandwidthKiB, b.BandwidthKiB = 0, 0 a.FullScan, b.FullScan = false, false + // "" and "native" select the same backend. + a.Backend, b.Backend = "", "" return reflect.DeepEqual(a, b) } diff --git a/internal/migration/hardlinks.go b/internal/migration/hardlinks.go index 23c4916..6a95332 100644 --- a/internal/migration/hardlinks.go +++ b/internal/migration/hardlinks.go @@ -2,14 +2,6 @@ package migration import ( "bytes" - "context" - "encoding/binary" - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "syscall" "time" bolt "go.etcd.io/bbolt" @@ -82,138 +74,3 @@ func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) { return same, nil } - -func inodeIdentity(info os.FileInfo) ([16]byte, uint64, error) { - var key [16]byte - st, ok := info.Sys().(*syscall.Stat_t) - if !ok { - return key, 0, errors.New("missing Linux inode information") - } - - binary.BigEndian.PutUint64(key[:8], uint64(st.Dev)) - binary.BigEndian.PutUint64(key[8:], st.Ino) - return key, uint64(st.Nlink), nil -} - -// hardlinkTopology compares the hard-link groups of src and dst. -// In repair mode it removes only excess target hardlinks. Missing paths are then -// recreated by the copy backend. In verification mode check both directions: -// source groups must stay joined, and unrelated source files must stay separate. -func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repair bool) (result error) { - scratch, err := os.MkdirTemp(scratchParent, ".cephmig-links-") - if err != nil { - return err - } - - defer os.RemoveAll(scratch) - index, err := openLinkIndex(filepath.Join(scratch, "index.bolt")) - if err != nil { - return err - } - - defer func() { - if err := index.close(); result == nil { - result = err - } - }() - - targetPath := func(path string) (string, error) { - rel, err := filepath.Rel(src, path) - if err != nil || !beneath(src, path) { - return "", fmt.Errorf("hardlink path outside source: %s", path) - } - - return filepath.Join(dst, rel), nil - } - - visitDir := func(path string) error { - target, err := targetPath(path) - if err != nil { - return err - } - - st, err := os.Lstat(target) - if repair && (errors.Is(err, os.ErrNotExist) || (err == nil && !st.IsDir())) { - // Never follow a target symlink directory, even when its referent exists. - return fs.SkipDir - } - if err != nil { - return err - } - - if !st.IsDir() { - return fmt.Errorf("target directory changed type: %s", target) - } - - return nil - } - - visitFile := func(path string, sourceInfo os.FileInfo) error { - if !sourceInfo.Mode().IsRegular() { - return nil - } - - target, err := targetPath(path) - if err != nil { - return err - } - - targetInfo, err := os.Lstat(target) - if repair && errors.Is(err, os.ErrNotExist) { - return nil - } - if err != nil { - return err - } - - if !targetInfo.Mode().IsRegular() { - if repair { - return nil - } - - return fmt.Errorf("hardlink target is not a regular file: %s", target) - } - - sourceKey, sourceLinks, err := inodeIdentity(sourceInfo) - if err != nil { - return err - } - - targetKey, targetLinks, err := inodeIdentity(targetInfo) - if err != nil { - return err - } - - if !repair && sourceLinks > 1 { - same, err := index.observe("source", sourceKey, targetKey) - if err != nil { - return err - } - - if !same { - return fmt.Errorf("source hardlink group was split at %s", target) - } - } - - if targetLinks > 1 { - same, err := index.observe("target", targetKey, sourceKey) - if err != nil { - return err - } - - if !same { - if !repair { - return fmt.Errorf("unrelated source files became hardlinked at %s", target) - } - - if err := os.Remove(target); err != nil { - return fmt.Errorf("break obsolete target hardlink: %w", err) - } - } - } - - return nil - } - - return walkTree(ctx, src, visitDir, visitFile) -} diff --git a/internal/migration/hardlinks_test.go b/internal/migration/hardlinks_test.go index 15b8d1c..ca010c2 100644 --- a/internal/migration/hardlinks_test.go +++ b/internal/migration/hardlinks_test.go @@ -1,148 +1,11 @@ package migration import ( - "context" "encoding/binary" - "io" - "os" - "os/exec" "path/filepath" "testing" ) -func mustWrite(t *testing.T, path string) { - t.Helper() - if err := os.WriteFile(path, []byte("identical contents"), 0640); err != nil { - t.Fatal(err) - } -} - -func TestHardlinkTopologyHandlesSplitAndRejoin(t *testing.T) { - if _, err := exec.LookPath("rsync"); err != nil { - t.Skip("rsync is not installed") - } - - ctx := context.Background() - src, dst, scratch := t.TempDir(), t.TempDir(), t.TempDir() - if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil { - t.Fatal(err) - } - - a, b := filepath.Join(src, "a"), filepath.Join(src, "d", "b") - mustWrite(t, a) - if err := os.Link(a, b); err != nil { - t.Fatal(err) - } - - r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard} - if err := r.Copy(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil { - t.Fatal(err) - } - - // Break one source link without changing bytes, mode or mtime. Rsync -H - // alone can leave an extra target link in this exact case. - old, err := os.Stat(b) - if err != nil { - t.Fatal(err) - } - - if err = os.Remove(b); err != nil { - t.Fatal(err) - } - - mustWrite(t, b) - if err = os.Chtimes(b, old.ModTime(), old.ModTime()); err != nil { - t.Fatal(err) - } - - if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil { - t.Fatal("extra destination hardlink was missed") - } - - if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil { - t.Fatal(err) - } - - if err = r.Copy(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil { - t.Fatal(err) - } - - x, _ := os.Stat(filepath.Join(dst, "a")) - y, _ := os.Stat(filepath.Join(dst, "d", "b")) - if os.SameFile(x, y) { - t.Fatal("split source files remained linked") - } - - if err = os.Remove(b); err != nil { - t.Fatal(err) - } - - if err = os.Link(a, b); err != nil { - t.Fatal(err) - } - - if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil { - t.Fatal("missing target hardlink was missed") - } - - if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil { - t.Fatal(err) - } - - if err = r.Copy(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil { - t.Fatal(err) - } - - entries, err := os.ReadDir(scratch) - if err != nil || len(entries) != 0 { - t.Fatal("scratch indexes were not removed") - } -} - -func TestHardlinkRepairDoesNotFollowTargetSymlinkDirectories(t *testing.T) { - src, dst, outside, scratch := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir() - if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil { - t.Fatal(err) - } - - mustWrite(t, filepath.Join(src, "d", "a")) - mustWrite(t, filepath.Join(src, "d", "b")) - mustWrite(t, filepath.Join(outside, "a")) - if err := os.Link(filepath.Join(outside, "a"), filepath.Join(outside, "b")); err != nil { - t.Fatal(err) - } - - if err := os.Symlink(outside, filepath.Join(dst, "d")); err != nil { - t.Fatal(err) - } - - if err := hardlinkTopology(context.Background(), src, dst, scratch, true); err != nil { - t.Fatal(err) - } - - a, err := os.Stat(filepath.Join(outside, "a")) - if err != nil { - t.Fatal(err) - } - - b, err := os.Stat(filepath.Join(outside, "b")) - if err != nil || !os.SameFile(a, b) { - t.Fatal("repair touched files outside the target tree") - } -} - func TestHardlinkDiskIndexSurvivesBatchBoundaries(t *testing.T) { x, err := openLinkIndex(filepath.Join(t.TempDir(), "index")) if err != nil { diff --git a/internal/migration/linux.go b/internal/migration/linux.go index de7b401..6168db7 100644 --- a/internal/migration/linux.go +++ b/internal/migration/linux.go @@ -3,22 +3,13 @@ package migration import ( - "bufio" - "context" "errors" "fmt" - "io" - "io/fs" "os" "path/filepath" "strings" - "syscall" ) -func unescapeMount(s string) string { - return strings.NewReplacer("\\040", " ", "\\011", "\t", "\\012", "\n", "\\134", "\\").Replace(s) -} - func privateDirectories(path string) error { if !filepath.IsAbs(path) { return errors.New("directory path must be absolute") @@ -47,229 +38,3 @@ func privateDirectories(path string) error { return nil } - -func checkMount(root string, writable bool) error { - f, err := os.Open("/proc/self/mountinfo") - if err != nil { - return err - } - - defer f.Close() - scan := bufio.NewScanner(f) - found := false - for scan.Scan() { - parts := strings.SplitN(scan.Text(), " - ", 2) - if len(parts) != 2 { - continue - } - - fields, after := strings.Fields(parts[0]), strings.Fields(parts[1]) - if len(fields) < 6 || len(after) < 2 { - continue - } - - mount := unescapeMount(fields[4]) - if mount == root { - if after[0] != "ceph" && after[0] != "fuse.ceph-fuse" { - return fmt.Errorf("%s is not a CephFS mount", root) - } - - if writable && !strings.Contains(","+fields[5]+",", ",rw,") { - return fmt.Errorf("target %s must be mounted read-write", root) - } - - found = true - } else if beneath(root, mount) { - return fmt.Errorf("nested mount %s below %s is unsupported", mount, root) - } - } - - if err := scan.Err(); err != nil { - return err - } - - if !found { - return fmt.Errorf("%s must be a dedicated CephFS filesystem-root mount", root) - } - - resolved, err := filepath.EvalSymlinks(root) - if err != nil { - return err - } - - if resolved != root { - return errors.New("mount path must not contain symlinks") - } - - return nil -} - -func xattr(path, key string) ([]byte, error) { - for attempt := 0; attempt < 3; attempt++ { - n, err := syscall.Getxattr(path, key, nil) - if errors.Is(err, syscall.ENODATA) { - return []byte("0"), nil - } - if err != nil { - return nil, err - } - - if n > 1<<20 { - return nil, fmt.Errorf("xattr too large: %s", key) - } - - b := make([]byte, n) - n, err = syscall.Getxattr(path, key, b) - if errors.Is(err, syscall.ERANGE) { - continue - } - if err != nil { - return nil, err - } - - return b[:n], nil - } - - return nil, errors.New("xattr changed repeatedly") -} - -var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"} - -// walkDirectories calls visit for every directory below root. -func walkDirectories(ctx context.Context, root string, visit func(string) error) error { - return walkTree(ctx, root, visit, nil) -} - -// walkTree walks root depth-first, skipping .snap. ReadDir batches keep a -// single very large directory from exhausting memory. -func walkTree(ctx context.Context, root string, visitDir func(string) error, visitFile func(string, os.FileInfo) error) error { - var walk func(string, int) error - walk = func(path string, depth int) error { - if err := ctx.Err(); err != nil { - return err - } - - if depth > 128 { - return errors.New("directory depth exceeds supported limit (128)") - } - - if visitDir != nil { - if err := visitDir(path); errors.Is(err, fs.SkipDir) { - return nil - } else if err != nil { - return err - } - } - - f, err := os.Open(path) - if err != nil { - return err - } - - defer f.Close() - for { - batch, readErr := f.ReadDir(128) - for _, e := range batch { - if err := ctx.Err(); err != nil { - return err - } - - if e.Name() == ".snap" { - continue - } - - child := filepath.Join(path, e.Name()) - if e.IsDir() { - if err := walk(child, depth+1); err != nil { - return err - } - } else if visitFile != nil { - info, err := e.Info() - if err != nil { - return err - } - - if err = visitFile(child, info); err != nil { - return err - } - } - } - - if errors.Is(readErr, io.EOF) { - return nil - } - - if readErr != nil { - return readErr - } - } - } - - return walk(root, 0) -} - -func clearQuotas(ctx context.Context, root string) error { - return walkDirectories(ctx, root, func(path string) error { - for _, key := range quotaKeys { - old, err := xattr(path, key) - if err != nil { - return fmt.Errorf("read quota %s: %w", path, err) - } - - if string(old) == "0" { - continue - } - - if err := syscall.Setxattr(path, key, []byte("0"), 0); err != nil { - return fmt.Errorf("clear quota %s: %w", path, err) - } - } - - return nil - }) -} - -func quotas(ctx context.Context, src, dst string, verify bool) error { - return walkDirectories(ctx, src, func(path string) error { - rel, err := filepath.Rel(src, path) - if err != nil { - return err - } - - target := filepath.Join(dst, rel) - st, err := os.Lstat(target) - if err != nil { - return err - } - - if !st.IsDir() { - return fmt.Errorf("quota target is not a real directory: %s", target) - } - - for _, key := range quotaKeys { - value, err := xattr(path, key) - if err != nil { - return fmt.Errorf("source quota %s %s: %w", path, key, err) - } - - actual, err := xattr(target, key) - if err != nil { - return fmt.Errorf("target quota %s %s: %w", target, key, err) - } - - if string(value) == string(actual) { - continue - } - - if verify { - return fmt.Errorf("quota mismatch: %s %s", rel, key) - } - - if err := syscall.Setxattr(target, key, value, 0); err != nil { - return fmt.Errorf("set quota %s %s: %w", target, key, err) - } - } - - return nil - }) -} diff --git a/internal/migration/native_access.go b/internal/migration/native_access.go index 3a32ae4..1b8fccf 100644 --- a/internal/migration/native_access.go +++ b/internal/migration/native_access.go @@ -23,12 +23,12 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe return nil, err } - sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x, native: true}) + sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x}) if err != nil { return nil, err } - tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x, native: true}) + tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x}) if err != nil { return nil, err } @@ -59,7 +59,7 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe } } - names, err := (ceph{endpoint: c.Source, exec: x, native: true}).names(ctx) + names, err := (ceph{endpoint: c.Source, exec: x}).names(ctx) if err != nil { return nil, err } diff --git a/internal/migration/native_claim_test.go b/internal/migration/native_claim_test.go new file mode 100644 index 0000000..1130c5a --- /dev/null +++ b/internal/migration/native_claim_test.go @@ -0,0 +1,126 @@ +package migration + +import ( + "context" + "errors" + "os" + "path/filepath" + "syscall" + "testing" + + "git.zb-server.de/Sebi/CephfsMig/internal/storage" +) + +// rootFS is a storage.FS rooted at a local directory, with real flock +// locks, for the claim operations. +type rootFS struct { + storage.FS + root string +} + +func (f rootFS) path(p string) string { return filepath.Join(f.root, p) } + +func (f rootFS) Stat(p string) (storage.Node, error) { return diskFS{}.Stat(f.path(p)) } +func (f rootFS) Mkdir(p string, mode uint32) error { return os.Mkdir(f.path(p), os.FileMode(mode)) } +func (f rootFS) Unlink(p string) error { return syscall.Unlink(f.path(p)) } +func (f rootFS) Rmdir(p string) error { return syscall.Rmdir(f.path(p)) } +func (f rootFS) Close() error { return nil } + +func (f rootFS) Open(p string, flags int, mode uint32) (storage.File, error) { + file, err := os.OpenFile(f.path(p), flags, os.FileMode(mode)) + if err != nil { + return nil, err + } + + return lockingFile{diskFile{file}}, nil +} + +type lockingFile struct{ diskFile } + +func (f lockingFile) Lock(uint64) error { + return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) +} + +func claimAccess(root string) nativeAccess { + fs := rootFS{root: root} + return nativeAccess{&nativeTransport{target: fs, openTarget: func() (storage.FS, error) { return fs, nil }}} +} + +func TestNativeClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) { + ctx, c := context.Background(), testConfig() + a := claimAccess(t.TempDir()) + first, err := a.Claim(ctx, c, "fsid", "job-one") + if err != nil { + t.Fatal(err) + } + + if second, err := a.Claim(ctx, c, "fsid", "job-one"); err == nil { + second.Close() + t.Fatal("concurrent use allowed") + } + + if err := first.Close(); err != nil { + t.Fatal(err) + } + + if other, err := a.Claim(ctx, c, "fsid", "job-two"); err == nil { + other.Close() + t.Fatal("different job stole target") + } + + resumed, err := a.Claim(ctx, c, "fsid", "job-one") + if err != nil { + t.Fatal(err) + } + + resumed.Close() +} + +func TestNativeReleaseRemovesOnlyOwnClaim(t *testing.T) { + ctx, root := context.Background(), t.TempDir() + a := claimAccess(root) + c := testConfig() + other := c + other.Target.Subvolume = "other" + for _, x := range []struct { + c Config + id string + }{{c, "job-one"}, {other, "job-two"}} { + f, err := a.Claim(ctx, x.c, "fsid", x.id) + if err != nil { + t.Fatal(err) + } + + f.Close() + } + + if err := a.Release(ctx, c, "fsid", "job-two"); err == nil { + t.Fatal("removed the claim of a different job") + } + + if err := a.Release(ctx, c, "fsid", "job-one"); err != nil { + t.Fatal(err) + } + + claims := filepath.Join(root, ".cephmig", "claims") + if _, err := os.Stat(filepath.Join(claims, claimName("fsid", c.Target))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("own claim still present: %v", err) + } + + if _, err := os.Stat(filepath.Join(claims, claimName("fsid", other.Target))); err != nil { + t.Fatalf("claim of another job removed: %v", err) + } + + if err := a.Release(ctx, other, "fsid", "job-two"); err != nil { + t.Fatal(err) + } + + if _, err := os.Stat(filepath.Join(root, ".cephmig")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("empty claim directories kept: %v", err) + } + + // Releasing again is a no-op. + if err := a.Release(ctx, c, "fsid", "job-one"); err != nil { + t.Fatal(err) + } +} diff --git a/internal/migration/native_helpers.go b/internal/migration/native_helpers.go index eda8b46..3eb10c2 100644 --- a/internal/migration/native_helpers.go +++ b/internal/migration/native_helpers.go @@ -18,6 +18,9 @@ import ( // the entries below it. var errSkipSubtree = errors.New("skip subtree") +// quotaKeys are the directory quota xattrs that the migration copies. +var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"} + func walkNative(ctx context.Context, fs storage.FS, root string, visit func(string, storage.Node, int) error) error { var walk func(string, storage.Node, int) error walk = func(p string, n storage.Node, depth int) error { diff --git a/internal/migration/process_test.go b/internal/migration/process_test.go new file mode 100644 index 0000000..2262733 --- /dev/null +++ b/internal/migration/process_test.go @@ -0,0 +1,27 @@ +package migration + +import ( + "context" + "io" + "testing" + "time" +) + +func TestProcessCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.Canceled { + t.Fatalf("got %v", err) + } + + ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + start := time.Now() + if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.DeadlineExceeded { + t.Fatalf("got %v", err) + } + + if time.Since(start) > 2*time.Second { + t.Fatal("cancellation was too slow") + } +} diff --git a/internal/migration/rsync.go b/internal/migration/rsync.go deleted file mode 100644 index 500bb5a..0000000 --- a/internal/migration/rsync.go +++ /dev/null @@ -1,82 +0,0 @@ -package migration - -import ( - "context" - "errors" - "fmt" - "io" - "os/exec" - "strconv" - "strings" -) - -// Transport copies a snapshot tree to the target and verifies the result. -type Transport interface { - Copy(context.Context, string, string) error - Verify(context.Context, string, string) error -} - -// Rsync is the Transport that copies between mounted CephFS trees with -// rsync. BandwidthKiB limits the transfer rate when positive. -type Rsync struct { - Exec Executor - Log io.Writer - BandwidthKiB int64 -} - -func (r Rsync) args(src, dst string) []string { - a := []string{"-aHAXS", "--numeric-ids", "--checksum", "--no-whole-file", - "--delete-during", "--partial", "--fsync", "--one-file-system", - "--filter=- .snap/", "--filter=-x ceph.*", "--filter=-x system.*"} - - if r.BandwidthKiB > 0 { - a = append(a, "--bwlimit="+strconv.FormatInt(r.BandwidthKiB, 10)) - } - - return append(a, "--", src+"/", dst+"/") -} - -// Copy mirrors src into dst, including hard links, ACLs and xattrs. -func (r Rsync) Copy(ctx context.Context, src, dst string) error { - for attempt := 0; attempt < 2; attempt++ { - err := r.Exec.Exec(ctx, r.Log, "rsync", r.args(src, dst)...) - var processError *ProcessError - var exitError *exec.ExitError - // EEXIST was observed on Ceph-FUSE while rsync rebuilt a hardlink group. - // One idempotent retry repairs the partial group. All other errors - // are returned immediately; publication still requires full verification. - if attempt == 0 && errors.As(err, &processError) && errors.As(err, &exitError) && exitError.ExitCode() == 23 && strings.Contains(processError.Diagnostic, "link ") && strings.Contains(processError.Diagnostic, "File exists (17)") { - if r.Log != nil { - fmt.Fprintln(r.Log, "rsync hardlink EEXIST: retrying once before snapshot verification") - } - - continue - } - - return err - } - - return errors.New("rsync retry limit reached") -} - -type differences struct{ n int64 } - -func (d *differences) Write(p []byte) (int, error) { - d.n += int64(len(p)) - return len(p), nil -} - -// Verify runs rsync as a dry run and fails if any difference remains. -func (r Rsync) Verify(ctx context.Context, src, dst string) error { - args := append([]string{"--dry-run", "--itemize-changes", "--out-format=%i"}, r.args(src, dst)...) - var d differences - if err := r.Exec.Exec(ctx, &d, "rsync", args...); err != nil { - return err - } - - if d.n != 0 { - return fmt.Errorf("verification found differences between %s and %s", src, dst) - } - - return nil -} diff --git a/internal/migration/rsync_test.go b/internal/migration/rsync_test.go deleted file mode 100644 index e9edf09..0000000 --- a/internal/migration/rsync_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package migration - -import ( - "context" - "errors" - "io" - "os" - "os/exec" - "path/filepath" - "strings" - "syscall" - "testing" - "time" -) - -type executorFunc func(context.Context, io.Writer, string, ...string) error - -func (f executorFunc) Exec(ctx context.Context, out io.Writer, name string, args ...string) error { - return f(ctx, out, name, args...) -} - -func TestRsyncRetriesOnlyObservedHardlinkEEXIST(t *testing.T) { - exitErr := exec.Command("sh", "-c", "exit 23").Run() - for name, tc := range map[string]struct { - diagnostic string - attempts int - }{ - "hardlink": {"link target failed: File exists (17)", 2}, - "permission": {"Permission denied (13)", 1}, - "other-eexist": {"mkdir failed: File exists (17)", 1}, - } { - t.Run(name, func(t *testing.T) { - calls := 0 - x := executorFunc(func(context.Context, io.Writer, string, ...string) error { - calls++ - if calls == 1 { - return &ProcessError{Name: "rsync", Err: exitErr, Diagnostic: tc.diagnostic} - } - - return nil - }) - - err := (Rsync{Exec: x, Log: io.Discard}).Copy(context.Background(), "/a", "/b") - if calls != tc.attempts { - t.Fatalf("attempts: %d", calls) - } - - if (err == nil) != (tc.attempts == 2) { - t.Fatalf("unexpected result: %v", err) - } - }) - } - - calls := 0 - x := executorFunc(func(context.Context, io.Writer, string, ...string) error { calls++; return context.Canceled }) - err := (Rsync{Exec: x}).Copy(context.Background(), "/a", "/b") - if !errors.Is(err, context.Canceled) || calls != 1 { - t.Fatalf("retried cancellation: %v, %d", err, calls) - } -} - -func TestRsyncDetectsSameSizeSameMtimeAndPreservesLinks(t *testing.T) { - if _, err := exec.LookPath("rsync"); err != nil { - t.Skip("rsync is not installed") - } - - src, dst := t.TempDir(), t.TempDir() - path := filepath.Join(src, "file with spaces\nand newline") - if err := os.WriteFile(path, []byte("AAAA"), 0640); err != nil { - t.Fatal(err) - } - - if err := os.Link(path, filepath.Join(src, "hardlink")); err != nil { - t.Fatal(err) - } - - if err := os.Symlink("nonexistent", filepath.Join(src, "dangling")); err != nil { - t.Fatal(err) - } - - if err := syscall.Setxattr(path, "user.cephmig", []byte("test"), 0); err != nil { - t.Fatal(err) - } - - r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard} - ctx := context.Background() - if err := r.Copy(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if err := r.Verify(ctx, src, dst); err != nil { - t.Fatal(err) - } - - a, _ := os.Stat(filepath.Join(dst, "hardlink")) - b, _ := os.Stat(filepath.Join(dst, filepath.Base(path))) - if !os.SameFile(a, b) { - t.Fatal("hardlinks were split") - } - - st, err := os.Stat(path) - if err != nil { - t.Fatal(err) - } - - if err = os.WriteFile(path, []byte("BBBB"), 0640); err != nil { - t.Fatal(err) - } - - if err = os.Chtimes(path, st.ModTime(), st.ModTime()); err != nil { - t.Fatal(err) - } - - if err = r.Verify(ctx, src, dst); err == nil { - t.Fatal("checksum verification missed changed bytes") - } - - if err = os.WriteFile(filepath.Join(dst, "obsolete"), []byte("extra"), 0600); err != nil { - t.Fatal(err) - } - - if err = r.Copy(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if err = r.Verify(ctx, src, dst); err != nil { - t.Fatal(err) - } - - if _, err = os.Stat(filepath.Join(dst, "obsolete")); !os.IsNotExist(err) { - t.Fatal("obsolete target file survived") - } - - got, err := xattr(filepath.Join(dst, "hardlink"), "user.cephmig") - if err != nil || string(got) != "test" { - t.Fatalf("xattr: %q, %v", got, err) - } -} - -func TestProcessCancellation(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.Canceled { - t.Fatalf("got %v", err) - } - - ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - start := time.Now() - if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.DeadlineExceeded { - t.Fatalf("got %v", err) - } - - if time.Since(start) > 2*time.Second { - t.Fatal("cancellation was too slow") - } -} - -func TestRsyncUsesIncrementalSafeOptions(t *testing.T) { - joined := strings.Join((Rsync{BandwidthKiB: 1024}).args("/source", "/target"), " ") - for _, required := range []string{"-aHAXS", "--checksum", "--delete-during", "--no-whole-file", "--fsync", "--bwlimit=1024", "--filter=-x ceph.*"} { - if !strings.Contains(joined, required) { - t.Fatalf("missing %s", required) - } - } - - for _, bad := range []string{"--inplace", "--delete-before", "--delete-after", "--delay-updates"} { - if strings.Contains(joined, bad) { - t.Fatalf("unsafe option %s", bad) - } - } -} diff --git a/internal/migration/state_test.go b/internal/migration/state_test.go index 35fa5a1..0361cc7 100644 --- a/internal/migration/state_test.go +++ b/internal/migration/state_test.go @@ -115,33 +115,6 @@ func TestLockExclusionAndRelease(t *testing.T) { third.Close() } -func TestTargetClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) { - root := t.TempDir() - c := testConfig() - first, err := claimTarget(root, "fsid", c.Target, "job-one") - if err != nil { - t.Fatal(err) - } - - if second, err := claimTarget(root, "fsid", c.Target, "job-one"); err == nil { - second.Close() - t.Fatal("concurrent use allowed") - } - - first.Close() - if other, err := claimTarget(root, "fsid", c.Target, "job-two"); err == nil { - other.Close() - t.Fatal("different job stole target") - } - - resumed, err := claimTarget(root, "fsid", c.Target, "job-one") - if err != nil { - t.Fatal(err) - } - - resumed.Close() -} - func TestStateAndLockRejectSymlinks(t *testing.T) { root := t.TempDir() real := filepath.Join(root, "real")