commit 7705ed3eaf5ce921c8169a4639c2d4c68ebf8c03 Author: Sebastian Unterschütz Date: Thu Dec 3 18:05:53 2026 +0100 chore: import CephMig prototype Initial import of the existing CephFS subvolume migration prototype, including the native libcephfs transport, rsync backend, local Ceph lab environment and integration tests. Co-Authored-By: Claude Opus 5.5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ca0b803 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +bin/ +.idea/ +.git/ +.agents/ +.aws/ +.codex/ +.dev/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eec8894 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/bin/ +/.dev/ +/.env +/.idea/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..16e3d4d --- /dev/null +++ b/Makefile @@ -0,0 +1,43 @@ +.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 +build: + go build -buildvcs=false -o bin/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 + 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 . doctor +dev-config: + docker compose -f dev/compose.yaml config --quiet +dev-up: + docker compose -f dev/compose.yaml up -d --wait --wait-timeout 300 +dev-down: + docker compose -f dev/compose.yaml down +dev-status: + docker compose -f dev/compose.yaml ps + docker compose -f dev/compose.yaml exec source ceph -s + docker compose -f dev/compose.yaml exec target ceph -s +dev-smoke: + docker compose -f dev/compose.yaml exec client timeout --kill-after=10s 90s bash /lab/smoke.sh +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 + docker compose -f dev/compose.yaml up -d --wait --wait-timeout 300 native + bash dev/native-test.sh +dev-smallfiles-test: dev-native-build + docker compose -f dev/compose.yaml up -d --wait --wait-timeout 300 client native + bash dev/smallfiles-test.sh +dev-million-start: dev-native-build + bash dev/million-start.sh +dev-million-status: + docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml ps -a + python3 -m json.tool .dev/million/main/status.json +dev-million-finish: + bash dev/million-finish.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..59d0016 --- /dev/null +++ b/README.md @@ -0,0 +1,156 @@ +# CephMig + +Go-Prototyp zur Migration eines CephFS-Subvolumes zwischen zwei Clustern, +mit nativem libcephfs-Transport, lokaler Entwicklungsumgebung und Integrationstests. +Der native Kopierer benötigt weder rsync noch einen Kernel-/FUSE-Mount. +Er überträgt den ersten Stand vollständig und verwendet danach Snapdiff und +bei geeigneten Dateien Blockdiff. Metadaten werden durch den Ziel-MDS angelegt; +die erforderlichen Daten überträgt der native Ceph-Client. + +**Dokumentierte Abweichung:** Native Snapshot-IDs und Ceph-Geburtszeitpunkte +werden am Ziel neu vergeben. Die Migration läuft damit weiter und vermerkt +die Abweichung in Ausgabe und Journal; ursprüngliche Erstellungszeiten bleiben +im Journal erhalten. Das entspricht der zuletzt vereinbarten Anforderung. +Kommandos, Grenzen und Nachweise stehen in [docs/migration.md](docs/migration.md). + +Vereinbarte Anforderungen: neueste stabile Ceph-Hauptversion, direkte Kernel- +oder FUSE-Mounts, Kopieren bei laufender Anwendung und ein kurzer Schreibstopp +für den finalen Abgleich und die Umschaltung. + +## Voraussetzungen + +- Linux mit Docker Engine und Docker Compose, Zugriff auf den Docker-Daemon. +- Go ab 1.25 und GNU Make. +- `/dev/fuse` auf dem Docker-Host für den unabhängigen Testclient; dieser läuft privilegiert. +- Bis zu 12 GiB Container-RAM und zwei dateibasierte 4-GiB-OSDs, zusätzlich Images. + +## Entwicklungsumgebung + +```sh +make doctor +make build +make check +make dev-config +make dev-up +make dev-status +make dev-smoke +make dev-native-test +make dev-smallfiles-test +make dev-migration-test +make dev-restart-check +make dev-shell +``` + +`make build` erzeugt `bin/cephmig`. Kommandos: `doctor`, `inspect`, `sync`, +`finalize` und `status`; Details zeigt `bin/cephmig --help`. +Dieser portable Build enthält das rsync-Backend. `make dev-native-build` baut +`cephmig-native:dev` mit CGO und den passenden Ceph-Headern; dabei laufen auch +die Go-Tests mit Race Detector und `go vet` für den nativen Build. +`dev/migration.example.json` wählt das native Backend. Beispiel: + +```sh +docker compose -f dev/compose.yaml exec native cephmig-native inspect \ + --config /lab/migration.example.json +``` + +Der Dienst `native` läuft ohne privilegierten Modus, ohne `/dev/fuse` und ohne +CephFS-Mounts. Der separate privilegierte `client` dient als unabhängiger +Anwendungsclient und für den rsync-Vergleichstest. + +`make dev-smallfiles-test` prüft standardmäßig 10.000 Dateien mit jeweils +128 Byte Inhalt, zusätzlich Hardlinks und Symlinks. Die Hälfte der Dateien +liegt in einem großen Verzeichnis, die andere verteilt auf 50 Unterverzeichnisse. +Der Test misst Erstübertragung, Änderungsabgleich und finalen Abgleich einschließlich +Prüfung. Ein separater Anwendungsclient vergleicht danach alle Inhalte, Metadaten +und Snapshot-Stände. Berichte liegen unter `/tmp/cephmig-smallfiles-report`; +erfolgreiche Testdaten und Snapshots werden entfernt. Die Dateianzahl lässt sich +beispielsweise mit `FILES=2000 make dev-smallfiles-test` begrenzen. +Ein dokumentierter lokaler Lauf einschließlich Vorher-/Nachher-Zählern für +MDS-Anfragen steht in [docs/smallfiles-local.md](docs/smallfiles-local.md). +Der getrennte Test mit einer Million Dateien und vier Snapshot-Ständen wird +mit `make dev-million-start` gestartet; Speicherbedarf, Status und Bereinigung +stehen in [docs/million-local.md](docs/million-local.md). +VCS-Stamping ist im Build deaktiviert, damit auch ein +Quellverzeichnis ohne nutzbare Git-Metadaten gebaut werden kann. + +Der Smoke-Test erstellt einen Subvolume-Snapshot, verändert danach die Quelle +und kopiert den unveränderten Snapshot zum Ziel. Er prüft Inhalte, Dateirechte, +POSIX-ACLs, ein Benutzer-xattr, Hardlinks, Symlinks, Quota-Operationen und die +Isolation der beiden Cluster. `make dev-restart-check` startet das Labor neu +und prüft, dass FSIDs und Daten beider Subvolumes erhalten bleiben. +Die Sparse-Testdatei wird auf ihren Inhalt geprüft; die physische Platzbelegung +ist keine Zusicherung dieses Tests. + +`source` und `target` sind unabhängige Ceph-Cluster mit unterschiedlichen FSIDs +und Schlüsseln. Jeder enthält MON, MGR, OSD und MDS sowie das Dateisystem +`cephfs`, die Subvolume-Gruppe `migration` und das Subvolume `demo`. +Der Client mountet diese Subvolumes unter `/mnt/source` und `/mnt/target`. +Für die von der Ceph-API gelieferten Snapshotpfade ist das Quelldateisystem +zusätzlich unter `/mnt/source-fs` und das Ziel unter `/mnt/target-fs` gemountet; +Subvolume-Snapshots liegen außerhalb +des aktuellen Daten-UUID-Verzeichnisses. +Es werden keine Host-Geräte formatiert und keine Ports am Host veröffentlicht. +Die OSD-Daten liegen in Docker-Volumes. Die Replikationszahl 1 und die +Administratorschlüssel im Testclient dienen ausschließlich dem lokalen Labor. +Der Client ergänzt das feste Ceph-Basisimage um die festgeschriebene +rsync-Paketversion. Das Journal kann unter `/state` in einem eigenen +Docker-Volume dauerhaft gespeichert werden. + +```sh +# Status und Logs +docker compose -f dev/compose.yaml logs --tail 100 source target client + +# Ceph CLI gegen den Quellcluster +docker compose -f dev/compose.yaml exec source ceph fs subvolume info cephfs demo --group_name migration + +# Stoppen; die Daten bleiben für den nächsten Start erhalten +make dev-down +``` + +Für einen vollständig frischen Testlauf löscht +`docker compose -f dev/compose.yaml down --volumes` **alle Labordaten**. +Das Basisimage lässt sich mit `CEPH_IMAGE=quay.io/ceph/ceph:` ändern. +Die Dockerfiles enthalten Paket- und SDK-Pins für Ceph 21.2.0 / EL10; bei einem +Versionswechsel müssen diese passend angepasst werden. +Die Baseline ist Ceph Umbrella 21.2.0 gemäß der +[offiziellen Releaseübersicht](https://docs.ceph.com/en/latest/releases/), +geprüft am 05.11.2026. +Das veröffentlichte Containerimage trägt intern den Versionszusatz `dev`; +für die Reproduzierbarkeit ist zusätzlich der Image-Digest festgeschrieben. +Der Bootstrap legt die Pools mit expliziten PG-Zahlen an, da das Standardkommando +`fs volume create` in diesem Image mit `EINVAL` scheiterte. + +`ceph health detail` kann im Labor `POOL_NO_REDUNDANCY` (ein OSD) und +`MON_DISK_LOW` (weniger als 30 % freier Platz im Host-Dateisystem) melden. +Diese Meldungen werden nicht unterdrückt. Container-Healthchecks prüfen die +Nutzbarkeit des Subvolumes; sie ersetzen keine Produktions-Healthchecks. + +## Migrationsablauf + +Zielgröße: bis zu 200 TB und mehr als 200 Millionen Dateien, einschließlich +vorhandener Snapshots, POSIX-ACLs, xattrs und Quotas. Pro Node stehen zwei +25-Gbit/s-Verbindungen zur Verfügung; effektiver Durchsatz und eine feste +Obergrenze für den Schreibstopp werden später bestimmt. Die lokale Umgebung prüft +Funktionen, bildet diese Datenmenge jedoch nicht ab. Der native Kopierer verwendet +begrenzte Worker und Puffer, einen dauerhaften Index auf lokalem Datenträger und +optionale Bandbreitendrosselung. Vollständige Metadatenscans bleiben erforderlich. +Ein Nachweis für Speicher, Indexgröße, Laufzeit und finalen Schreibstopp fehlt. + +1. Quelle, Ziel, Berechtigungen, Kapazität und benötigte Metadaten prüfen. +2. Konsistenten Quellsnapshot erstellen und initial bei laufender Anwendung kopieren. +3. Änderungen mit weiteren Snapshots und Abgleichen nachziehen. +4. Alle schreibenden Anwendungen anhalten, offene Schreibvorgänge abschließen, + letzten Snapshot übertragen und Daten sowie Metadaten verifizieren. +5. Clients auf das Ziel ummounten und Anwendungen freigeben. + +Ein Dateisystemsnapshot allein stellt keine Anwendungskonsistenz für Datenbanken +her. Der finale Schreibstopp muss alle Clients umfassen. Ein Umhängen eines +Mounts übernimmt keine bereits offenen Dateideskriptoren. Nach ersten +Schreibzugriffen am Ziel benötigt ein Rückwechsel einen erneuten Abgleich. +Die derzeit implementierte Datenübertragung ist im Labormodus prüfbar; +produktive Umschaltung und Lastnachweise für die Zielgröße sind noch offen. + +Die Umgebung folgt dem +[manuellen Ceph-Bootstrap](https://docs.ceph.com/en/latest/install/manual-deployment/). +Die Einordnung des direkten RADOS-Objektimports und die Grenzen der nativen +Implementierung stehen in [docs/raw-transfer.md](docs/raw-transfer.md). diff --git a/cmd/nativeprobe/main_ceph.go b/cmd/nativeprobe/main_ceph.go new file mode 100644 index 0000000..4e13f1f --- /dev/null +++ b/cmd/nativeprobe/main_ceph.go @@ -0,0 +1,57 @@ +//go:build ceph && cgo + +package main + +import ( + "CephMig/internal/cephfsnative" + "CephMig/internal/storage" + "encoding/json" + "flag" + "fmt" + "io" + "os" +) + +func main() { + config := flag.String("config", "/lab/migration.example.json", "config") + root := flag.String("root", "/", "path to stat, or snapshot root") + rel := flag.String("rel", ".", "relative snapshot path") + a := flag.String("from", "", "previous snapshot") + b := flag.String("to", "", "current snapshot") + flag.Parse() + data, err := os.ReadFile(*config) + if err != nil { + panic(err) + } + var c struct{ Source storage.Options } + if err = json.Unmarshal(data, &c); err != nil { + panic(err) + } + fs, err := cephfsnative.Open(c.Source) + if err != nil { + panic(err) + } + defer fs.Close() + n, err := fs.Stat(*root) + if err != nil { + panic(err) + } + json.NewEncoder(os.Stdout).Encode(n) + if *a != "" { + d, err := fs.SnapDiff(*root, *rel, *a, *b) + if err != nil { + panic(err) + } + defer d.Close() + for { + name, err := d.Next() + if err == io.EOF { + break + } + if err != nil { + panic(err) + } + fmt.Printf("diff: %q\n", name) + } + } +} diff --git a/dev/Dockerfile.client b/dev/Dockerfile.client new file mode 100644 index 0000000..099db00 --- /dev/null +++ b/dev/Dockerfile.client @@ -0,0 +1,4 @@ +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/Dockerfile.native b/dev/Dockerfile.native new file mode 100644 index 0000000..65d873e --- /dev/null +++ b/dev/Dockerfile.native @@ -0,0 +1,20 @@ +ARG CEPH_IMAGE=quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d +FROM ${CEPH_IMAGE} AS build +RUN dnf install -y gcc golang-1.26.10-1.el10_2 \ + https://download.ceph.com/rpm-21.2.0/el10/x86_64/libcephfs-devel-21.2.0-0.el10.x86_64.rpm \ + https://download.ceph.com/rpm-21.2.0/el10/x86_64/libcephfs-proxy2-21.2.0-0.el10.x86_64.rpm \ + https://download.ceph.com/rpm-21.2.0/el10/x86_64/librados-devel-21.2.0-0.el10.x86_64.rpm \ + && dnf clean all +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=1 go test -race -tags ceph ./... \ + && CGO_ENABLED=1 go vet -tags ceph ./... \ + && CGO_ENABLED=1 go build -buildvcs=false -tags ceph -o /out/native-probe ./cmd/nativeprobe \ + && CGO_ENABLED=1 go build -buildvcs=false -tags ceph -o /out/cephmig-native . + +FROM ${CEPH_IMAGE} +COPY --from=build /out/ /usr/local/bin/ +ENTRYPOINT ["/usr/local/bin/cephmig-native"] diff --git a/dev/client.sh b/dev/client.sh new file mode 100644 index 0000000..8d30ea1 --- /dev/null +++ b/dev/client.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +mkdir -p /mnt/source /mnt/target /mnt/source-fs /mnt/target-fs +pids=() +cleanup() { + trap - EXIT TERM INT + umount /mnt/source /mnt/target /mnt/source-fs /mnt/target-fs 2>/dev/null || true + if ((${#pids[@]})); then + kill "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + fi +} +trap cleanup EXIT +trap 'exit 0' TERM INT +for cluster in source target; do + ceph-fuse -f -c "/clusters/$cluster/ceph.conf" \ + -k "/clusters/$cluster/ceph.client.admin.keyring" \ + --client-fs cephfs -r "$(cat "/clusters/$cluster/subvolume-path")" \ + "/mnt/$cluster" & + pids+=("$!") +done +# Administrative mount for snapshot getpath results (outside the data UUID). +for cluster in source target; do + ceph-fuse -f -c "/clusters/$cluster/ceph.conf" \ + -k "/clusters/$cluster/ceph.client.admin.keyring" --client-fs cephfs "/mnt/$cluster-fs" & + pids+=("$!") +done +wait -n "${pids[@]}" +exit 1 diff --git a/dev/cluster.sh b/dev/cluster.sh new file mode 100644 index 0000000..0da0f57 --- /dev/null +++ b/dev/cluster.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +umask 077 +: "${CLUSTER_NAME:?set CLUSTER_NAME}" +CEPHMIG_OSD_GIB=${CEPHMIG_OSD_GIB:-4} +if [[ ! $CEPHMIG_OSD_GIB =~ ^[0-9]+$ ]] || ((10#$CEPHMIG_OSD_GIB < 4 || 10#$CEPHMIG_OSD_GIB > 64)); then + echo 'CEPHMIG_OSD_GIB must be an integer between 4 and 64' >&2; exit 1 +fi +block_bytes=$((10#$CEPHMIG_OSD_GIB * 1024 * 1024 * 1024)) +rm -f /run/cephmig-ready +mkdir -p /state/{mon,osd,mgr,mds} /etc/ceph /run/ceph +pids=() +cleanup() { + trap - EXIT TERM INT + rm -f /run/cephmig-ready + if ((${#pids[@]})); then + kill "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + fi +} +trap cleanup EXIT +trap 'exit 0' TERM INT +start() { "$@" & pids+=("$!"); } +retry() { + local attempt + for ((attempt=0; attempt<90; attempt++)); do + if "$@"; then return 0; fi + sleep 2 + done + echo "Timeout: $*" >&2 + return 1 +} +if [[ ! -f /state/fsid ]]; then cat /proc/sys/kernel/random/uuid > /state/fsid; fi +ip=$(hostname -i | awk '{print $1}') +cat > /etc/ceph/ceph.conf < /state/osd-uuid; fi + ceph osd new "$(cat /state/osd-uuid)" 0 + ceph-osd -i 0 --mkfs --mkkey --osd-uuid "$(cat /state/osd-uuid)" --no-mon-config +fi +ceph auth add osd.0 osd 'allow *' mon 'allow profile osd' mgr 'allow profile osd' \ + -i /state/osd/keyring +start ceph-osd -i 0 -f +retry bash -c 'ceph osd stat --format json | python3 -c '\''import json,sys; s=json.load(sys.stdin); sys.exit(s["num_up_osds"] != 1)'\''' +ceph auth get-or-create mds.a mon 'allow profile mds' mgr 'allow profile mds' \ + osd 'allow rw tag cephfs *=*' mds 'allow' -o /state/mds/keyring +start ceph-mds -i a -f +# Explicit PG counts avoid an EINVAL in Umbrella's volume-create pool defaults. +retry ceph osd pool create cephfs.cephfs.meta 8 +retry ceph osd pool create cephfs.cephfs.data 8 +retry ceph fs new cephfs cephfs.cephfs.meta cephfs.cephfs.data +retry ceph fs subvolumegroup create cephfs migration +retry ceph fs subvolume create cephfs demo --group_name migration +ceph fs subvolume getpath cephfs demo --group_name migration > /etc/ceph/subvolume-path +touch /run/cephmig-ready +echo "Cluster $CLUSTER_NAME ready" +wait -n "${pids[@]}" +exit 1 diff --git a/dev/compose.million.yaml b/dev/compose.million.yaml new file mode 100644 index 0000000..5628a50 --- /dev/null +++ b/dev/compose.million.yaml @@ -0,0 +1,33 @@ +# Always run with -p cephmig-million; its volumes are separate from cephmig-dev. +services: + source: + environment: + CEPHMIG_OSD_GIB: "24" + CEPHMIG_MDS_CACHE_BYTES: "805306368" + target: + environment: + CEPHMIG_OSD_GIB: "24" + CEPHMIG_MDS_CACHE_BYTES: "805306368" + client: + profiles: [fuse] + native: + profiles: [manual] + benchmark: + image: cephmig-native:dev + init: true + entrypoint: [python3, -u, /lab/million.py] + networks: [lab] + depends_on: + source: {condition: service_healthy} + target: {condition: service_healthy} + mem_limit: 2g + stop_grace_period: 45s + volumes: + - source-config:/clusters/source:ro + - target-config:/clusters/target:ro + - ./:/lab:ro + - migration-state:/state + - ../.dev/million:/report + logging: + driver: json-file + options: {max-size: 10m, max-file: '2'} diff --git a/dev/compose.yaml b/dev/compose.yaml new file mode 100644 index 0000000..ef28ea1 --- /dev/null +++ b/dev/compose.yaml @@ -0,0 +1,89 @@ +name: cephmig-dev +x-ceph: &ceph + image: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d} + init: true + stop_grace_period: 30s + networks: [lab] + logging: + driver: json-file + options: {max-size: 10m, max-file: '3'} + ulimits: + core: 0 +x-cluster: &cluster + <<: *ceph + entrypoint: [bash, /lab/cluster.sh] + healthcheck: + test: [CMD-SHELL, 'test -f /run/cephmig-ready && ceph fs subvolume getpath cephfs demo --group_name migration >/dev/null'] + interval: 5s + timeout: 10s + retries: 60 + mem_limit: 4g +services: + native: + <<: *ceph + image: cephmig-native:dev + build: + context: .. + dockerfile: dev/Dockerfile.native + args: + CEPH_IMAGE: ${CEPH_IMAGE:-quay.io/ceph/ceph:v21.2.0@sha256:c9e6ed4ac3fcf67b28f38358bb9619dee4d1dfb96ddd4b9b583eee316a15f04d} + entrypoint: [sleep, infinity] + depends_on: + source: {condition: service_healthy} + target: {condition: service_healthy} + volumes: + - source-config:/clusters/source:ro + - target-config:/clusters/target:ro + - ./:/lab:ro + - migration-state:/state + mem_limit: 2g + source: + <<: *cluster + hostname: source + environment: {CLUSTER_NAME: source} + volumes: + - source-state:/state + - source-config:/etc/ceph + - ./:/lab:ro + target: + <<: *cluster + hostname: target + environment: {CLUSTER_NAME: target} + volumes: + - target-state:/state + - target-config:/etc/ceph + - ./:/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] + depends_on: + source: {condition: service_healthy} + target: {condition: service_healthy} + volumes: + - 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'] + interval: 5s + timeout: 5s + retries: 30 + mem_limit: 2g +networks: + lab: {} +volumes: + source-state: {} + target-state: {} + source-config: {} + target-config: {} + migration-state: {} diff --git a/dev/migration-test.sh b/dev/migration-test.sh new file mode 100644 index 0000000..38a3998 --- /dev/null +++ b/dev/migration-test.sh @@ -0,0 +1,214 @@ +#!/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 +completed=true +echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization' + diff --git a/dev/migration.example.json b/dev/migration.example.json new file mode 100644 index 0000000..52ce363 --- /dev/null +++ b/dev/migration.example.json @@ -0,0 +1,20 @@ +{ + "backend": "native", + "source": { + "config": "/clusters/source/ceph.conf", + "keyring": "/clusters/source/ceph.client.admin.keyring", + "filesystem": "cephfs", + "group": "migration", + "subvolume": "demo", + "mount": "/mnt/source-fs" + }, + "target": { + "config": "/clusters/target/ceph.conf", + "keyring": "/clusters/target/ceph.client.admin.keyring", + "filesystem": "cephfs", + "group": "migration", + "subvolume": "demo", + "mount": "/mnt/target-fs" + }, + "bandwidth_kib": 0 +} diff --git a/dev/million-await.sh b/dev/million-await.sh new file mode 100644 index 0000000..ec9fe23 --- /dev/null +++ b/dev/million-await.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Wait for Docker's completion event; no status polling. +set -Eeuo pipefail +cd "$(dirname "$0")/.." +exit_code=$(docker wait cephmig-million-benchmark-1) +if [[ $exit_code != 0 ]]; then + echo "Benchmark exited $exit_code; retaining test data and diagnostics." >&2 + exit 1 +fi +exec bash dev/million-finish.sh diff --git a/dev/million-finish.sh b/dev/million-finish.sh new file mode 100644 index 0000000..748379f --- /dev/null +++ b/dev/million-finish.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Save a completed run, then release only this isolated test project's volumes. +set -Eeuo pipefail +cd "$(dirname "$0")/.." +compose=(docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml) +python3 - <<'PY' +import json,pathlib +s=json.loads(pathlib.Path('.dev/million/main/status.json').read_text()) +if s.get('result') != 'PASS': + raise SystemExit('Refusing cleanup: independent million-file verification has not passed') +PY +# PASS is written just before the independent writer shuts down. +exit_code=$(docker wait cephmig-million-benchmark-1) +[[ $exit_code = 0 ]] || { echo "Benchmark exited $exit_code; retaining diagnostics" >&2; exit 1; } +mkdir -p .dev/million/summary +for cluster in source target; do + "${compose[@]}" exec -T "$cluster" ceph df --format json > ".dev/million/summary/$cluster-capacity.json" + "${compose[@]}" exec -T "$cluster" ceph health detail --format json > ".dev/million/summary/$cluster-health.json" + "${compose[@]}" exec -T "$cluster" python3 -c ' +import os,json +s=os.stat("/state/osd/block") +print(json.dumps(dict(logical_bytes=s.st_size,allocated_bytes=s.st_blocks*512)))' > ".dev/million/summary/$cluster-host-allocation.json" +done +docker inspect cephmig-million-benchmark-1 --format '{{.Image}}' > .dev/million/native-image.txt +python3 - <<'PY' +import datetime,json,pathlib +root=pathlib.Path('.dev/million/main') +def read(name): return json.loads((root/name).read_text()) +def sample(name): return json.loads((pathlib.Path('.dev/million/summary')/name).read_text()) +result=dict(status=read('status.json'),migration=read('migration-state.json'), + phases={phase:read(phase+'.metrics.json') for phase in ('initial','catchup','final')}, + ceph_capacity={c:sample(c+'-capacity.json') for c in ('source','target')}, + ceph_health={c:sample(c+'-health.json') for c in ('source','target')}, + host_osd_allocation={c:sample(c+'-host-allocation.json') for c in ('source','target')}, + image=pathlib.Path('.dev/million/native-image.txt').read_text().strip(), + recorded_at=datetime.datetime.now(datetime.timezone.utc).isoformat()) +pathlib.Path('docs/million-local.json').write_text(json.dumps(result,indent=2)+'\n') +print('Saved docs/million-local.json') +PY +"${compose[@]}" down --volumes +df -B1 . > .dev/million/host-after-cleanup.txt +echo 'PASS: results saved; isolated million-file cluster storage released.' diff --git a/dev/million-start.sh b/dev/million-start.sh new file mode 100644 index 0000000..b25d238 --- /dev/null +++ b/dev/million-start.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +cd "$(dirname "$0")/.." +compose=(docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml) +# Each sparse OSD can grow to 24 GiB. Leave another 20 GiB for the host. +if ! docker volume inspect cephmig-million_source-state >/dev/null 2>&1; then + python3 - <<'PY' +import os +s = os.statvfs('.') +available = s.f_bavail * s.f_frsize +if available < 68 * 1024**3: + raise SystemExit('Need 68 GiB free for two 24 GiB OSDs and a 20 GiB host reserve') +print(f'Host free: {available / 1024**3:.1f} GiB') +PY +fi +mkdir -p .dev/million +"${compose[@]}" config --quiet +"${compose[@]}" up -d --wait --wait-timeout 600 source target +"${compose[@]}" up -d benchmark +docker inspect cephmig-million-benchmark-1 --format '{{.Image}}' > .dev/million/native-image.txt +echo 'Persistent test started. Status: .dev/million/main/status.json' +echo 'Logs: docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml logs -f benchmark' diff --git a/dev/million.py b/dev/million.py new file mode 100644 index 0000000..bcd611e --- /dev/null +++ b/dev/million.py @@ -0,0 +1,509 @@ +#!/usr/bin/env python3 +"""Persistent, bounded-memory million-file CephFS snapshot migration test. + +The Python SDK acts as application writer and independent verifier. Expected +contents and metadata are derived from a deterministic model, not the Go reader. +""" +import concurrent.futures +from collections import deque +import datetime +import hashlib +import json +import os +from pathlib import Path +import signal +import sqlite3 +import stat +import subprocess +import threading +import time +import uuid + +import cephfs +from smallfiles import ceph, volume, snap, payload, posix_acl + +RUN_LABEL = os.environ.get('RUN_LABEL', 'main') +if RUN_LABEL not in ('main', 'pilot'): + raise ValueError('RUN_LABEL must be main or pilot') +REPORT = Path('/report') / RUN_LABEL +WORK = Path('/state') / ('million-' + RUN_LABEL) +COUNT = int(os.environ.get('FILES', '1000000')) +PER_DIR = 1000 +STAMP = 1700000000 +STOP = threading.Event() +STATUS_LOCK = threading.RLock() +state = {} + + +def atomic_json(path, value): + temporary = path.with_suffix(path.suffix + '.tmp') + with temporary.open('w') as f: + json.dump(value, f, indent=2) + f.write('\n') + f.flush() + os.fsync(f.fileno()) + temporary.replace(path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + + +def progress(**changes): + with STATUS_LOCK: + state.update(changes) + state['updated_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat() + atomic_json(REPORT / 'status.json', state) + print(json.dumps(changes), flush=True) + + +def guard(): + if STOP.is_set(): + raise RuntimeError('test stopped') + usage = os.statvfs('/state') + if usage.f_bavail * usage.f_frsize < 20 * 1024**3: + raise RuntimeError('host reserve below 20 GiB; stopping further test writes') + memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines()) + if int(memory['MemAvailable'].split()[0]) < 3 * 1024**2: + raise RuntimeError('host available memory below 3 GiB') + + +def space_guard(): + guard() + for cluster in ('source', 'target'): + s = json.loads(ceph(cluster, 'df', '--format', 'json'))['stats'] + if s['total_avail_bytes'] < 3 * 1024**3: + raise RuntimeError(f'{cluster} has less than 3 GiB reserve') + + +class FS: + def __init__(self, cluster): + self.fs = cephfs.LibCephFS(conffile=f'/clusters/{cluster}/ceph.conf') + self.fs.conf_set('keyring', f'/clusters/{cluster}/ceph.client.admin.keyring') + self.fs.conf_set('client_acl_type', 'posix_acl') + self.fs.conf_set('client_cache_size', '4096') + self.fs.conf_set('client_oc', 'false') + self.fs.mount() + + def __enter__(self): + return self.fs + + def __exit__(self, *_): + self.fs.shutdown() + + +def names(fs, path): + d = fs.opendir(path) + try: + result = set() + while entry := fs.readdir(d): + name = entry.d_name.decode() + if name not in ('.', '..', '.snap'): + result.add(name) + return result + finally: + fs.closedir(d) + + +def mkdir(fs, path): + try: + fs.mkdir(path, 0o755) + except cephfs.ObjectExists: + if not stat.S_ISDIR(fs.lstat(path).st_mode): + raise + + +def exists(fs, path): + try: + fs.lstat(path) + return True + except cephfs.ObjectNotFound: + return False + + +def relative(i): + return f'data/d{i // PER_DIR:04d}/f{i % PER_DIR:06d}' + + +def object_attrs(i, changed): + result = {} + if i < COUNT and i // PER_DIR == 0: + acl = posix_acl() + if changed and i % 100 == 3: + # Change the ACL mask to match chmod 0660. + import struct + acl = bytearray(acl) + struct.pack_into('= 15: + space_guard() + try: + for line in Path(f'/proc/{p.pid}/status').read_text().splitlines(): + if line.startswith(('VmRSS:', 'VmHWM:')): + peak = max(peak, int(line.split()[1])) + except FileNotFoundError: + pass + with (REPORT / f'{phase}.log').open('rb') as tail: + tail.seek(max(0, os.fstat(tail.fileno()).st_size - 2048)) + lines = tail.read().decode(errors='replace').splitlines() + progress(elapsed_seconds=round(now - started, 1), peak_rss_kib=peak, + last_engine_message=lines[-1] if lines else 'starting') + last = now + if STOP.is_set(): raise RuntimeError('migration stopped') + if now - started > 48 * 3600: raise RuntimeError('migration phase exceeded 48 hours') + time.sleep(1) + except BaseException: + p.terminate() + try: p.wait(timeout=30) + except subprocess.TimeoutExpired: + p.kill(); p.wait() + raise + if p.returncode: + raise RuntimeError(f'{phase} failed ({p.returncode}); see {phase}.log') + result = json.loads((WORK / 'job.json').read_text()) + if not all(s['done'] for s in result['snapshots']): raise RuntimeError('unfinished snapshot') + after = {c: counters(c) for c in before} + metrics = dict(seconds=time.monotonic() - started, wall_seconds=time.time() - wall_started, + peak_rss_kib=peak, snapshots=result['snapshots'], + resumed=attempts[phase] > 1, + mds={c: {k: after[c][k] - before[c][k] for k in before[c]} for c in before}) + atomic_json(REPORT / f'{phase}.metrics.json', metrics) + atomic_json(REPORT / 'migration-state.json', result) + if phase == 'final': + if result['phase'] != 'ready-for-cutover' or result['snapshots'][-1]['transfer']['bytes_copied']: + raise RuntimeError('unchanged final round must be ready and write zero payload bytes') + completed = {phase + '_complete': True} + if phase == 'initial': + completed['initial_snapshots'] = [record['name'] for record in result['snapshots']] + progress(**completed) + + +def expected_mode(i, changed): + return 0o660 if changed and i < COUNT and i % 100 == 3 else (0o640 if i < PER_DIR else 0o644) + + +def check_regular(fs, root, rel, i, changed): + path = root + '/' + rel + s = fs.lstat(path) + if s.st_mode != stat.S_IFREG | expected_mode(i, changed) or s.st_size != 128: + raise RuntimeError(f'type/mode/size mismatch: {path}') + if (s.st_uid, s.st_gid) != ((12345, 23456) if i == 0 else (0, 0)): + raise RuntimeError(f'owner mismatch: {path}') + if s.st_mtime != datetime.datetime.fromtimestamp(STAMP + i, datetime.timezone.utc).replace(tzinfo=None): + raise RuntimeError(f'mtime mismatch: {path}') + if actual_attrs(fs, path) != object_attrs(i, changed): + raise RuntimeError(f'xattr/ACL mismatch: {path}') + version = 2 if i >= COUNT else (1 if changed and i % 100 == 0 else 0) + fd = fs.open(path, os.O_RDONLY | os.O_NOFOLLOW, 0) + try: data = fs.read(fd, 0, 129) + finally: fs.close(fd) + if data != payload(i, version): raise RuntimeError(f'content mismatch: {path}') + return i, str(s.st_ino) + + +def verify_view(label, root, changed): + if label in state.get('verified_views', []): return + progress(phase='verifying', view=label, verified_regular_paths=0) + dbpath = WORK / 'verify.sqlite' + dbpath.unlink(missing_ok=True) + db = sqlite3.connect(dbpath) + db.executescript('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-16384;' + 'CREATE TABLE links(object_id INTEGER PRIMARY KEY, inode TEXT UNIQUE NOT NULL);') + checked, last = 0, time.monotonic() + try: + with FS('target') as fs, concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool: + if names(fs, root) != {'data', 'links'}: raise RuntimeError('unexpected root entries') + for rel in ('.', 'data', 'links'): + s = fs.lstat(root + '/' + rel) + expected_attrs = ({key: bytes.fromhex(value) for key, value in state['root_attrs'].items()} + if rel == '.' else {}) + if (s.st_mode != (stat.S_IFDIR | 0o755) or s.st_uid or s.st_gid or + s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP) or + actual_attrs(fs, root + '/' + rel) != expected_attrs): + raise RuntimeError(f'root/parent metadata mismatch: {rel}') + end = COUNT + COUNT // 100 if changed else COUNT + directory_count = (end + PER_DIR - 1) // PER_DIR + if names(fs, root + '/data') != {f'd{i:04d}' for i in range(directory_count)}: + raise RuntimeError('data directory inventory mismatch') + def consume(future): + nonlocal checked + i, ino = future.result() + cursor = db.execute('INSERT OR IGNORE INTO links VALUES(?,?)', (i, ino)) + if not cursor.rowcount: + row = db.execute('SELECT inode FROM links WHERE object_id=?', (i,)).fetchone() + if row != (ino,): raise RuntimeError('hardlink group split or unrelated objects merged') + checked += 1 + for d in range(directory_count): + guard() + expected = {} + for i in range(d * PER_DIR, min(end, (d + 1) * PER_DIR)): + if changed and i < COUNT and i % 100 == 1: continue + rel = relative(i) + ('-renamed' if changed and i < COUNT and i % 100 == 2 else '') + expected[rel.rsplit('/', 1)[1]] = (rel, i) + path = root + f'/data/d{d:04d}' + if names(fs, path) != set(expected): raise RuntimeError(f'inventory mismatch: {path}') + s = fs.lstat(path) + if s.st_mode != stat.S_IFDIR | 0o755 or s.st_uid or s.st_gid or s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP): + raise RuntimeError(f'directory metadata mismatch: {path}') + attrs = {'system.posix_acl_default': posix_acl()} if d == 0 else {} + if actual_attrs(fs, path) != attrs: raise RuntimeError(f'directory ACL mismatch: {path}') + pending = deque() + for rel, i in expected.values(): + pending.append(pool.submit(check_regular, fs, root, rel, i, changed)) + if len(pending) >= 64: consume(pending.popleft()) + while pending: consume(pending.popleft()) + db.commit() + if time.monotonic() - last >= 15: + progress(view=label, verified_regular_paths=checked) + last = time.monotonic() + expected_links = {f'{kind}{i:03d}' for kind in ('hard', 'soft') for i in range(100)} + if names(fs, root + '/links') != expected_links: raise RuntimeError('link inventory mismatch') + for i in range(100): + result = check_regular(fs, root, f'links/hard{i:03d}', i, changed) + done = concurrent.futures.Future(); done.set_result(result); consume(done) + path = root + f'/links/soft{i:03d}' + s = fs.lstat(path) + if not stat.S_ISLNK(s.st_mode) or s.st_uid or s.st_gid: + raise RuntimeError('symlink metadata mismatch') + if fs.readlink(path, 4096).decode() != '../' + relative(i): raise RuntimeError('symlink text mismatch') + if s.st_mtime.isoformat() != state['symlink_times'][f'links/soft{i:03d}']: + raise RuntimeError('symlink mtime mismatch') + for key, value in [('ceph.quota.max_files', COUNT * 2 + 1000), ('ceph.quota.max_bytes', COUNT * 256 + 4194304)]: + if fs.getxattr(root, key, 128) != str(value).encode(): raise RuntimeError('quota mismatch') + if checked != COUNT + 100: raise RuntimeError(f'wrong file count: {checked}') + state.setdefault('verified_views', []).append(label) + progress(verified_regular_paths=checked) + finally: + db.close() + dbpath.unlink(missing_ok=True) + + +def other_writer(): + try: + with FS('source') as fs: + demo = volume('source', 'getpath', 'cephfs', 'demo') + path = demo + '/million-liveness' + fd = fs.open(path, os.O_CREAT | os.O_RDWR, 0o600) + try: + while not STOP.is_set(): + value = state.get('other_subvolume_writes', 0) + 1 + fs.write(fd, str(value).encode(), 0) + fs.fsync(fd, False) + with STATUS_LOCK: state['other_subvolume_writes'] = value + STOP.wait(2) + finally: + fs.close(fd) + fs.unlink(path) + except BaseException as e: + state['other_writer_error'] = str(e) + STOP.set() + + +def main(): + global state + if COUNT < 1000 or COUNT > 1000000 or COUNT % PER_DIR: + raise ValueError('FILES must be a multiple of 1000, from 1000 to 1000000') + REPORT.mkdir(parents=True, exist_ok=True) + WORK.mkdir(mode=0o700, parents=True, exist_ok=True) + if (REPORT / 'status.json').exists(): + state = json.loads((REPORT / 'status.json').read_text()) + if state.get('total_files') != COUNT: raise RuntimeError('cannot change count on resume') + if state.get('result') == 'PASS': return + state.pop('result', None) + state.pop('error', None) + state.pop('other_writer_error', None) + else: + state = dict(name='million-itest-' + str(uuid.uuid4()), total_files=COUNT, + started_at=datetime.datetime.now(datetime.timezone.utc).isoformat()) + for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: STOP.set()) + try: + if not state.get('prepared'): prepare() + thread = threading.Thread(target=other_writer, daemon=True) + thread.start() + try: + if not state.get('initial_complete'): run_phase('initial') + if not state.get('mutated'): mutate() + if not state.get('catchup_complete'): run_phase('catchup') + before = state.get('other_subvolume_writes', 0) + if not state.get('final_complete'): + run_phase('final') + if state.get('other_subvolume_writes', 0) <= before: + raise RuntimeError('other subvolume did not remain writable during finalization') + job = json.loads((WORK / 'job.json').read_text()) + if len(job['snapshots']) < 4: raise RuntimeError('expected at least four snapshot stands') + initial = set(state.get('initial_snapshots', [x['name'] for x in job['snapshots'][:2]])) + verify_view('live', state['roots']['target'], True) + for record in job['snapshots']: + path = ceph('target', 'fs', 'subvolume', 'snapshot', 'getpath', + 'cephfs', state['name'], record['name'], 'migration') + verify_view(record['name'], path, record['name'] not in initial) + if snap('source', 'metadata', 'ls', 'cephfs', state['name'], record['name']) != snap( + 'target', 'metadata', 'ls', 'cephfs', state['name'], record['name']): + raise RuntimeError('snapshot custom metadata mismatch') + if state.get('other_writer_error'): raise RuntimeError(state['other_writer_error']) + progress(phase='complete', result='PASS', + snapshot_count=len(job['snapshots']), + total_regular_paths_verified=(COUNT + 100) * (len(job['snapshots']) + 1)) + finally: + STOP.set() + thread.join(timeout=30) + except BaseException as e: + progress(phase='failed', result='FAIL', error=repr(e)) + raise + + +if __name__ == '__main__': + main() diff --git a/dev/native-fixture.py b/dev/native-fixture.py new file mode 100644 index 0000000..a6fa6fe --- /dev/null +++ b/dev/native-fixture.py @@ -0,0 +1,245 @@ +#!/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 + + +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 acl(): + entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff), + (16, 4, 0xffffffff), (32, 0, 0xffffffff)] + return struct.pack(" 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 == "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") + claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest() + os.unlink("/mnt/target-fs/.cephmig/claims/" + claim) + shutil.rmtree(work) +else: + raise ValueError(action) diff --git a/dev/native-test.sh b/dev/native-test.sh new file mode 100644 index 0000000..160537f --- /dev/null +++ b/dev/native-test.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +cd "$(dirname "$0")/.." +compose=(docker compose -f dev/compose.yaml) +fixture() { "${compose[@]}" exec -T client python3 /lab/native-fixture.py "$@"; } +name=$(fixture setup) +work="/state/$name" +state="$work/job.json" +config="$work/config.json" +binary=/usr/local/bin/cephmig-native +completed=false +busy_pid= +cleanup() { + "${compose[@]}" exec -T native touch "$work/stop-busy" || true + if [[ -n $busy_pid ]]; then wait "$busy_pid" || true; fi + if [[ $completed = true ]]; then + fixture cleanup "$name" + else + echo "FAIL: retained native fixtures subvolume=$name state=$state" >&2 + fi +} +trap cleanup EXIT +fixture busy "$name" & +busy_pid=$! +"${compose[@]}" exec -T native "$binary" inspect --config "$config" +"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH' +set -Eeuo pipefail +binary=$1 config=$2 state=$3 work=$4 +test ! -e /dev/fuse +! command -v rsync +! grep -q 'fuse.ceph' /proc/self/mountinfo +"$binary" sync --config "$config" --state "$state" > "$work/interrupted.json" 2> "$work/interrupted.log" & +pid=$! +for ((i=0; i<300; i++)); do + kill -0 "$pid" || { cat "$work/interrupted.log"; exit 1; } + if grep -q 'snapshot=history-1: copying' "$work/interrupted.log"; then break; fi + sleep 0.1 +done +sleep 1 +kill -TERM "$pid" +if wait "$pid"; then echo 'expected cancellation' >&2; exit 1; fi +grep -q 'context canceled' "$work/interrupted.log" +python3 - "$state" <<'PY' +import json,sys +s=json.load(open(sys.argv[1])) +assert not s.get("live_snapshot") and not s["snapshots"][0]["done"], s +PY +SH +fixture unthrottle "$name" +# Crash after the target snapshot was persisted, before the journal can mark it done. +"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH' +set -Eeuo pipefail +binary=$1 config=$2 state=$3 work=$4 +mkdir "$work/bin" +cat > "$work/bin/ceph" <<'WRAPPER' +#!/usr/bin/env bash +set -euo pipefail +if [[ -f $CEPHMIG_CRASH_ONCE && " $* " == *'/clusters/target/ceph.conf'* && + " $* " == *' fs subvolume snapshot create '* ]]; then + /usr/bin/ceph "$@" + rm "$CEPHMIG_CRASH_ONCE" + kill -KILL "$PPID" + exit 0 +fi +exec /usr/bin/ceph "$@" +WRAPPER +chmod +x "$work/bin/ceph" +export CEPHMIG_CRASH_ONCE="$work/crash" +touch "$CEPHMIG_CRASH_ONCE" +if PATH="$work/bin:$PATH" "$binary" sync --config "$config" --state "$state" > "$work/crashed.json"; then + echo 'expected SIGKILL' >&2; exit 1 +fi +test ! -f "$CEPHMIG_CRASH_ONCE" +SH +"${compose[@]}" exec -T native "$binary" sync --config "$config" --state "$state" +fixture verify "$name" +fixture mutate "$name" +"${compose[@]}" exec -T native "$binary" sync --config "$config" --state "$state" +"${compose[@]}" exec -T native cp "$work/busy-count" "$work/busy-before-final" +"${compose[@]}" exec -T native "$binary" finalize --config "$config" --state "$state" --writers-stopped +fixture final "$name" +"${compose[@]}" exec -T native bash -s -- "$binary" "$config" "$state" "$work" <<'SH' +set -Eeuo pipefail +cp "$3" "$4/before.json" +"$1" finalize --config "$2" --state "$3" --writers-stopped > "$4/idempotent.json" +python3 - "$4" <<'PY' +import json,pathlib,sys +p=pathlib.Path(sys.argv[1]) +assert json.loads((p/"before.json").read_text()) == json.loads((p/"idempotent.json").read_text()) +assert int((p/"busy-count").read_text()) > int((p/"busy-before-final").read_text()) > 20 +PY +SH +completed=true +echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization' diff --git a/dev/restart-check.sh b/dev/restart-check.sh new file mode 100644 index 0000000..97f324f --- /dev/null +++ b/dev/restart-check.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +cd "$(dirname "$0")/.." +compose() { docker compose -f dev/compose.yaml "$@"; } +marker=".cephmig-restart-$(cat /proc/sys/kernel/random/uuid)" +source_fsid=$(compose exec -T source ceph fsid) +target_fsid=$(compose exec -T target ceph fsid) +test "$source_fsid" != "$target_fsid" +cleanup() { + compose exec -T client rm -f "/mnt/source/$marker" "/mnt/target/$marker" || true +} +trap cleanup EXIT +compose exec -T client bash -c 'printf source > "/mnt/source/$1"; printf target > "/mnt/target/$1"' bash "$marker" +compose down +compose up -d --wait --wait-timeout 300 +test "$(compose exec -T source ceph fsid)" = "$source_fsid" +test "$(compose exec -T target ceph fsid)" = "$target_fsid" +test "$(compose exec -T client cat "/mnt/source/$marker")" = source +test "$(compose exec -T client cat "/mnt/target/$marker")" = target +echo 'PASS: cluster identities and subvolume data survive down/up' diff --git a/dev/smallfiles-test.sh b/dev/smallfiles-test.sh new file mode 100644 index 0000000..70b46e0 --- /dev/null +++ b/dev/smallfiles-test.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +cd "$(dirname "$0")/.." +compose=(docker compose -f dev/compose.yaml) +count=${FILES:-10000} +report=${REPORT_DIR:-/tmp/cephmig-smallfiles-report} +binary=${BINARY:-/usr/local/bin/cephmig-native} +mkdir -p "$report" +docker inspect cephmig-dev-native-1 --format '{{.Image}}' > "$report/native-image.txt" +python3 - "$count" "$binary" "$report/settings.json" <<'PY' +import json,sys +with open(sys.argv[3],"w") as f: json.dump(dict(files=int(sys.argv[1]),bytes_per_file=128,workers=4,binary=sys.argv[2]),f) +PY +mds_counters() { + "${compose[@]}" exec -T "$1" ceph daemon mds.a perf dump | python3 -c ' +import json,sys +d=json.load(sys.stdin) +s=d["mds_server"] +print(json.dumps(dict(requests=d["mds"]["request"],**{ + k:s["req_"+k+"_latency"]["avgcount"] for k in ("getattr","lookup","lookupsnap","setattr","readdir")})))' +} +df -B1 . > "$report/host-before.txt" +"${compose[@]}" exec -T source ceph df --format json > "$report/source-before.json" +"${compose[@]}" exec -T target ceph df --format json > "$report/target-before.json" +name=$("${compose[@]}" exec -T client python3 /lab/smallfiles.py setup --count "$count") +printf '%s\n' "$name" > "$report/fixture-name.txt" +completed=false +cleanup() { + if [[ $completed = true ]]; then + "${compose[@]}" exec -T client python3 /lab/smallfiles.py cleanup "$name" + else + echo "FAIL: retained fixture $name; diagnostics at /state/$name" >&2 + fi +} +trap cleanup EXIT +for phase in initial catchup final; do + if [[ $phase = catchup ]]; then + "${compose[@]}" exec -T client python3 /lab/smallfiles.py mutate "$name" + fi + echo "smallfiles: phase=$phase count=$count" + for cluster in source target; do + mds_counters "$cluster" > "$report/$phase-$cluster-mds-before.json" + done + "${compose[@]}" exec -T native python3 /lab/smallfiles.py run "$name" --phase "$phase" --binary "$binary" | + tee "$report/$phase.json" + for cluster in source target; do + mds_counters "$cluster" > "$report/$phase-$cluster-mds-after.json" + done +done +"${compose[@]}" exec -T client python3 /lab/smallfiles.py verify "$name" | + tee "$report/verification.json" +"${compose[@]}" exec -T native du -sk "/state/$name" > "$report/local-state-kib.txt" +"${compose[@]}" exec -T source ceph df --format json > "$report/source-after.json" +"${compose[@]}" exec -T target ceph df --format json > "$report/target-after.json" +df -B1 . > "$report/host-after.txt" +completed=true +echo "PASS: $count small files, snapshots, same-mtime changes, deletes, renames, metadata, links; report=$report" diff --git a/dev/smallfiles.py b/dev/smallfiles.py new file mode 100644 index 0000000..fd35de9 --- /dev/null +++ b/dev/smallfiles.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Space-conscious, application-side many-small-files migration benchmark.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import stat +import struct +import subprocess +import sys +import time +import uuid + + +def ceph(cluster, *args): + return subprocess.check_output([ + "ceph", "-c", f"/clusters/{cluster}/ceph.conf", "-k", + f"/clusters/{cluster}/ceph.client.admin.keyring", *args], text=True).strip() + + +def volume(cluster, *args): + return ceph(cluster, "fs", "subvolume", *args, "--group_name", "migration") + + +def snap(cluster, *args): + return volume(cluster, "snapshot", *args) + + +def relative(i, count): + return f"flat/f{i:08d}" if i < count // 2 else f"tree/b{i % 50:02d}/f{i:08d}" + + +def payload(i, version): + return hashlib.sha256(f"{i}:{version}".encode()).digest() * 4 + + +def posix_acl(): + entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff), + (16, 4, 0xffffffff), (32, 0, 0xffffffff)] + return struct.pack(" args.timeout: + stop_child(process) + raise RuntimeError("benchmark phase timed out; fixture retained") + if abs((time.time() - wall_started) - (now - started)) > 5: + stop_child(process) + raise RuntimeError("host suspend or clock jump detected; discard timing and rerun") + if now - last_progress >= 30: + print(f"{args.phase}: elapsed={now - started:.0f}s " + f"native_peak_rss={peak_rss / 1024:.1f} MiB", + file=sys.stderr, flush=True) + last_progress = now + time.sleep(0.1) + elapsed = time.monotonic() - started + if process.returncode: + print((work / f"{args.phase}.log").read_text(), file=sys.stderr) + raise RuntimeError(f"migration exited {process.returncode}") + state = json.loads(journal.read_text()) + if not all(x["done"] for x in state["snapshots"]): + raise AssertionError("unfinished snapshot") + if args.phase == "final" and (state["phase"] != "ready-for-cutover" or + state["snapshots"][-1]["transfer"]["bytes_copied"] != 0): + raise AssertionError("finalization must finish without rewriting unchanged data") + result = dict(phase=args.phase, seconds=round(elapsed, 3), + native_peak_rss_kib=peak_rss, + rounds=[dict(name=x["name"], **x["transfer"]) for x in state["snapshots"]]) + (work / f"{args.phase}.metrics.json").write_text(json.dumps(result, indent=2)) + print(json.dumps(result), flush=True) + elif args.action == "verify": + state = json.loads(journal.read_text()) + started = time.monotonic() + checked = compare(roots["source"], roots["target"]) + if checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4: + raise AssertionError("unexpected file count or incomplete migration") + snapshots = [] + for s in state["snapshots"]: + a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath", + "cephfs", name, s["name"], "migration") for c in ("source", "target")] + snapshot_checked = compare(a, b, s["name"]) + if snapshot_checked != count + 100: + raise AssertionError(f"unexpected snapshot file count: {s['name']}") + snapshots.append(dict(name=s["name"], files_checked=snapshot_checked)) + result = dict(live_files_checked=checked, snapshots=snapshots, + seconds=round(time.monotonic() - started, 3)) + (work / "verification.json").write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + elif args.action == "cleanup": + for cluster in ("source", "target"): + for s in json.loads(snap(cluster, "ls", "cephfs", name)): + snap(cluster, "rm", "cephfs", name, s["name"]) + volume(cluster, "rm", "cephfs", name, "--force") + claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest() + try: + os.unlink("/mnt/target-fs/.cephmig/claims/" + claim) + except FileNotFoundError: + pass + shutil.rmtree(work) + + +if __name__ == "__main__": + main() diff --git a/dev/smoke.sh b/dev/smoke.sh new file mode 100644 index 0000000..5d99b27 --- /dev/null +++ b/dev/smoke.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -Eeuo pipefail +mountpoint -q /mnt/source +mountpoint -q /mnt/target +mountpoint -q /mnt/source-fs +test_dir=".cephmig-smoke-$(cat /proc/sys/kernel/random/uuid)" +source_ceph() { + ceph -c /clusters/source/ceph.conf -k /clusters/source/ceph.client.admin.keyring "$@" +} +snapshot_created=false +cleanup() { + if [[ $snapshot_created = true ]]; then + source_ceph fs subvolume snapshot rm cephfs demo "$test_dir" --group_name migration + fi + rm -rf "/mnt/source/$test_dir" "/mnt/target/$test_dir" +} +trap cleanup EXIT +mkdir "/mnt/source/$test_dir" "/mnt/target/$test_dir" +printf 'cephmig source\n' > "/mnt/source/$test_dir/file" +ln "/mnt/source/$test_dir/file" "/mnt/source/$test_dir/hardlink" +ln -s file "/mnt/source/$test_dir/symlink" +truncate -s 16777216 "/mnt/source/$test_dir/sparse" +chmod 0640 "/mnt/source/$test_dir/file" +python3 - "/mnt/source/$test_dir/file" <<'PY' +import os, struct, sys +os.setxattr(sys.argv[1], 'user.cephmig', b'preserve-me') +# POSIX ACL: owner rw, named user 12345 r, group ---, mask r, other ---. +entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff), + (16, 4, 0xffffffff), (32, 0, 0xffffffff)] +acl = struct.pack(' "/mnt/source/$test_dir/file" +cp -a "$snapshot/." "/mnt/target/$test_dir/" +diff -r "$snapshot" "/mnt/target/$test_dir" +test "$(cat "/mnt/target/$test_dir/file")" = 'cephmig source' +test "$(cat "/mnt/source/$test_dir/file")" = 'live write after snapshot' +test "$(stat -c %a "/mnt/target/$test_dir/file")" = 640 +python3 - "$snapshot/file" "/mnt/target/$test_dir/file" <<'PY' +import os, sys +assert os.getxattr(sys.argv[2], 'user.cephmig') == b'preserve-me' +assert os.getxattr(sys.argv[1], 'system.posix_acl_access') == os.getxattr(sys.argv[2], 'system.posix_acl_access') +PY +# Quotas belong to directories and need explicit handling beyond file copying. +python3 - "/mnt/source/$test_dir" "/mnt/target/$test_dir" <<'PY' +import os, sys +for path in sys.argv[1:]: + os.setxattr(path, 'ceph.quota.max_bytes', b'33554432') + assert os.getxattr(path, 'ceph.quota.max_bytes') == b'33554432' + os.setxattr(path, 'ceph.quota.max_bytes', b'0') +PY +test "$(stat -c %i "/mnt/target/$test_dir/file")" = "$(stat -c %i "/mnt/target/$test_dir/hardlink")" +test "$(readlink "/mnt/target/$test_dir/symlink")" = file +printf 'target only\n' > "/mnt/target/$test_dir/isolated" +test ! -e "/mnt/source/$test_dir/isolated" +echo 'PASS: independent clusters, snapshot copy with live changes, permissions, POSIX ACL, xattr, quota operations, hardlink, symlink, sparse-file contents' diff --git a/dev/snapshot-identity.py b/dev/snapshot-identity.py new file mode 100644 index 0000000..1f0cc39 --- /dev/null +++ b/dev/snapshot-identity.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Read-only lab probe: compare native snapshot identity across two clusters.""" +import argparse +import json +import subprocess + +import cephfs + + +def snapshot_identity(endpoint, name): + args = ["ceph", "--conf", endpoint["config"], "--keyring", endpoint["keyring"]] + user = endpoint.get("user", "client.admin") + if user: + args += ["--name", user] + args += ["fs", "subvolume", "snapshot", "getpath", + endpoint["filesystem"], endpoint["subvolume"], name] + if endpoint.get("group"): + args += ["--group_name", endpoint["group"]] + path = subprocess.check_output(args, text=True, timeout=30).strip() + fs = cephfs.LibCephFS(conffile=endpoint["config"], + auth_id=user.removeprefix("client.")) + try: + fs.conf_set("keyring", endpoint["keyring"]) + fs.conf_set("client_fs", endpoint["filesystem"]) + fs.mount() + info = fs.snap_info(path) + birthtime = fs.getxattr(path, "ceph.snap.btime").decode("ascii") + return {"id": info["id"], "birthtime": birthtime} + finally: + fs.shutdown() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True) + parser.add_argument("--snapshot", required=True) + args = parser.parse_args() + with open(args.config) as f: + config = json.load(f) + source = snapshot_identity(config["source"], args.snapshot) + target = snapshot_identity(config["target"], args.snapshot) + print(json.dumps({"snapshot": args.snapshot, "source": source, "target": target, + "native_ids_equal": source["id"] == target["id"], + "native_birthtimes_equal": source["birthtime"] == target["birthtime"]})) + + +if __name__ == "__main__": + main() + diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..4ad5da7 --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,282 @@ +# Migrationsprototyp + +Die Prüfung eines direkten RADOS-Objekttransfers und die native Alternative +über libcephfs sind in [raw-transfer.md](raw-transfer.md) dokumentiert. + +## Snapshot-Identität: dokumentierte Abweichung + +Native Snapshot-IDs und Ceph-Geburtszeitpunkte werden am Ziel neu vergeben. +Wie vereinbart blockiert diese Abweichung die Migration nicht. `inspect`, +die Übertragungsausgabe und das persistente Journal enthalten einen Hinweis; +ursprüngliche und neue Erstellungszeiten stehen bei jedem übertragenen Snapshot. +Eine Anwendung, die native IDs direkt speichert, muss die neuen Werte beachten. + +Die unterstützte `ceph_mksnap`-Schnittstelle nimmt Namen, Modus und +benutzerdefinierte Metadaten entgegen, aber keine gewünschte native ID oder +Geburtszeit. `ceph.snap.btime` ist im Client ausdrücklich schreibgeschützt. +Auch CephFS-Mirroring erzeugt im Ziel einen neuen Snapshot und hält die +Quell-ID als separate Metadaten fest. + +Quellen: + +- [libcephfs-Schnittstelle](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h) +- [Client: virtuelle Snapshot-Attribute](https://github.com/ceph/ceph/blob/main/src/client/Client.cc) +- [Mirror: Anlegen eines Zielsnapshots](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc) + +Im lokalen Ceph-21.2.0-Labor wurden bei einem gleichnamigen Snapshot +Quell-ID 6 und Ziel-ID 2 sowie unterschiedliche Geburtszeiten gemessen. +Ein Schreibversuch mit dem bereits vorhandenen Wert von `ceph.snap.btime` +am eigenen Testsnapshot wurde mit `EROFS` abgewiesen. + +Mit den geprüften Schnittstellen lässt sich die native Snapshot-Identität nicht +vorgeben. Diese Einschränkung ist akzeptiert; sie wird ausdrücklich vermerkt. +Lastnachweise und eine automatisierte produktive Client-Umschaltung fehlen noch. + +## Kommandos + +Das native Backend benötigt Linux, Ceph CLI, libcephfs und einen mit CGO und +`-tags ceph` gebauten Kopierer. Es benötigt keine Betriebssystem-Mounts und +keinen privilegierten Container. Zum Erhalten fremder UID/GID und geschützter +xattrs sind entsprechende Client-/Prozessrechte nötig; das Labor verwendet root. +Der optionale Referenzpfad `backend: rsync` benötigt zusätzlich rsync und am +Dateisystem-Root gemountete Quell-/Zieldateisysteme. +Die Subvolumes müssen schon existieren. Für einen neuen Job müssen Datenbaum, +Snapshots und benutzerdefinierte Metadaten des Ziels leer sein. +Keine Anwendung darf ins Ziel schreiben. + +Die Konfiguration in `dev/migration.example.json` wählt `backend: native` und +gilt im Labordienst `native`. `mount` wird dort nicht verwendet und kann fehlen. +`workers` begrenzt gleichzeitige Dateikopien (Standard 8, maximal 64), +`bandwidth_kib` begrenzt die Summe geschriebener Nutzdatenbytes pro Sekunde. +Beide Werte dürfen bei Wiederaufnahme geändert werden. +Die nativen `transfer`-Statistiken im Journal nennen Modus, Basis-Snapshot, +besuchte/kopierte Dateien sowie geschriebene und zur Prüfung gelesene Bytes. +`bytes_copied` zählt Nutzdaten-Schreibzugriffe ohne ausgesparte Nullbereiche; +es misst nicht das gesamte Netzwerkaufkommen einschließlich Protokoll und Prüfung. + +```sh +make dev-native-build +docker compose -f dev/compose.yaml up -d --wait native +docker compose -f dev/compose.yaml exec native \ + cephmig-native inspect --config /lab/migration.example.json +``` + +Der lesende Preflight vergleicht CLI-FSID und die über den Client gelesene +`ceph.cluster_fsid`, prüft Pfade und Subvolume-Status und meldet die aktuelle +Datenmenge sowie Snapshotnamen. Die Datenmenge ist **keine** Kapazitätsprognose +für alle historischen Snapshots. + +Das Backend hat folgende Übertragungskommandos: + +```sh +cephmig sync --config /absolute/config.json --state /local-state/job.json +cephmig status --state /local-state/job.json +# Alle Quellwriter einschließlich weiterer Clients stoppen und flushen. +cephmig finalize --config /absolute/config.json \ + --state /local-state/job.json --writers-stopped +``` + +`sync` verarbeitet bekannte, noch nicht abgeschlossene Stände, neu entdeckte +Anwendungssnapshots und danach einen neuen Quellsnapshot. Weitere Änderungen +werden durch erneutes `sync` nachgezogen. Das native Backend verwendet Snapdiff +und die Ceph-Inode-Version; dadurch werden auch Datenänderungen gleicher Größe +und gleicher mtime erkannt. Der rsync-Pfad verwendet Prüfsummen. + +`finalize` bestätigt den Schreibstopp ausschließlich über die ausdrückliche +Operatorangabe; es stoppt oder sperrt selbst keine Anwendung. Alle Writer +müssen bis zur abgeschlossenen Umschaltung gestoppt bleiben. Der Job endet +bei `ready-for-cutover`. Remounts, Neustarts der Anwendungen und eine +Rückmigration nach Schreibzugriffen am Ziel sind nicht automatisiert. + +## Übertragene Daten + +- Snapshotnamen und Inhalte; bestehende Snapshots werden chronologisch übertragen. +- Numerische UID/GID, Modus, mtime, POSIX-ACLs einschließlich Default-ACLs. +- Benutzer-xattrs und weitere portable xattrs; einschließlich leerer Werte und Löschungen. +- Hardlinks innerhalb des Subvolumes, Symlinks und FIFOs. +- Sparse-Dateiinhalte; der native Pfad überspringt Nullbereiche bzw. verwendet Hole-Punching. + Die physische Platzbelegung wird nicht zugesichert. +- Verzeichnisquotas `ceph.quota.max_bytes` und `ceph.quota.max_files`, auch am Datenroot. +- Benutzerdefinierte Subvolume- und Snapshot-Metadaten über die Manager-API. +- Ursprüngliche und neue Snapshot-Erstellungszeiten im Journal. + +Softlinks bleiben als Linktext erhalten, auch wenn das Ziel nicht existiert. +Der native Pfad erhält auch Hardlinks auf Symlinks und FIFOs; bei Symlinks +verknüpft er die Inode über die öffentliche Low-Level-Schnittstelle, damit der +Link selbst und nicht sein Referent verknüpft wird. +Absolute Links werden nicht umgeschrieben; bei der Umschaltung muss der +Anwendungs-Mountpfad dazu passen. Hardlinks über die Grenze des übertragenen +Subvolumes hinaus werden nicht als gemeinsame Verknüpfung migriert. + +Clusterinterne Layout-, Pool- und andere `ceph.*`-Attribute werden nicht +blind kopiert; Quotas werden gesondert übertragen. Pool-/Layout-Mappings, +Subvolumegruppenquotas, Pinning, Authorisierungen, Snapshot-Zeitpläne, aktive +Clone-Jobs und weitere Ceph-Verwaltungszustände sind nicht implementiert. +Die Migration übernimmt die von der Subvolume-API aufgelisteten Snapshots mit +ihrem gesamten Verzeichnisbaum. CephFS unterstützt allgemein Verzeichnissnapshots; +eigene Snapshots unterhalb eines verwalteten Subvolumes verweigert der MDS jedoch. +Im Ceph-21.2.0-Labor war ein Snapshot eines normalen Verzeichnisses erfolgreich, +derselbe Versuch in einem Subvolume-Unterordner scheiterte mit `EPERM`. +In Unterordnern sichtbare, geerbte Snapshot-Ansichten sind Bestandteil des +übergeordneten Subvolume-Snapshots. Die frühere Warnung zu separaten +Unterverzeichnissnapshots war für dieses verwaltete Subvolume-Modell zu pauschal. +Siehe [MDS-Prüfung der Subvolume-Grenze](https://github.com/ceph/ceph/blob/main/src/mds/Server.cc). +ctime, atime, originale Inode-Nummern und native Snapshot-IDs bleiben nicht erhalten. +Verschlüsselte, normalisierte, nicht case-sensitive oder mit Earmark versehene +Subvolumes werden abgelehnt. + +## Wiederaufnahme und Verifikation + +Der Job speichert ein atomar ersetztes, mit fsync gesichertes JSON-Journal +mit Modus 0600. Es enthält Konfiguration, Cluster-FSIDs, die konkreten +Subvolume-Datenpfade und Snapshot-Intent-/Abschlussinformationen. Eine +Neuanlage desselben Subvolumenamens mit anderer Daten-UUID wird abgewiesen. + +Eine lokale flock-Sperre verhindert parallele Zugriffe auf dasselbe Journal. +Ein persistenter Claim unter `/.cephmig/claims/` mit +exklusiver Datei-/CephFS-Sperre schützt das Ziel auch bei verschiedenen lokalen +Journalpfaden. Ein fehlendes oder unvollständiges Journal wird nicht durch +automatische Übernahme vorhandener Zieldaten ersetzt. + +Jeder Snapshotstand wird kopiert, einschließlich Quotas verifiziert und erst +danach am Ziel als Snapshot angelegt. Ein bereits angelegter, aber noch nicht +im Journal bestätigter Zielsnapshot wird bei Wiederaufnahme erneut gegen die +unveränderliche Quelle geprüft. Ersatz oder Verlust bereits abgeschlossener +Snapshots wird anhand der gespeicherten Identität erkannt. + +Der native Datenpfad verwendet einen lokalen bbolt-Index mit Quell-Inode, +Inode-Version, Größe und Ziel-Inode pro Pfad. Er enthält keine Dateiinhalte. +Die bestätigte Basis wird vor jeder Zieländerung im JSON-Journal ungültig +gemacht und erst nach erfolgreicher Verifikation und einem fsync des Index +erneut bestätigt. Cluster, Daten-UUID-Pfade und Snapshotname müssen passen. +Nach einem Abbruch wird der offene Stand vollständig nativ rekonstruiert; +ein nur teilweise ausgeführter Blockdiff darf nicht als Basis gelten. +Ein bereits publizierter, unbestätigter Zielsnapshot wird erneut geprüft. +Nach SIGKILL kann die Freigabe alter Ceph-Clientsitzungen den Wiederanlauf verzögern. + +Der Index enthält außerdem das vollständige Pfadinventar des unveränderlichen +Quellsnapshots: Dateien, Verzeichnisse, Hardlink-Aliase und Spezialdateien. +Erst nach vollständiger Erfassung wird es als vollständig markiert. Aufräumen +und Überhangprüfung gleichen Zielpfade mit diesem lokalen Inventar ab und +vermeiden dadurch erneute `stat`-Abfragen für jeden Quellpfad. Unvollständige +oder beschädigte Inventare führen zum Abbruch. Bereits identische Inode-Zeilen +werden bei der Verifikation nicht erneut in den Index geschrieben. + +Unveränderliche Pfade unter `.snap` werden bei `stat` und `readdirplus` mit +`AT_STATX_DONT_SYNC` gelesen, wie in Cephs eigenem Mirror. Dadurch werden +Metadatensperren nicht allein für eine erneute Synchronisation bereits +unveränderlicher Snapshot-Inodes angefordert. Live-Zielpfade behalten ihre +normale Synchronisationssemantik. Details und Messergebnisse stehen in +[smallfiles-local.md](smallfiles-local.md). + +Bei einer vollständigen Kopie vergleicht die native Prüfung alle Dateiinhalte. +Bei Folgeständen prüft sie kopierte Dateien bzw. die von Blockdiff gemeldeten +Bereiche. Unveränderte Bytes stammen aus der zuvor verifizierten Basis. Daher +muss der Zielbaum während des gesamten Jobs ausschließlich dem Kopierer gehören. +Fremde Änderungen unveränderter Dateibereiche werden damit nicht zuverlässig +gefunden. Metadaten, Quotas und Hardlink-Topologie werden in jedem Stand geprüft. +Ein direkt nach der Prüfung angelegter Zielsnapshot wird auf Metadaten und +Links geprüft; dieselben unveränderlichen Daten werden nicht erneut gelesen. + +Die rsync-Prüfung liest Dateiinhalte per Checksumme und vergleicht zusätzlich +die unterstützten Metadaten. Quotawerte werden separat geprüft. Wiederaufnahme +innerhalb eines Standes nutzt die vorhandenen Teilkopien, muss den Baum aber +erneut scannen; Checkpoints sind derzeit pro Snapshot, nicht pro Datei. +Bei einem im Labor reproduzierten Hardlink-`EEXIST` wird genau einmal +idempotent wiederholt; andere Fehler werden sofort zurückgegeben. + +Zusätzlich wird die Hardlink-Topologie in beide Richtungen geprüft: alle +Quellpfade derselben Inode müssen im Ziel zusammengehören; unabhängige +Quelldateien dürfen im Ziel nicht versehentlich dieselbe Inode teilen. +Das ist nötig, weil [rsync -H](https://download.samba.org/pub/rsync/rsync.1) +überzählige bestehende Zielverknüpfungen nicht in jedem Fall auflöst. +Im rsync-Pfad werden vor dem Kopieren solche überzähligen Verknüpfungen am +exklusiven Ziel entfernt und aus dem Quellsnapshot neu aufgebaut. Der native +Pfad erzeugt vollständige Kopien atomar als neue Inodes und setzt anschließend +die Hardlink-Aliase. Alte Zielsnapshots +bleiben unverändert. Symlink-Verzeichnisse werden dabei nicht verfolgt. + +Die Prüfzuordnungen liegen in einem temporären bbolt-Index neben dem Journal; +Schreibtransaktionen werden nach 4.096 Beobachtungen abgeschlossen. Der Index +wird nach jedem Prüf-/Reparaturlauf verworfen und bei Bedarf neu aufgebaut. +Er ist kein Wiederaufnahmejournal. Der native Basisindex unter +`.native/base.bolt` bleibt dagegen erhalten. Dafür muss lokal ausreichend Platz +vorhanden sein. Pfadtiefen über 128 Verzeichnisse werden derzeit abgewiesen. +Nach einem harten Prozessabbruch während eines Indexlaufs können temporäre +Indexverzeichnisse übrig bleiben; sie werden nicht als Checkpoints verwendet. + +Quell- und Zielsnapshots werden nicht automatisch gelöscht. Journal und Claim +müssen für Wiederaufnahme erhalten bleiben. Ein unvollständiger Claim nach +einem Absturz während seiner allerersten Anlage wird absichtlich nicht +automatisch repariert; dafür ist eine Prüfung der ursprünglichen Job-ID nötig. + +## Tests und Größenordnung + +```sh +make check +go test -race ./... +make dev-migration-test +make dev-native-test +``` + +Die Integrationstests erzeugen eigene Subvolumes und prüfen historische Stände, +Änderungsnachlauf, Metadaten, entfernte Dateien, Kopierfehler und einen +SIGKILL nach dem Anlegen eines Zielsnapshots, aber vor dem Journal-Commit. +Er prüft auch den gespeicherten Hinweis auf neue Snapshot-Identitäten und das +Auflösen zuvor vorhandener Hardlinks bei unveränderten Dateiinhalten. +Bei Erfolg entfernt er ausschließlich seine eigenen Fixtures; bei Fehlern +bleiben die ausgegebenen Testpfade zur Diagnose erhalten. + +Der native Test verwendet einen Kopierer ohne FUSE-Gerät, CephFS-Mounts und +rsync. Ein separater FUSE-Anwendungsclient prüft unabhängig alle Dateiinhalte +mit SHA-256 sowie Metadaten, Links und Snapshots. Er prüft eine 4-KiB-Änderung +in einer 64-MiB-Datei bei gleicher mtime, Wachstum und Nullbereiche, Linkgruppen +mit Trennung/Wiedervereinigung sowie Wechsel zwischen Verzeichnis und Symlink. +Hardlinks auf nicht auflösbare Symlinks und FIFOs werden ebenfalls unabhängig +anhand der Inodes verglichen, einschließlich späterer Trennung einer FIFO-Gruppe. +Weitere Prüfungen betreffen Abbruch während der Kopie, SIGKILL unmittelbar nach +Snapshot-Erzeugung, Wiederanlauf und idempotenten Abschluss. Währenddessen +schreibt eine Anwendung fortlaufend in ein anderes Quell-Subvolume. + +Laborergebnis vom 05.11.2026 mit Ceph 21.2.0: nativer Integrationstest und +rsync-Regression erfolgreich; Go-Tests einschließlich Race Detector und +`go vet` für den Ceph-Build erfolgreich. Der native Test schloss fünf Stände +mit `ready-for-cutover` ab und prüfte sie zusätzlich über den Anwendungsclient. +Bei der Änderung von 4 KiB in der 64-MiB-Datei wurden für diese Datei 4 KiB, +für den gesamten zweiten Stand einschließlich weiterer geänderter Dateien +4.128 Nutzdatenbytes geschrieben. Im unveränderten finalen Stand waren es +0 Nutzdatenbytes. Das ist ein Funktionsnachweis, kein Durchsatzbenchmark. + +Der lesende Identitätsvergleich für bereits vorhandene Laborsnapshots lautet: + +```sh +python3 /lab/snapshot-identity.py \ + --config /absolute/lab-config.json --snapshot existing-snapshot +``` + +Go liest Verzeichnisquotas in Batches und hält keine Liste aller Dateien. +Das gilt **nicht** als Speicherobergrenze des externen rsync-Prozesses: +große Einzelverzeichnisse und Hardlinkgruppen können dort erheblichen +Speicher benötigen. Jeder Stand verursacht vollständige Scans und +Checksum-Lesevorgänge. Geänderte große Dateien können bei neuen Snapshots +erheblichen zusätzlichen Zielplatz benötigen. + +Im nativen Pfad sind Datei-Worker, Datenpuffer und Verzeichnisiteration begrenzt; +Kopier- und Vergleichspuffer sind höchstens 4 MiB groß und werden für kleine +Dateien bzw. kurze Prüfbereiche entsprechend verkleinert. Identische Besitzer, +Rechte und mtime lösen keinen erneuten `setattr`-Aufruf aus; eine unmittelbar +zuvor gelesene Zielstatistik wird bei der Metadatenprüfung wiederverwendet. +Pfad-/Hardlink-Zuordnungen liegen auf lokalem Datenträger. Snapdiff und Blockdiff +vermeiden wiederholte Vollübertragung und vollständiges Lesen unveränderter +Dateiinhalte. Die Implementierung scannt aber weiterhin alle Metadaten, +einschließlich vollständiger Topologie- und Quotaprüfung. Umbenannte Dateien +können erneut vollständig kopiert werden. Einzeltransaktionen des nativen +Index sind noch nicht auf 200 Millionen Pfade optimiert. + +200 TB und mehr als 200 Millionen Dateien sind damit noch nicht nachgewiesen. +Für diese Freigabe fehlen insbesondere Scans vermeidende Änderungsplanung, +belastbare Speicher-/Laufzeitmessungen, ein Kapazitätsmodell für historische +Versionen sowie ein automatisierter Client-Cutover. Eine feste maximale +Schreibstopplänge wird nicht zugesichert. Native API-Aufrufe sind blockierend; +Abbruch wird zwischen Aufrufen geprüft und wartet auf bereits laufende I/O. + diff --git a/docs/million-local.json b/docs/million-local.json new file mode 100644 index 0000000..71c72f2 --- /dev/null +++ b/docs/million-local.json @@ -0,0 +1,730 @@ +{ + "status": { + "name": "million-itest-88030c39-1619-44d9-9e27-98b66875fcbe", + "total_files": 1000000, + "started_at": "2026-11-06T15:54:20.675466+00:00", + "phase": "complete", + "bytes_per_file": 128, + "layout": "1000 files per directory", + "updated_at": "2026-11-07T00:58:57.634057+00:00", + "roots": { + "source": "/volumes/migration/million-itest-88030c39-1619-44d9-9e27-98b66875fcbe/72e0322f-a366-417e-ba3c-e09bcd2f8ea8", + "target": "/volumes/migration/million-itest-88030c39-1619-44d9-9e27-98b66875fcbe/841dd90b-0817-4cfe-aecd-5487d29149ce" + }, + "root_attrs": { + "user.ceph.subvolume.earmark": "", + "user.ceph.subvolume.enctag": "" + }, + "generated_directories": 1000, + "generated_files": 1000000, + "symlink_times": { + "links/soft000": "2026-11-06T16:27:41", + "links/soft001": "2026-11-06T16:27:41", + "links/soft002": "2026-11-06T16:27:41", + "links/soft003": "2026-11-06T16:27:41", + "links/soft004": "2026-11-06T16:27:41", + "links/soft005": "2026-11-06T16:27:41", + "links/soft006": "2026-11-06T16:27:41", + "links/soft007": "2026-11-06T16:27:41", + "links/soft008": "2026-11-06T16:27:41", + "links/soft009": "2026-11-06T16:27:41", + "links/soft010": "2026-11-06T16:27:41", + "links/soft011": "2026-11-06T16:27:41", + "links/soft012": "2026-11-06T16:27:41", + "links/soft013": "2026-11-06T16:27:41", + "links/soft014": "2026-11-06T16:27:41", + "links/soft015": "2026-11-06T16:27:41", + "links/soft016": "2026-11-06T16:27:41", + "links/soft017": "2026-11-06T16:27:41", + "links/soft018": "2026-11-06T16:27:41", + "links/soft019": "2026-11-06T16:27:41", + "links/soft020": "2026-11-06T16:27:41", + "links/soft021": "2026-11-06T16:27:41", + "links/soft022": "2026-11-06T16:27:41", + "links/soft023": "2026-11-06T16:27:41", + "links/soft024": "2026-11-06T16:27:41", + "links/soft025": "2026-11-06T16:27:41", + "links/soft026": "2026-11-06T16:27:41", + "links/soft027": "2026-11-06T16:27:41", + "links/soft028": "2026-11-06T16:27:41", + "links/soft029": "2026-11-06T16:27:41", + "links/soft030": "2026-11-06T16:27:41", + "links/soft031": "2026-11-06T16:27:41", + "links/soft032": "2026-11-06T16:27:41", + "links/soft033": "2026-11-06T16:27:41", + "links/soft034": "2026-11-06T16:27:41", + "links/soft035": "2026-11-06T16:27:41", + "links/soft036": "2026-11-06T16:27:41", + "links/soft037": "2026-11-06T16:27:41", + "links/soft038": "2026-11-06T16:27:41", + "links/soft039": "2026-11-06T16:27:41", + "links/soft040": "2026-11-06T16:27:41", + "links/soft041": "2026-11-06T16:27:41", + "links/soft042": "2026-11-06T16:27:41", + "links/soft043": "2026-11-06T16:27:41", + "links/soft044": "2026-11-06T16:27:41", + "links/soft045": "2026-11-06T16:27:41", + "links/soft046": "2026-11-06T16:27:41", + "links/soft047": "2026-11-06T16:27:41", + "links/soft048": "2026-11-06T16:27:41", + "links/soft049": "2026-11-06T16:27:41", + "links/soft050": "2026-11-06T16:27:41", + "links/soft051": "2026-11-06T16:27:41", + "links/soft052": "2026-11-06T16:27:41", + "links/soft053": "2026-11-06T16:27:41", + "links/soft054": "2026-11-06T16:27:41", + "links/soft055": "2026-11-06T16:27:41", + "links/soft056": "2026-11-06T16:27:41", + "links/soft057": "2026-11-06T16:27:41", + "links/soft058": "2026-11-06T16:27:41", + "links/soft059": "2026-11-06T16:27:41", + "links/soft060": "2026-11-06T16:27:41", + "links/soft061": "2026-11-06T16:27:41", + "links/soft062": "2026-11-06T16:27:41", + "links/soft063": "2026-11-06T16:27:41", + "links/soft064": "2026-11-06T16:27:41", + "links/soft065": "2026-11-06T16:27:41", + "links/soft066": "2026-11-06T16:27:41", + "links/soft067": "2026-11-06T16:27:41", + "links/soft068": "2026-11-06T16:27:41", + "links/soft069": "2026-11-06T16:27:41", + "links/soft070": "2026-11-06T16:27:41", + "links/soft071": "2026-11-06T16:27:41", + "links/soft072": "2026-11-06T16:27:41", + "links/soft073": "2026-11-06T16:27:41", + "links/soft074": "2026-11-06T16:27:41", + "links/soft075": "2026-11-06T16:27:41", + "links/soft076": "2026-11-06T16:27:41", + "links/soft077": "2026-11-06T16:27:41", + "links/soft078": "2026-11-06T16:27:41", + "links/soft079": "2026-11-06T16:27:41", + "links/soft080": "2026-11-06T16:27:41", + "links/soft081": "2026-11-06T16:27:41", + "links/soft082": "2026-11-06T16:27:41", + "links/soft083": "2026-11-06T16:27:41", + "links/soft084": "2026-11-06T16:27:41", + "links/soft085": "2026-11-06T16:27:41", + "links/soft086": "2026-11-06T16:27:41", + "links/soft087": "2026-11-06T16:27:41", + "links/soft088": "2026-11-06T16:27:41", + "links/soft089": "2026-11-06T16:27:41", + "links/soft090": "2026-11-06T16:27:41", + "links/soft091": "2026-11-06T16:27:41", + "links/soft092": "2026-11-06T16:27:41", + "links/soft093": "2026-11-06T16:27:41", + "links/soft094": "2026-11-06T16:27:41", + "links/soft095": "2026-11-06T16:27:41", + "links/soft096": "2026-11-06T16:27:41", + "links/soft097": "2026-11-06T16:27:41", + "links/soft098": "2026-11-06T16:27:41", + "links/soft099": "2026-11-06T16:27:41" + }, + "prepared": true, + "other_subvolume_writes": 14640, + "phase_started": "2026-11-06T22:45:48.165005+00:00", + "elapsed_seconds": 4810.4, + "peak_rss_kib": 648576, + "last_engine_message": "native verifying paths=987619 target=/volumes/migration/million-itest-88030c39-1619-44d9-9e27-98b66875fcbe/841dd90b-0817-4cfe-aecd-5487d29149ce", + "initial_complete": true, + "mutated_directories": 991, + "mutated": true, + "catchup_complete": true, + "final_complete": true, + "view": "cephmig-6ff40f899047-fd7ff32d5d5f", + "verified_regular_paths": 1000100, + "verified_views": [ + "live", + "baseline", + "cephmig-6ff40f899047-a127c7cf6098", + "cephmig-6ff40f899047-33a1da43488d", + "cephmig-6ff40f899047-fd7ff32d5d5f" + ], + "result": "PASS", + "total_regular_paths_verified": 5000500 + }, + "migration": { + "version": 1, + "id": "6ff40f8990478d1c13b871a2639d1039", + "config": { + "backend": "native", + "workers": 8, + "source": { + "config": "/clusters/source/ceph.conf", + "keyring": "/clusters/source/ceph.client.admin.keyring", + "filesystem": "cephfs", + "group": "migration", + "subvolume": "million-itest-88030c39-1619-44d9-9e27-98b66875fcbe" + }, + "target": { + "config": "/clusters/target/ceph.conf", + "keyring": "/clusters/target/ceph.client.admin.keyring", + "filesystem": "cephfs", + "group": "migration", + "subvolume": "million-itest-88030c39-1619-44d9-9e27-98b66875fcbe" + } + }, + "source_fsid": "b12b8396-606a-4aba-ab7f-dbcf4dc1688f", + "target_fsid": "1a1ab7be-eb67-407f-8694-888c8acdbb06", + "source_path": "/volumes/migration/million-itest-88030c39-1619-44d9-9e27-98b66875fcbe/72e0322f-a366-417e-ba3c-e09bcd2f8ea8", + "target_path": "/volumes/migration/million-itest-88030c39-1619-44d9-9e27-98b66875fcbe/841dd90b-0817-4cfe-aecd-5487d29149ce", + "phase": "ready-for-cutover", + "snapshots": [ + { + "name": "baseline", + "source_created_at": "2026-11-06 16:27:43.568048", + "target_created_at": "2026-11-06 19:28:16.824535", + "owned": false, + "done": true, + "metadata": { + "fixture": "million-v0" + }, + "transfer": { + "mode": "full", + "files_visited": 1001203, + "files_copied": 1000000, + "bytes_copied": 128000000, + "bytes_verified": 128000000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + } + }, + { + "name": "cephmig-6ff40f899047-a127c7cf6098", + "source_created_at": "2026-11-06 20:24:30.570161", + "target_created_at": "2026-11-06 20:49:43.965781", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 1001203, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1002 + } + }, + { + "name": "cephmig-6ff40f899047-33a1da43488d", + "source_created_at": "2026-11-06 21:33:43.340047", + "target_created_at": "2026-11-06 22:06:22.252650", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "cephmig-6ff40f899047-a127c7cf6098", + "files_visited": 1001213, + "files_copied": 50001, + "bytes_copied": 6400128, + "bytes_verified": 6400128, + "blockdiff_files": 0, + "snapdiff_entries": 41012 + } + }, + { + "name": "cephmig-6ff40f899047-fd7ff32d5d5f", + "source_created_at": "2026-11-06 22:45:57.916611", + "target_created_at": "2026-11-06 23:10:42.123700", + "owned": true, + "final": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "cephmig-6ff40f899047-33a1da43488d", + "files_visited": 1001213, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1012 + } + } + ], + "notes": [ + "Native snapshot IDs and Ceph birthtimes are recreated at the target; original creation timestamps are recorded in the migration journal." + ], + "live_snapshot": "cephmig-6ff40f899047-fd7ff32d5d5f" + }, + "phases": { + "initial": { + "seconds": 18070.86489043699, + "wall_seconds": 18070.86489009857, + "peak_rss_kib": 661740, + "snapshots": [ + { + "name": "baseline", + "source_created_at": "2026-11-06 16:27:43.568048", + "target_created_at": "2026-11-06 19:28:16.824535", + "owned": false, + "done": true, + "metadata": { + "fixture": "million-v0" + }, + "transfer": { + "mode": "full", + "files_visited": 1001203, + "files_copied": 1000000, + "bytes_copied": 128000000, + "bytes_verified": 128000000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + } + }, + { + "name": "cephmig-6ff40f899047-a127c7cf6098", + "source_created_at": "2026-11-06 20:24:30.570161", + "target_created_at": "2026-11-06 20:49:43.965781", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 1001203, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1002 + } + } + ], + "mds": { + "source": { + "requests": 18253200, + "getattr": 8130318, + "lookupsnap": 8097116 + }, + "target": { + "requests": 22197800, + "getattr": 4068615, + "lookupsnap": 4033247 + } + } + }, + "catchup": { + "seconds": 4333.497519656987, + "wall_seconds": 4333.497520208359, + "peak_rss_kib": 510052, + "snapshots": [ + { + "name": "baseline", + "source_created_at": "2026-11-06 16:27:43.568048", + "target_created_at": "2026-11-06 19:28:16.824535", + "owned": false, + "done": true, + "metadata": { + "fixture": "million-v0" + }, + "transfer": { + "mode": "full", + "files_visited": 1001203, + "files_copied": 1000000, + "bytes_copied": 128000000, + "bytes_verified": 128000000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + } + }, + { + "name": "cephmig-6ff40f899047-a127c7cf6098", + "source_created_at": "2026-11-06 20:24:30.570161", + "target_created_at": "2026-11-06 20:49:43.965781", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 1001203, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1002 + } + }, + { + "name": "cephmig-6ff40f899047-33a1da43488d", + "source_created_at": "2026-11-06 21:33:43.340047", + "target_created_at": "2026-11-06 22:06:22.252650", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "cephmig-6ff40f899047-a127c7cf6098", + "files_visited": 1001213, + "files_copied": 50001, + "bytes_copied": 6400128, + "bytes_verified": 6400128, + "blockdiff_files": 0, + "snapdiff_entries": 41012 + } + } + ], + "mds": { + "source": { + "requests": 6531338, + "getattr": 3209017, + "lookupsnap": 3190207 + }, + "target": { + "requests": 10343770, + "getattr": 2039796, + "lookupsnap": 2016662 + } + } + }, + "final": { + "seconds": 4823.694291661988, + "wall_seconds": 4823.694292068481, + "peak_rss_kib": 648576, + "snapshots": [ + { + "name": "baseline", + "source_created_at": "2026-11-06 16:27:43.568048", + "target_created_at": "2026-11-06 19:28:16.824535", + "owned": false, + "done": true, + "metadata": { + "fixture": "million-v0" + }, + "transfer": { + "mode": "full", + "files_visited": 1001203, + "files_copied": 1000000, + "bytes_copied": 128000000, + "bytes_verified": 128000000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + } + }, + { + "name": "cephmig-6ff40f899047-a127c7cf6098", + "source_created_at": "2026-11-06 20:24:30.570161", + "target_created_at": "2026-11-06 20:49:43.965781", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 1001203, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1002 + } + }, + { + "name": "cephmig-6ff40f899047-33a1da43488d", + "source_created_at": "2026-11-06 21:33:43.340047", + "target_created_at": "2026-11-06 22:06:22.252650", + "owned": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "cephmig-6ff40f899047-a127c7cf6098", + "files_visited": 1001213, + "files_copied": 50001, + "bytes_copied": 6400128, + "bytes_verified": 6400128, + "blockdiff_files": 0, + "snapdiff_entries": 41012 + } + }, + { + "name": "cephmig-6ff40f899047-fd7ff32d5d5f", + "source_created_at": "2026-11-06 22:45:57.916611", + "target_created_at": "2026-11-06 23:10:42.123700", + "owned": true, + "final": true, + "done": true, + "transfer": { + "mode": "snapdiff", + "base_snapshot": "cephmig-6ff40f899047-33a1da43488d", + "files_visited": 1001213, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 1012 + } + } + ], + "mds": { + "source": { + "requests": 8168892, + "getattr": 4089126, + "lookupsnap": 4065642 + }, + "target": { + "requests": 11090199, + "getattr": 2042174, + "lookupsnap": 2016662 + } + } + } + }, + "ceph_capacity": { + "source": { + "stats": { + "total_bytes": 25769803776, + "total_avail_bytes": 19139497984, + "total_used_bytes": 6630305792, + "total_used_raw_bytes": 6630305792, + "total_used_raw_ratio": 0.25728973746299744, + "num_osds": 1, + "num_per_pool_osds": 1, + "num_per_pool_omap_osds": 1 + }, + "stats_by_class": { + "hdd": { + "total_bytes": 25769803776, + "total_avail_bytes": 19139497984, + "total_used_bytes": 6630305792, + "total_used_raw_bytes": 6630305792, + "total_used_raw_ratio": 0.25728973746299744 + } + }, + "pools": [ + { + "name": ".mgr", + "id": 1, + "stats": { + "stored": 459280, + "objects": 2, + "kb_used": 452, + "bytes_used": 462848, + "percent_used": 2.5927725801011547e-05, + "max_avail": 17851006976 + } + }, + { + "name": "cephfs.cephfs.meta", + "id": 2, + "stats": { + "stored": 364305904, + "objects": 1097, + "kb_used": 355799, + "bytes_used": 364338160, + "percent_used": 0.020001715049147606, + "max_avail": 17851006976 + } + }, + { + "name": "cephfs.cephfs.data", + "id": 3, + "stats": { + "stored": 130822024, + "objects": 1032269, + "kb_used": 4088184, + "bytes_used": 4186300416, + "percent_used": 0.18996424973011017, + "max_avail": 17851006976 + } + } + ] + }, + "target": { + "stats": { + "total_bytes": 25769803776, + "total_avail_bytes": 19254382592, + "total_used_bytes": 6515421184, + "total_used_raw_bytes": 6515421184, + "total_used_raw_ratio": 0.2528316080570221, + "num_osds": 1, + "num_per_pool_osds": 1, + "num_per_pool_omap_osds": 1 + }, + "stats_by_class": { + "hdd": { + "total_bytes": 25769803776, + "total_avail_bytes": 19254382592, + "total_used_bytes": 6515421184, + "total_used_raw_bytes": 6515421184, + "total_used_raw_ratio": 0.2528316080570221 + } + }, + "pools": [ + { + "name": ".mgr", + "id": 1, + "stats": { + "stored": 459280, + "objects": 2, + "kb_used": 452, + "bytes_used": 462848, + "percent_used": 2.5761932192835957e-05, + "max_avail": 17965891584 + } + }, + { + "name": "cephfs.cephfs.meta", + "id": 2, + "stats": { + "stored": 292899984, + "objects": 1080, + "kb_used": 286067, + "bytes_used": 292932244, + "percent_used": 0.016043325886130333, + "max_avail": 17965891584 + } + }, + { + "name": "cephfs.cephfs.data", + "id": 3, + "stats": { + "stored": 134670016, + "objects": 1102814, + "kb_used": 4208436, + "bytes_used": 4309438464, + "percent_used": 0.19346238672733307, + "max_avail": 17965891584 + } + } + ] + } + }, + "ceph_health": { + "source": { + "status": "HEALTH_WARN", + "checks": { + "BLUESTORE_BLUEFS_OVERSIZED": { + "severity": "HEALTH_WARN", + "summary": { + "message": "1 OSD(s) have BlueFS usage exceeding configured ratio of main device size", + "count": 1 + }, + "detail": [ + { + "message": " osd.0 BlueFS usage (2.1 GiB) exceeds 6.0000% of main device (24 GiB, 8.67%)" + } + ], + "muted": false + }, + "BLUESTORE_SLOW_OP_ALERT": { + "severity": "HEALTH_WARN", + "summary": { + "message": "1 OSD(s) experiencing slow operations in BlueStore", + "count": 1 + }, + "detail": [ + { + "message": " osd.0 observed slow operation indications in BlueStore" + } + ], + "muted": false + }, + "MON_DISK_LOW": { + "severity": "HEALTH_WARN", + "summary": { + "message": "mon a is low on available space", + "count": 1 + }, + "detail": [ + { + "message": "mon.a has 8% avail" + } + ], + "muted": false + }, + "POOL_NO_REDUNDANCY": { + "severity": "HEALTH_WARN", + "summary": { + "message": "3 pool(s) have no replicas configured", + "count": 3 + }, + "detail": [ + { + "message": "pool '.mgr' has no replicas configured" + }, + { + "message": "pool 'cephfs.cephfs.meta' has no replicas configured" + }, + { + "message": "pool 'cephfs.cephfs.data' has no replicas configured" + } + ], + "muted": false + } + }, + "mutes": [] + }, + "target": { + "status": "HEALTH_WARN", + "checks": { + "BLUESTORE_BLUEFS_OVERSIZED": { + "severity": "HEALTH_WARN", + "summary": { + "message": "1 OSD(s) have BlueFS usage exceeding configured ratio of main device size", + "count": 1 + }, + "detail": [ + { + "message": " osd.0 BlueFS usage (1.9 GiB) exceeds 6.0000% of main device (24 GiB, 8.05%)" + } + ], + "muted": false + }, + "BLUESTORE_SLOW_OP_ALERT": { + "severity": "HEALTH_WARN", + "summary": { + "message": "1 OSD(s) experiencing slow operations in BlueStore", + "count": 1 + }, + "detail": [ + { + "message": " osd.0 observed slow operation indications in BlueStore" + } + ], + "muted": false + }, + "MON_DISK_LOW": { + "severity": "HEALTH_WARN", + "summary": { + "message": "mon a is low on available space", + "count": 1 + }, + "detail": [ + { + "message": "mon.a has 8% avail" + } + ], + "muted": false + }, + "POOL_NO_REDUNDANCY": { + "severity": "HEALTH_WARN", + "summary": { + "message": "3 pool(s) have no replicas configured", + "count": 3 + }, + "detail": [ + { + "message": "pool '.mgr' has no replicas configured" + }, + { + "message": "pool 'cephfs.cephfs.meta' has no replicas configured" + }, + { + "message": "pool 'cephfs.cephfs.data' has no replicas configured" + } + ], + "muted": false + } + }, + "mutes": [] + } + }, + "host_osd_allocation": { + "source": { + "logical_bytes": 25769803776, + "allocated_bytes": 19682660352 + }, + "target": { + "logical_bytes": 25769803776, + "allocated_bytes": 24452927488 + } + }, + "image": "sha256:38319ffd757a86af4ec3eba7a0d32b374c40b2b658c3bb920ab051ef074cebdf", + "recorded_at": "2026-11-07T00:59:01.049376+00:00" +} diff --git a/docs/million-local.md b/docs/million-local.md new file mode 100644 index 0000000..8411fd0 --- /dev/null +++ b/docs/million-local.md @@ -0,0 +1,100 @@ +# Lokaler Millionentest mit Snapshots + +## Ergebnis vom 06./07.11.2026 + +**PASS**, abgeschlossen am 07.11.2026 um 01:58:57 Uhr MEZ. Der Job erreichte +`ready-for-cutover`. Die unabhängige Prüfung bestätigte den aktuellen Zielstand +und vier Snapshots: insgesamt **5.000.500 reguläre Dateipfade**, zusätzlich +Symlinks, Verzeichnisse, Besitzer, Rechte, ACLs, xattrs, Quotas und Snapshot- +Benutzermetadaten. Ein anderes Subvolume blieb mit 14.640 bestätigten +Schreibvorgängen beschreibbar. + +| Phase einschließlich interner Prüfungen | Dauer | Geschriebene Nutzdaten | MDS-Anfragen, beide Cluster | +|---|---:|---:|---:| +| Erstabgleich, bestehender und neuer Snapshot | 5 h 01 min 11 s | 128.000.000 Byte | 40.451.000 | +| Änderungsabgleich | 1 h 12 min 13 s | 6.400.128 Byte | 16.875.108 | +| Finalisierung, unveränderte Quelle | 1 h 20 min 24 s | 0 Byte | 19.259.091 | + +Die erste vollständige Kopie einschließlich abschließender Inventar- und +Metadatenarbeit dauerte rund 1 h 40 min; die erste vollständige Prüfung des +Live-Ziels danach etwa 1 h 21 min. Das gesamte Testszenario einschließlich +Datenerzeugung, Änderungen und unabhängiger Prüfung dauerte 9 h 04 min 37 s. +Maximal erfasster RSS des Go-Prozesses über die drei Phasen: 646,2 MiB. +Die Rohmesswerte stehen in [million-local.json](million-local.json). + +Die vollständigen Metadatendurchläufe bleiben teuer: Selbst die Finalisierung +ohne Nutzdatenänderungen verursachte rund 19,3 Millionen MDS-Anfragen. Der +Prüfpfad ist derzeit seriell. Ceph meldete während des Laufs außerdem langsame +BlueStore-Operationen und einen hohen BlueFS-Anteil auf den kleinen Test-OSDs. +Die genauen Anteile von CPU und Datenträgerlatenz wurden nicht isoliert +profiliert. Es gab keine Prüfung der produktiven 2×25-Gbit-Verbindung. +Der Lauf belegt die geprüfte Datenkorrektheit im Labor; ein kurzer finaler +Schreibstopp für 200 Millionen Dateien ist damit noch nicht nachgewiesen. +Die Finalisierungsdauer enthält keinen Anwendungsneustart oder Client-Remount. + +Die automatische Bereinigung entfernte ausschließlich das Projekt +`cephmig-million` samt Testvolumes am 07.11.2026 gegen 02:03 Uhr MEZ. +Die Berichte blieben erhalten; danach waren rund 84 GiB Hostspeicher frei. + +## Testaufbau + +Der Test legt 1.000.000 Dateien mit je 128 Byte reproduzierbarem Inhalt an, +verteilt auf 1.000 Verzeichnisse. Dazu kommen 100 Hardlink-Namen und 100 Symlinks, +numerische Besitzer, POSIX-Zugriffs-/Default-ACLs, Benutzer-xattrs und Quotas. + +Ein vor der Migration angelegter Snapshot enthält den ursprünglichen Stand. +Nach dem Erstabgleich ändert der Anwendungsclient jeweils 1 % der Inhalte, +Dateinamen, Rechte/xattrs, löscht 1 % der Dateien und legt 1 % neue Dateien an. +Inhaltsänderungen behalten die ursprüngliche mtime. Danach folgen Änderungsabgleich +und Finalisierung mit gestopptem Testschreiber. Ein Schreiber in einem anderen +Subvolume läuft währenddessen weiter und bestätigt seine Schreibvorgänge mit fsync. + +Nach der Migration liest ein separater Python-libcephfs-Client den aktuellen +Zielstand und vier Ziel-Snapshots vollständig. Erwartete Inhalte und Metadaten +werden aus dem Testmodell berechnet. SQLite prüft auf Platte die bijektive +Zuordnung der Inodes zu Hardlink-Gruppen. Insgesamt sind 5.000.500 reguläre +Dateipfade sowie Symlinks, Verzeichnisse, ACLs, xattrs, Quotas und Snapshot- +Benutzermetadaten zu prüfen. Die Go-Migration prüft zusätzlich intern. +Ceph-interne Snapshot-IDs und ursprüngliche Erstellungszeitpunkte werden nicht +erhalten; diese bekannte Einschränkung bleibt bestehen. + +## Start und Fortschritt + +```sh +make dev-million-start +make dev-million-status +docker compose -p cephmig-million -f dev/compose.yaml -f dev/compose.million.yaml logs -f benchmark +``` + +Das getrennte Compose-Projekt verwendet zwei dünn belegte 24-GiB-OSDs und +höchstens 10 GiB Container-RAM. Für den ersten Start sind 68 GiB freier +Hostspeicher vorgesehen: maximal 48 GiB OSDs plus 20 GiB Reserve. Die laufende +Prüfung stoppt weitere Schreibvorgänge bei weniger als 20 GiB Hostreserve, +3 GiB freiem Host-RAM oder 3 GiB freiem Ceph-Speicher je Cluster. +Images, bestehende Testcluster und deren Speicher kommen hinzu. Es werden keine +Kernel- oder FUSE-Mounts benötigt. Die Daemons laufen mit einem MDS-Cachelimit +von jeweils 768 MiB. Die Laufzeit hängt stark vom Datenträger und den anderen +Prozessen auf dem Host ab. + +Der Treiber läuft als eigener Container weiter. Status, Protokolle, MDS-Zähler, +Laufzeiten und abgetasteter maximaler RSS des Go-Prozesses liegen unter +`.dev/million/main/`. Nur `result: PASS` bestätigt die vollständige Prüfung. +Erzeugung und abgeschlossene Prüfansichten haben Checkpoints; ein unterbrochener +Go-Abgleich verwendet das bestehende Migrationsjournal. Eine unterbrochene +Phase zählt nicht als verwertbare Laufzeitmessung. Die Testerzeugung läuft mit +acht Threads, der Kopierer mit acht Workern, die unabhängige Prüfung mit 16 Threads. +Queues und Datenpuffer sind begrenzt; Index und Inode-Zuordnung liegen auf Platte. + +## Bereinigung + +Nach erfolgreicher Prüfung Messwerte nach `docs/million-local.json` sichern +und ausschließlich dieses Testprojekt entfernen. Der Befehl verweigert die +Bereinigung ohne `PASS` und erfolgreichen Container-Exit: + +```sh +make dev-million-finish +``` + +Die Berichte auf dem Host bleiben erhalten. Das Projekt `cephmig-dev` ist separat. +Ein lokaler Lauf ist kein Leistungsnachweis für 200 TB oder 200 Millionen Dateien. +MDS-Anfragen sind keine Messung physischer Datenträger-IOPS. diff --git a/docs/raw-transfer.md b/docs/raw-transfer.md new file mode 100644 index 0000000..ac52969 --- /dev/null +++ b/docs/raw-transfer.md @@ -0,0 +1,107 @@ +# Direkter RADOS-Transfer eines einzelnen Subvolumes + +Geprüft am 05.11.2026 für die Anforderung: genau ein CephFS-Subvolume zwischen +unabhängigen Clustern migrieren, während andere Subvolumes weiterlaufen. +Native Snapshot-IDs und Geburtszeitpunkte dürfen dabei abweichen. + +## Ergebnis + +Ein roher Import von RADOS-Daten- und Metadatenobjekten ist unter diesen +Bedingungen kein geprüfter Ersatz für den vorhandenen Transport. Der aktuelle +Code wurde deshalb nicht auf einen solchen Import umgestellt. + +RADOS kann Objektinhalt, xattrs und OMAP lesen und schreiben. Damit ist jedoch +noch kein separat einhängbares CephFS-Subvolume übertragen: + +- Der MDS-Metadatenpool enthält die Hierarchie und dateisystemweite Zustände, + etwa Journale, Inode-/Snapshot-Verwaltung und Clientsitzungen. +- Ein Subvolume hat keinen unabhängigen MDS-Metadatenpool. Ein separater + Daten-Namespace würde nur bei der Zuordnung von Datenobjekten helfen. +- Dateilayouts und Metadaten beziehen sich auf Inodes, Pools und Snapshots der + Quelle. Sie dürfen nicht unverändert in ein laufendes, anders aufgebautes + Ziel-Dateisystem importiert werden. +- Der untersuchte RADOS-Pool-Export schreibt ausdrücklich nur HEAD-Objekte. + Historische RADOS-Snapshot-Versionen sind damit nicht als vollständige + CephFS-Snapshot-Historie migriert. +- Die dokumentierte Pool-Migration beschreibt Migration zwischen Pools + innerhalb desselben Clusters. Sie ist keine Subvolume-Replikation zwischen + unabhängigen Clustern. + +Die Schlussfolgerung folgt aus diesen Verwaltungs- und Konsistenzabhängigkeiten: +Ein eigener Raw-Kopierer müsste zusätzlich eine konsistente Teilmenge der +CephFS-Metadaten exportieren, auf die Zielidentitäten abbilden und mit dessen +laufendem MDS koordinieren. Ein gewöhnlicher Objektkopierer leistet das nicht. +Auch ein Objekttransfer muss die erforderlichen Nutzdaten zum Ziel bewegen. + +## Geprüfte native Alternative + +Der Go-Transport `backend: native` verwendet libcephfs ohne rsync und ohne +Kernel-/FUSE-Mount. Metadatenoperationen erfolgen über den Ziel-MDS; +Daten-I/O übernimmt der native Ceph-Client direkt gegen RADOS. Ein roher Import +des gemeinsamen MDS-Metadatenpools ist weiterhin nicht Bestandteil der Migration. + +In der tatsächlich laufenden Bibliothek des Labors wurden folgende Symbole +geprüft: + +| Schnittstelle | Vorhanden | +| --- | --- | +| ceph_open_snapdiff | ja | +| ceph_open_snapdiff2 | nein | +| ceph_readdir_snapdiff2 | nein | +| ceph_file_blockdiff_init | ja | +| ceph_file_blockdiff | ja | +| ceph_file_blockdiff_finish | ja | + +Die installierte Ceph-21.2.0-Konfiguration kennt +`cephfs_mirror_blockdiff_min_file_size` mit Standardwert 16 MiB. + +Implementierter Ablauf: + +1. Initialer nativer Transfer des Snapshotstands. +2. Snapdiff zum Ermitteln geänderter Verzeichniseinträge. +3. Blockdiff für geeignete geänderte Dateien; notwendige Datenbereiche übertragen. +4. Hardlink-Zuordnungen, ACLs, xattrs, Quotas und Journal weiterhin explizit verwalten. +5. Gezielte Verifikation der Änderungen und ein finaler Abgleich beim Schreibstopp. + +Der Backendpfad liegt in `internal/migration/native_*.go`, die schmale CGO-Anbindung +an öffentliche Ceph-Schnittstellen in `internal/cephfsnative`. Aktivierung: +`go build -tags ceph` mit CGO, C-Compiler und passenden libcephfs-Headern. +`make dev-native-test` baut diese Abhängigkeiten im Container und prüft den +Transport zwischen den unabhängigen Laborclustern. + +Snapdiff markiert geänderte Inodes; zusätzlich verhindert der Vergleich der +Ceph-Inode-Version, dass Datenänderungen mit gleicher Größe und mtime entgehen. +Blockdiff wird ab 16 MiB verwendet, sofern eine bestätigte Basis mit passenden +Quell-/Ziel-Inodes vorliegt. Bei nicht verfügbaren Diff-Schnittstellen wird +nativ vollständig rekonstruiert. Es gibt keinen stillen rsync-Fallback. + +Die Implementierung scannt derzeit trotzdem alle Metadaten und prüft die +Hardlink-Topologie jedes Standes vollständig. Snapdiff ersetzt diese Scans noch +nicht. Datenprüfung liest beim ersten Stand alle Bytes, bei bestätigten +Folgeständen nur kopierte Bereiche. Unveränderte Bereiche werden aus der zuvor +verifizierten Basis übernommen. Das Ziel muss exklusiv dem Migrationsjob gehören; +fremde Änderungen an unveränderten Bereichen werden damit nicht umfassend erkannt. +Ein Index auf lokalem Datenträger bindet die Basis an Cluster, Datenpfade und +Journal. Vor jeder Änderung wird ihre Gültigkeit im Journal entzogen. Ein Abbruch +erzwingt im nächsten Prozess eine vollständige Rekonstruktion des offenen Standes. + +Ein Laufzeit- oder Durchsatznachweis für 200 TB / 200 Millionen Dateien fehlt. +Auch nach einem Abbruch kann die vollständige Rekonstruktion entsprechend lange +dauern. Die Zahl der durch die Anwendung geänderten Bytes ist keine feste +Obergrenze für die vom OSD gemeldeten geänderten Bereiche. + +Das fertige cephfs-mirror verwendet native Replikation, unterstützt laut +Dokumentation aber keine Erhaltung gemeinsamer Hardlink-Inodes. Es würde +Hardlink-Dateien als getrennte Dateien synchronisieren. Deshalb wäre ein +ungeprüfter Wechsel auf cephfs-mirror kein Ersatz für die vereinbarten +Link-Anforderungen. + +## Primärquellen + +- [MDS-Metadatenpool und Journale](https://docs.ceph.com/en/latest/cephfs/mds-journaling/) +- [CephFS-Architektur und direkter RADOS-Datenzugriff](https://docs.ceph.com/en/latest/cephfs/index.html) +- [PoolDump: Export nur des HEAD-Zustands](https://github.com/ceph/ceph/blob/main/src/tools/rados/PoolDump.cc) +- [Pool-Migration innerhalb desselben Clusters](https://docs.ceph.com/en/latest/dev/pool-migration-design/) +- [libcephfs: Snapdiff und Blockdiff](https://github.com/ceph/ceph/blob/main/src/include/cephfs/libcephfs.h) +- [CephFS-Mirroring: Blockdiff und Hardlink-Grenzen](https://docs.ceph.com/en/latest/cephfs/cephfs-mirroring/) + diff --git a/docs/smallfiles-local.json b/docs/smallfiles-local.json new file mode 100644 index 0000000..eb2c1ef --- /dev/null +++ b/docs/smallfiles-local.json @@ -0,0 +1,414 @@ +{ + "lab": "Two independent Ceph 21.2.0 clusters, each one MON/MGR/MDS and one 4-GiB file-backed BlueStore OSD; same shared host; four copy workers.", + "method": "128-byte deterministic nonzero files; half flat and half across 50 directories; 100 hardlink aliases and 100 symlinks; content/change/delete/rename/new/metadata cases; independent FUSE validation of live tree and all four snapshots. The 2000-file comparisons additionally include numeric non-root ownership and POSIX access/default ACLs.", + "runs": { + "baseline_10000": { + "phases": { + "initial": { + "seconds": 554.412, + "peak_rss_kib": 138656, + "bytes_written": 1280000, + "files_copied": 10000, + "rounds": [ + { + "name": "baseline", + "mode": "full", + "files_visited": 10254, + "files_copied": 10000, + "bytes_copied": 1280000, + "bytes_verified": 1280000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + }, + { + "name": "cephmig-c34587df4cd5-101b88303f64", + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 10254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ] + }, + "catchup": { + "seconds": 459.292, + "peak_rss_kib": 127016, + "bytes_written": 64128, + "files_copied": 501, + "rounds": [ + { + "name": "cephmig-c34587df4cd5-dc58410bd6ca", + "mode": "snapdiff", + "base_snapshot": "cephmig-c34587df4cd5-101b88303f64", + "files_visited": 10254, + "files_copied": 501, + "bytes_copied": 64128, + "bytes_verified": 64128, + "blockdiff_files": 0, + "snapdiff_entries": 453 + } + ] + }, + "final": { + "seconds": 84.147, + "peak_rss_kib": 117068, + "bytes_written": 0, + "files_copied": 0, + "rounds": [ + { + "name": "cephmig-c34587df4cd5-a5031d3d1f04", + "mode": "snapdiff", + "base_snapshot": "cephmig-c34587df4cd5-dc58410bd6ca", + "files_visited": 10254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ] + } + }, + "verification": { + "live_files_checked": 10100, + "snapshots": [ + { + "name": "baseline", + "files_checked": 10100 + }, + { + "name": "cephmig-c34587df4cd5-101b88303f64", + "files_checked": 10100 + }, + { + "name": "cephmig-c34587df4cd5-dc58410bd6ca", + "files_checked": 10100 + }, + { + "name": "cephmig-c34587df4cd5-a5031d3d1f04", + "files_checked": 10100 + } + ], + "seconds": 600.677 + }, + "image": "sha256:e140f90a9737f0be756f2396ebe5dbba709b5fbda92db7aace8d7da0786e2129", + "source_raw_used_delta_bytes": 284422144, + "target_raw_used_delta_bytes": 761856000, + "local_state_kib": 1628 + }, + "before_2000": { + "phases": { + "initial": { + "seconds": 490.197, + "peak_rss_kib": 95960, + "bytes_written": 256000, + "files_copied": 2000, + "rounds": [ + { + "name": "baseline", + "mode": "full", + "files_visited": 2254, + "files_copied": 2000, + "bytes_copied": 256000, + "bytes_verified": 256000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + }, + { + "name": "cephmig-16df989f3ef6-12f9d260ba97", + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 2254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ], + "mds": { + "source": { + "requests": 72443, + "getattr": 34917, + "lookup": 274, + "lookupsnap": 32972, + "setattr": 0, + "readdir": 110 + }, + "target": { + "requests": 42689, + "getattr": 16239, + "lookup": 4813, + "lookupsnap": 14152, + "setattr": 2254, + "readdir": 166 + } + } + }, + "catchup": { + "seconds": 52.159, + "peak_rss_kib": 74008, + "bytes_written": 12928, + "files_copied": 101, + "rounds": [ + { + "name": "cephmig-16df989f3ef6-4cc40889f324", + "mode": "snapdiff", + "base_snapshot": "cephmig-16df989f3ef6-12f9d260ba97", + "files_visited": 2254, + "files_copied": 101, + "bytes_copied": 12928, + "bytes_verified": 12928, + "blockdiff_files": 0, + "snapdiff_entries": 133 + } + ], + "mds": { + "source": { + "requests": 31356, + "getattr": 15926, + "lookup": 196, + "lookupsnap": 14893, + "setattr": 0, + "readdir": 55 + }, + "target": { + "requests": 21321, + "getattr": 8262, + "lookup": 5122, + "lookupsnap": 7076, + "setattr": 205, + "readdir": 122 + } + } + }, + "final": { + "seconds": 30.086, + "peak_rss_kib": 65556, + "bytes_written": 0, + "files_copied": 0, + "rounds": [ + { + "name": "cephmig-16df989f3ef6-b695d046dded", + "mode": "snapdiff", + "base_snapshot": "cephmig-16df989f3ef6-4cc40889f324", + "files_visited": 2254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ], + "mds": { + "source": { + "requests": 40410, + "getattr": 20722, + "lookup": 158, + "lookupsnap": 19388, + "setattr": 0, + "readdir": 55 + }, + "target": { + "requests": 18940, + "getattr": 8622, + "lookup": 2770, + "lookupsnap": 7076, + "setattr": 101, + "readdir": 111 + } + } + } + }, + "verification": { + "live_files_checked": 2100, + "snapshots": [ + { + "name": "baseline", + "files_checked": 2100 + }, + { + "name": "cephmig-16df989f3ef6-12f9d260ba97", + "files_checked": 2100 + }, + { + "name": "cephmig-16df989f3ef6-4cc40889f324", + "files_checked": 2100 + }, + { + "name": "cephmig-16df989f3ef6-b695d046dded", + "files_checked": 2100 + } + ], + "seconds": 131.604 + }, + "image": "sha256:27d4b00ba7745c4449e78af1b2c5ac276f752613fc71c66db7f369e32687ab6b", + "source_raw_used_delta_bytes": 10969088, + "target_raw_used_delta_bytes": 146714624, + "local_state_kib": 440 + }, + "after_2000": { + "phases": { + "initial": { + "seconds": 55.151, + "peak_rss_kib": 78208, + "bytes_written": 256000, + "files_copied": 2000, + "rounds": [ + { + "name": "baseline", + "mode": "full", + "files_visited": 2254, + "files_copied": 2000, + "bytes_copied": 256000, + "bytes_verified": 256000, + "blockdiff_files": 0, + "snapdiff_entries": 0 + }, + { + "name": "cephmig-88b9689c7436-d293f230cff5", + "mode": "snapdiff", + "base_snapshot": "baseline", + "files_visited": 2254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ], + "mds": { + "source": { + "requests": 45087, + "getattr": 21289, + "lookup": 149, + "lookupsnap": 19450, + "setattr": 0, + "readdir": 110 + }, + "target": { + "requests": 42350, + "getattr": 11698, + "lookup": 13624, + "lookupsnap": 9644, + "setattr": 2254, + "readdir": 166 + } + } + }, + "catchup": { + "seconds": 21.157, + "peak_rss_kib": 66536, + "bytes_written": 12928, + "files_copied": 101, + "rounds": [ + { + "name": "cephmig-88b9689c7436-1a7033d3e834", + "mode": "snapdiff", + "base_snapshot": "cephmig-88b9689c7436-d293f230cff5", + "files_visited": 2254, + "files_copied": 101, + "bytes_copied": 12928, + "bytes_verified": 12928, + "blockdiff_files": 0, + "snapdiff_entries": 133 + } + ], + "mds": { + "source": { + "requests": 17685, + "getattr": 9124, + "lookup": 133, + "lookupsnap": 8092, + "setattr": 0, + "readdir": 55 + }, + "target": { + "requests": 21226, + "getattr": 5976, + "lookup": 9583, + "lookupsnap": 4822, + "setattr": 205, + "readdir": 122 + } + } + }, + "final": { + "seconds": 24.066, + "peak_rss_kib": 63992, + "bytes_written": 0, + "files_copied": 0, + "rounds": [ + { + "name": "cephmig-88b9689c7436-634b26608cdd", + "mode": "snapdiff", + "base_snapshot": "cephmig-88b9689c7436-1a7033d3e834", + "files_visited": 2254, + "files_copied": 0, + "bytes_copied": 0, + "bytes_verified": 0, + "blockdiff_files": 0, + "snapdiff_entries": 53 + } + ], + "mds": { + "source": { + "requests": 22323, + "getattr": 11706, + "lookup": 103, + "lookupsnap": 10373, + "setattr": 0, + "readdir": 55 + }, + "target": { + "requests": 18751, + "getattr": 6270, + "lookup": 7209, + "lookupsnap": 4822, + "setattr": 101, + "readdir": 111 + } + } + } + }, + "verification": { + "live_files_checked": 2100, + "snapshots": [ + { + "name": "baseline", + "files_checked": 2100 + }, + { + "name": "cephmig-88b9689c7436-d293f230cff5", + "files_checked": 2100 + }, + { + "name": "cephmig-88b9689c7436-1a7033d3e834", + "files_checked": 2100 + }, + { + "name": "cephmig-88b9689c7436-634b26608cdd", + "files_checked": 2100 + } + ], + "seconds": 130.061 + }, + "image": "sha256:0d8c355cbfa896b2a3f843d4ed0eee30f5ad86616a0d6afdefb50e2e07b2f934", + "source_raw_used_delta_bytes": 18640896, + "target_raw_used_delta_bytes": 138170368, + "local_state_kib": 464 + } + }, + "binaries_sha256": "af66d7499e10961c0bd0f4a7e07b81b706b5061abf0c08bda67fb9b03835cba9 /state/benchmark-binaries/cephmig-before\n871f69016ce2f692397bf578a2a207d02580df3c072c307fb82d4b3df5615ae0 /usr/local/bin/cephmig-native\n", + "caveats": [ + "Single runs, no production throughput guarantee. Original 2000-file baseline without counters varied between 99 and 490 seconds for the first run; MDS lock waits were observed.", + "MDS counters measure completed metadata requests, including CLI/control activity; they do not measure physical block-device IOPS.", + "Raw-used differences include asynchronous Ceph allocation, journals and BlueFS/RocksDB growth and are not an isolated capacity model.", + "The interrupted overnight comparison and its 42-second resume are discarded from the comparison.", + "Full source and target metadata walks remain; 200 TB / 200 million files are not validated." + ], + "regression_validation": "Passed: ceph-tagged Go unit tests with race detector and vet; full native Ceph integration including historical snapshots, sparse/large files, blockdiff, ACLs, quotas, hardlinks on symlinks/FIFOs, cancellations and crash resume; successful test fixtures removed." +} diff --git a/docs/smallfiles-local.md b/docs/smallfiles-local.md new file mode 100644 index 0000000..3c3120f --- /dev/null +++ b/docs/smallfiles-local.md @@ -0,0 +1,53 @@ +# Lokaler Test mit vielen kleinen Dateien + +Gemessen am 05./06.11.2026 mit Ceph 21.2.0. Zwei unabhängige Laborcluster, je ein MON/MGR/MDS und ein dateibasierter 4-GiB-BlueStore-OSD auf demselben Host; vier Kopier-Worker. + +Jede Datei enthält 128 Byte deterministische, nicht ausschließlich nullwertige Daten. Eine Hälfte liegt in einem großen Verzeichnis, die andere verteilt auf 50 Verzeichnisse. Zusätzlich: 100 Hardlink-Namen und 100 Symlinks. Änderungen: jeweils 1 % Inhalt, Löschungen, Umbenennungen, neue Dateien, Modus/xattr-Änderungen und xattr-Löschungen. Die 2.000-Dateien-Läufe enthalten außerdem numerische Besitzer und Zugriffs-/Default-ACLs. + +## Vergleich mit 2.000 Dateien + +| Phase | Vorher | Nachher | MDS-Anfragen vorher | MDS-Anfragen nachher | +|---|---:|---:|---:|---:| +| Erstlauf, zwei Stände | 490.2 s | 55.2 s | 115.132 | 87.437 | +| Änderungsabgleich | 52.2 s | 21.2 s | 52.677 | 38.911 | +| Finaler Abgleich | 30.1 s | 24.1 s | 59.350 | 41.074 | + +Im finalen Lauf: 30.8 % weniger MDS-Anfragen, 20.0 % kürzere Laufzeit. In beiden Varianten wurden dabei 0 Nutzdatenbytes geschrieben. Der Änderungsabgleich schrieb in beiden Varianten 12.928 Byte für 101 Dateien. + +Gemessener maximaler Prozess-RSS über die Phasen: vorher 93.7 MiB, nachher 76.4 MiB. Ceph-Daemons, CLI-Kinder und Anwendungsclient sind darin nicht enthalten. + +Die alte Version zeigte beim Erstlauf MDS-Lesesperren-Wartezeiten. Andere Vorläufe lagen dort bei etwa 99 s. Die große Differenz des Erstlaufs ist deshalb kein allgemeines Beschleunigungsversprechen. Der über Nacht unterbrochene Vergleich sowie dessen Wiederanlauf sind nicht als Vergleichsmessung enthalten. + +## Abgeschlossener Test mit 10.000 Dateien, vor Optimierung + +| Phase | Dauer | Geschriebene Nutzdaten | +|---|---:|---:| +| Erstlauf, zwei Stände | 554.4 s | 1.280.000 Byte | +| Änderungsabgleich | 459.3 s | 64.128 Byte | +| Finaler Abgleich | 84.1 s | 0 Byte | + +Der unabhängige Anwendungsclient verglich live und in vier historischen Ständen insgesamt 50.500 reguläre Dateipfade einschließlich Hardlinks, zusätzlich Symlinks und Metadaten. Alle Prüfungen waren erfolgreich. Diese zusätzliche Testprüfung dauert 600,7 s und gehört nicht zur gemessenen Dauer von `finalize`. Remount und Anwendungsneustart sind ebenfalls nicht enthalten. + +Der Kopierer erreichte 135.4 MiB Prozess-RSS. Journal und Index belegten am Ende 1.59 MiB. Ceph meldete vor der Bereinigung etwa 271.2 MiB zusätzliche Rohbelegung an der Quelle und 726.6 MiB am Ziel. Diese Werte enthalten auch internen Verwaltungsaufwand, Journal- und BlueFS/RocksDB-Wachstum. + +## Umgesetzte Änderungen + +- Vollständiges lokales Pfadinventar des unveränderlichen Quellsnapshots für Aufräumen und Überhangprüfung; erneute Quell-`stat`-Abfragen je Zielpfad entfallen. Unvollständige Inventare verhindern das Aufräumen. +- Keine erneuten Index-Schreibtransaktionen für identische Inode-Zeilen. +- Keine erneuten `setattr`-Aufrufe für bereits gleiche Besitzer, Rechte und mtime; Zielstatistik wird bei der Prüfung wiederverwendet. +- Datenpuffer passend zur Dateigröße bzw. Prüflänge, höchstens 4 MiB je Puffer. +- `AT_STATX_DONT_SYNC` nur für unveränderliche Snapshotpfade; Live-Zielpfade behalten normale Synchronisationssemantik. Cephs eigener [Mirror verwendet denselben Snapshot-Zugriff](https://github.com/ceph/ceph/blob/main/src/tools/cephfs_mirror/PeerReplayer.cc). + +## Grenzen und Reproduktion + +MDS-Anfragen sind keine physisch gemessenen Datenträger-IOPS. Die Läufe sind einzelne Messungen auf einem gemeinsam genutzten Host, ohne zugesicherte Cache-Bedingungen. Es bleiben vollständige Metadatendurchläufe; für 200 Millionen Dateien ist weiterhin ein Änderungsplan nötig, der unveränderte Teilbäume überspringt. Die Ergebnisse sind keine Freigabe für diese Größenordnung. + +```sh +make dev-smallfiles-test +# kleinerer Test mit MDS-Zählern: +FILES=2000 REPORT_DIR=/tmp/cephmig-smallfiles-report make dev-smallfiles-test +``` + +Die Testprogramme bereinigen bei Erfolg ihre eigenen Subvolumes, Snapshots, Claims und lokalen Zustandsdateien. Ceph kann freigewordenen Platz verzögert zurückmelden. Rohdaten, Binär-Hashes und Details stehen in [smallfiles-local.json](smallfiles-local.json). + +Zusätzlich bestanden die Go-Tests mit Race Detector und `go vet` für den nativen Build sowie der vollständige native Funktionstest mit großen/Sparse-Dateien, Blockdiff, historischen Snapshots, ACLs, Quotas, Hardlinks auf Symlinks/FIFOs, Abbruch und SIGKILL-Wiederaufnahme. Die erfolgreichen Test-Fixtures wurden entfernt. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a064a2f --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module CephMig + +go 1.25.0 + +require go.etcd.io/bbolt v1.5.0 + +require golang.org/x/sys v0.45.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5478636 --- /dev/null +++ b/go.sum @@ -0,0 +1,14 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU= +go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/cephfsnative/client_ceph.go b/internal/cephfsnative/client_ceph.go new file mode 100644 index 0000000..334ca03 --- /dev/null +++ b/internal/cephfsnative/client_ceph.go @@ -0,0 +1,447 @@ +//go:build ceph && cgo + +// Package cephfsnative provides a small binding to the installed libcephfs ABI. +// Client handles are userspace connections, not operating-system/FUSE mounts. +package cephfsnative + +/* +#cgo CFLAGS: -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE +#cgo LDFLAGS: -lcephfs +#include +#include +#include +#include +#include +#include + +static int cm_stat(struct ceph_mount_info *m, const char *p, struct ceph_statx *s,int flags) { + return ceph_statx(m,p,s,CEPH_STATX_BASIC_STATS|CEPH_STATX_VERSION,flags); +} +static int cm_attr(struct ceph_mount_info *m,const char *p,unsigned mode,unsigned uid, + unsigned gid,long sec,long nsec) { + struct ceph_statx s = {0}; + s.stx_mode=mode; s.stx_uid=uid; s.stx_gid=gid; + s.stx_mtime.tv_sec=sec; s.stx_mtime.tv_nsec=nsec; + int mask=CEPH_SETATTR_UID|CEPH_SETATTR_GID|CEPH_SETATTR_MTIME; + if ((mode&S_IFMT)!=S_IFLNK) mask|=CEPH_SETATTR_MODE; + return ceph_setattrx(m,p,&s,mask,AT_SYMLINK_NOFOLLOW); +} + +// ceph_link resolves a symbolic-link source. Use inode-based linking so the +// link itself, including a dangling symlink, is shared instead of its referent. +static int cm_link_nofollow(struct ceph_mount_info *m,const char *oldpath, + const char *newparent,const char *name) { + const UserPerm *perms=ceph_mount_perms(m); + Inode *in=NULL,*parent=NULL; + struct ceph_statx s={0}; + int ret=ceph_ll_walk(m,oldpath,&in,&s,CEPH_STATX_BASIC_STATS,AT_SYMLINK_NOFOLLOW,perms); + if (ret<0) return ret; + ret=ceph_ll_walk(m,newparent,&parent,&s,CEPH_STATX_BASIC_STATS,0,perms); + if (ret==0) ret=ceph_ll_link(m,in,parent,name,perms); + if (parent) ceph_ll_put(m,parent); + ceph_ll_put(m,in); + return ret; +} +*/ +import "C" + +import ( + "errors" + "fmt" + "io" + "path" + "strings" + "syscall" + "time" + "unsafe" + + "CephMig/internal/storage" +) + +type Client struct{ mount *C.struct_ceph_mount_info } + +func errno(ret C.int) error { + if ret < 0 { + return syscall.Errno(-ret) + } + return nil +} +func str(s string) (*C.char, func()) { + p := C.CString(s) + return p, func() { C.free(unsafe.Pointer(p)) } +} +func Open(o storage.Options) (*Client, error) { + c := &Client{} + user := strings.TrimPrefix(o.User, "client.") + if user == "" { + user = "admin" + } + id, free := str(user) + defer free() + if err := errno(C.ceph_create(&c.mount, id)); err != nil { + return nil, err + } + failed := true + defer func() { + if failed { + c.Close() + } + }() + conf, release := str(o.Config) + defer release() + if err := errno(C.ceph_conf_read_file(c.mount, conf)); err != nil { + return nil, err + } + settings := map[string]string{"keyring": o.Keyring, "client_mount_timeout": "30", + "client_acl_type": "posix_acl", "client_oc": "false"} + for k, v := range settings { + key, fk := str(k) + value, fv := str(v) + ret := C.ceph_conf_set(c.mount, key, value) + fk() + fv() + if err := errno(ret); err != nil { + return nil, fmt.Errorf("Ceph option %s: %w", k, err) + } + } + fs, ff := str(o.Filesystem) + defer ff() + if err := errno(C.ceph_select_filesystem(c.mount, fs)); err != nil { + return nil, err + } + root, fr := str("/") + defer fr() + if err := errno(C.ceph_mount(c.mount, root)); err != nil { + return nil, err + } + failed = false + return c, nil +} +func (c *Client) Close() error { + if c.mount != nil { + C.ceph_shutdown(c.mount) + c.mount = nil + } + return nil +} +func node(s C.struct_ceph_statx) storage.Node { + return storage.Node{Mode: uint32(s.stx_mode), Inode: uint64(s.stx_ino), + Version: uint64(s.stx_version), Nlink: uint64(s.stx_nlink), Size: uint64(s.stx_size), + Rdev: uint64(s.stx_rdev), UID: uint32(s.stx_uid), GID: uint32(s.stx_gid), + Mtime: time.Unix(int64(s.stx_mtime.tv_sec), int64(s.stx_mtime.tv_nsec))} +} +func (c *Client) Stat(path string) (storage.Node, error) { + p, f := str(path) + defer f() + var s C.struct_ceph_statx + err := errno(C.cm_stat(c.mount, p, &s, nativeStatFlags(path))) + return node(s), err +} + +func nativeStatFlags(path string) C.int { + flags := C.int(C.AT_SYMLINK_NOFOLLOW) + // Snapshot inodes are immutable and separately cached by snapshot ID. As in + // cephfs-mirror, avoid acquiring all shared metadata locks again for them. + // Live target paths retain normal synchronization semantics. + if strings.Contains(path, "/.snap/") { + flags |= C.AT_STATX_DONT_SYNC + } + return flags +} +func (c *Client) Open(path string, flags int, mode uint32) (storage.File, error) { + p, f := str(path) + defer f() + ret := C.ceph_open(c.mount, p, C.int(flags), C.mode_t(mode)) + if err := errno(ret); err != nil { + return nil, err + } + return &file{client: c, fd: ret}, nil +} + +type file struct { + client *Client + fd C.int + closed bool +} + +func (f *file) Close() error { + if f.closed { + return nil + } + f.closed = true + return errno(C.ceph_close(f.client.mount, f.fd)) +} +func (f *file) ReadAt(b []byte, off int64) (int, error) { + if len(b) == 0 { + return 0, nil + } + n := C.ceph_read(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off)) + if err := errno(n); err != nil { + return 0, err + } + if int(n) < len(b) { + return int(n), io.EOF + } + return int(n), nil +} +func (f *file) WriteAt(b []byte, off int64) (int, error) { + if len(b) == 0 { + return 0, nil + } + n := C.ceph_write(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off)) + if err := errno(n); err != nil { + return 0, err + } + if int(n) != len(b) { + return int(n), io.ErrShortWrite + } + return int(n), nil +} +func (f *file) Truncate(n int64) error { + return errno(C.ceph_ftruncate(f.client.mount, f.fd, C.int64_t(n))) +} +func (f *file) Sync() error { return errno(C.ceph_fsync(f.client.mount, f.fd, 0)) } +func (f *file) Lock(owner uint64) error { + return errno(C.ceph_flock(f.client.mount, f.fd, C.LOCK_EX|C.LOCK_NB, C.uint64_t(owner))) +} +func (f *file) PunchHole(off, length int64) error { + return errno(C.ceph_fallocate(f.client.mount, f.fd, 3, C.int64_t(off), C.int64_t(length))) +} + +type dir struct { + client *Client + handle *C.struct_ceph_dir_result + path string + flags C.int +} + +func (c *Client) OpenDir(path string) (storage.DirectoryStream, error) { + p, f := str(path) + defer f() + d := &dir{client: c, path: path, flags: nativeStatFlags(path)} + if err := errno(C.ceph_opendir(c.mount, p, &d.handle)); err != nil { + return nil, err + } + return d, nil +} +func (d *dir) Next() (*storage.Entry, error) { + for { + var entry C.struct_dirent + var s C.struct_ceph_statx + ret := C.ceph_readdirplus_r(d.client.mount, d.handle, &entry, &s, + C.CEPH_STATX_BASIC_STATS|C.CEPH_STATX_VERSION, C.uint(d.flags), nil) + if err := errno(ret); err != nil { + return nil, err + } + if ret == 0 { + return nil, io.EOF + } + name := C.GoString(&entry.d_name[0]) + if name == "." || name == ".." || name == ".snap" { + continue + } + return &storage.Entry{Name: name, Node: node(s)}, nil + } +} +func (d *dir) Close() error { return errno(C.ceph_closedir(d.client.mount, d.handle)) } +func (c *Client) Mkdir(path string, mode uint32) error { + p, f := str(path) + defer f() + return errno(C.ceph_mkdir(c.mount, p, C.mode_t(mode))) +} +func (c *Client) Unlink(path string) error { + p, f := str(path) + defer f() + return errno(C.ceph_unlink(c.mount, p)) +} +func (c *Client) Rmdir(path string) error { + p, f := str(path) + defer f() + return errno(C.ceph_rmdir(c.mount, p)) +} +func (c *Client) Rename(a, b string) error { + p, f := str(a) + defer f() + q, g := str(b) + defer g() + return errno(C.ceph_rename(c.mount, p, q)) +} +func (c *Client) Link(a, b string) error { + p, f := str(a) + defer f() + q, g := str(path.Dir(b)) + defer g() + name, h := str(path.Base(b)) + defer h() + return errno(C.cm_link_nofollow(c.mount, p, q, name)) +} +func (c *Client) Symlink(a, b string) error { + p, f := str(a) + defer f() + q, g := str(b) + defer g() + return errno(C.ceph_symlink(c.mount, p, q)) +} +func (c *Client) Mknod(path string, mode uint32, dev uint64) error { + p, f := str(path) + defer f() + return errno(C.ceph_mknod(c.mount, p, C.mode_t(mode), C.dev_t(dev))) +} +func (c *Client) Readlink(path string) (string, error) { + p, f := str(path) + defer f() + for size := 256; size <= 1<<20; size *= 2 { + b := make([]byte, size) + n := C.ceph_readlink(c.mount, p, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(size)) + if err := errno(n); err != nil { + return "", err + } + if int(n) < size { + return string(b[:int(n)]), nil + } + } + return "", errors.New("symlink target exceeds 1 MiB") +} +func (c *Client) SetAttr(path string, n storage.Node) error { + p, f := str(path) + defer f() + return errno(C.cm_attr(c.mount, p, C.uint(n.Mode), C.uint(n.UID), C.uint(n.GID), C.long(n.Mtime.Unix()), C.long(n.Mtime.Nanosecond()))) +} +func (c *Client) GetXattr(path, key string) ([]byte, error) { + p, f := str(path) + defer f() + k, g := str(key) + defer g() + for size := 256; size <= 1<<20; size *= 2 { + b := make([]byte, size) + ret := C.ceph_lgetxattr(c.mount, p, k, unsafe.Pointer(&b[0]), C.size_t(size)) + if ret == -C.ERANGE { + continue + } + if err := errno(ret); err != nil { + return nil, err + } + return b[:int(ret)], nil + } + return nil, errors.New("xattr exceeds 1 MiB") +} +func (c *Client) ListXattr(path string) ([]string, error) { + p, f := str(path) + defer f() + for size := 4096; size <= 1<<20; size *= 2 { + b := make([]byte, size) + ret := C.ceph_llistxattr(c.mount, p, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(size)) + if ret == -C.ERANGE { + continue + } + if err := errno(ret); err != nil { + return nil, err + } + var names []string + for _, s := range strings.Split(string(b[:int(ret)]), "\x00") { + if s != "" { + names = append(names, s) + } + } + return names, nil + } + return nil, errors.New("xattr list exceeds 1 MiB") +} +func (c *Client) SetXattr(path, key string, b []byte) error { + p, f := str(path) + defer f() + k, g := str(key) + defer g() + var ptr unsafe.Pointer + if len(b) > 0 { + ptr = unsafe.Pointer(&b[0]) + } + return errno(C.ceph_lsetxattr(c.mount, p, k, ptr, C.size_t(len(b)), 0)) +} +func (c *Client) RemoveXattr(path, key string) error { + p, f := str(path) + defer f() + k, g := str(key) + defer g() + return errno(C.ceph_lremovexattr(c.mount, p, k)) +} +func (c *Client) Sync() error { return errno(C.ceph_sync_fs(c.mount)) } + +type snapDiff struct{ info C.struct_ceph_snapdiff_info } + +func (c *Client) SnapDiff(root, rel, a, b string) (storage.DiffStream, error) { + p, f := str(root) + defer f() + q, g := str(rel) + defer g() + x, h := str(a) + defer h() + y, j := str(b) + defer j() + s := &snapDiff{} + if err := errno(C.ceph_open_snapdiff(c.mount, p, q, x, y, &s.info)); err != nil { + return nil, err + } + return s, nil +} +func (s *snapDiff) Next() (string, error) { + for { + var entry C.struct_ceph_snapdiff_entry_t + ret := C.ceph_readdir_snapdiff(&s.info, &entry) + if err := errno(ret); err != nil { + return "", err + } + if ret == 0 { + return "", io.EOF + } + name := C.GoString(&entry.dir_entry.d_name[0]) + if name == "." || name == ".." || name == ".snap" { + continue + } + return name, nil + } +} +func (s *snapDiff) Close() error { return errno(C.ceph_close_snapdiff(&s.info)) } + +type blockDiff struct { + info C.struct_ceph_file_blockdiff_info + done bool +} + +func (c *Client) BlockDiff(root, rel, a, b string) (storage.BlockStream, error) { + p, f := str(root) + defer f() + q, g := str(rel) + defer g() + x, h := str(a) + defer h() + y, j := str(b) + defer j() + s := &blockDiff{} + if err := errno(C.ceph_file_blockdiff_init(c.mount, p, q, x, y, &s.info)); err != nil { + return nil, err + } + return s, nil +} +func (s *blockDiff) Next() ([]storage.Extent, error) { + if s.done { + return nil, io.EOF + } + var blocks C.struct_ceph_file_blockdiff_changedblocks + ret := C.ceph_file_blockdiff(&s.info, &blocks) + if err := errno(ret); err != nil { + return nil, err + } + defer C.ceph_free_file_blockdiff_buffer(&blocks) + s.done = ret == 0 + if uint64(blocks.num_blocks) > 1<<20 { + return nil, errors.New("blockdiff batch exceeds supported bound") + } + cblocks := unsafe.Slice(blocks.b, int(blocks.num_blocks)) + out := make([]storage.Extent, len(cblocks)) + for i, b := range cblocks { + out[i] = storage.Extent{Offset: uint64(b.offset), Length: uint64(b.len)} + } + return out, nil +} +func (s *blockDiff) Close() error { return errno(C.ceph_file_blockdiff_finish(&s.info)) } diff --git a/internal/migration/access.go b/internal/migration/access.go new file mode 100644 index 0000000..48ca5c2 --- /dev/null +++ b/internal/migration/access.go @@ -0,0 +1,94 @@ +package migration + +import ( + "context" + "fmt" + "io" + "path" + "strings" +) + +func nativePath(p string) (string, error) { + if !strings.HasPrefix(p, "/") || path.Clean(p) != p || p == "/" { + return "", fmt.Errorf("invalid Ceph data path %q", p) + } + return p, nil +} + +// Access separates filesystem access from the shared snapshot/journal workflow. +type Access interface { + Inspect(context.Context, Config, Executor) (*Inspection, error) + Empty(context.Context, string) error + Claim(context.Context, Config, string, string) (io.Closer, error) + Prepare(context.Context, string, string, string) error + Apply(context.Context, string, string) error + Verify(context.Context, string, 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) 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) Inspect(ctx context.Context, c Config) (*Inspection, error) { + return e.access().Inspect(ctx, c, e.Exec) +} + +type Round struct { + SourcePath, TargetPath string + BaseName, BaseSourcePath string + Name, StatePath string +} +type RoundTransport interface { + BeginRound(context.Context, Round) error + Published(string) + Commit(context.Context, string) error + Statistics() TransferStats +} +type TransferStats struct { + Mode string `json:"mode"` + BaseSnapshot string `json:"base_snapshot,omitempty"` + FilesVisited int64 `json:"files_visited"` + FilesCopied int64 `json:"files_copied"` + BytesCopied int64 `json:"bytes_copied"` + BytesVerified int64 `json:"bytes_verified"` + BlockDiffFiles int64 `json:"blockdiff_files"` + SnapDiffEntries int64 `json:"snapdiff_entries"` +} + +// NewEngine never silently falls back from native I/O to mounted/rsync I/O. +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 +} + +type nopCloser struct{} + +func (nopCloser) Close() error { return nil } diff --git a/internal/migration/ceph.go b/internal/migration/ceph.go new file mode 100644 index 0000000..a649eaa --- /dev/null +++ b/internal/migration/ceph.go @@ -0,0 +1,146 @@ +package migration + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" +) + +type ceph struct { + endpoint Endpoint + exec Executor + native bool +} + +func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) { + // A manager operation may wait for MDS capability/session recovery after a + // killed client. Keep a deadline, but allow the normal recovery grace period. + ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + flags := []string{"--conf", c.endpoint.Config, "--keyring", c.endpoint.Keyring} + if c.endpoint.User != "" { + flags = append(flags, "--name", c.endpoint.User) + } + b, err := output(ctx, c.exec, "ceph", append(flags, args...)...) + if err != nil { + // The first three tokens identify the operation; omit names and metadata + // values, which can contain confidential application information. + return nil, fmt.Errorf("Ceph %s: %w", strings.Join(args[:min(3, len(args))], " "), err) + } + return b, nil +} +func (c ceph) sub(ctx context.Context, op string, extra ...string) ([]byte, error) { + args := []string{"fs", "subvolume", op, c.endpoint.Filesystem, c.endpoint.Subvolume} + args = append(args, extra...) + if c.endpoint.Group != "" { + args = append(args, "--group_name", c.endpoint.Group) + } + return c.call(ctx, args...) +} +func (c ceph) snap(ctx context.Context, op, name string, extra ...string) ([]byte, error) { + args := []string{"fs", "subvolume", "snapshot", op, c.endpoint.Filesystem, c.endpoint.Subvolume} + if name != "" { + args = append(args, name) + } + args = append(args, extra...) + if c.endpoint.Group != "" { + args = append(args, "--group_name", c.endpoint.Group) + } + return c.call(ctx, args...) +} +func (c ceph) snapshotPath(ctx context.Context, name string) (string, error) { + b, err := c.snap(ctx, "getpath", name) + if err != nil { + return "", err + } + p := strings.TrimSpace(string(b)) + if c.native { + return nativePath(p) + } + return dataPath(c.endpoint.Mount, p) +} +func (c ceph) names(ctx context.Context) ([]string, error) { + b, err := c.snap(ctx, "ls", "") + if err != nil { + return nil, err + } + var list []struct { + Name string `json:"name"` + } + if err = json.Unmarshal(b, &list); err != nil { + return nil, err + } + names := make([]string, 0, len(list)) + for _, s := range list { + if !validName(s.Name) { + return nil, fmt.Errorf("unsupported snapshot name %q", s.Name) + } + names = append(names, s.Name) + } + return names, nil +} +func (c ceph) metadata(ctx context.Context, snapshot string) (map[string]string, error) { + args := []string{"fs", "subvolume"} + if snapshot != "" { + args = append(args, "snapshot") + } + args = append(args, "metadata", "ls", c.endpoint.Filesystem, c.endpoint.Subvolume) + if snapshot != "" { + args = append(args, snapshot) + } + if c.endpoint.Group != "" { + args = append(args, "--group_name", c.endpoint.Group) + } + b, err := c.call(ctx, args...) + if err != nil { + return nil, err + } + var m map[string]string + err = json.Unmarshal(b, &m) + return m, err +} +func (c ceph) setMetadata(ctx context.Context, snapshot string, m map[string]string) error { + // Remove obsolete keys too, including keys removed during a catch-up round. + old, err := c.metadata(ctx, snapshot) + if err != nil { + return err + } + for k := range old { + if _, exists := m[k]; exists { + continue + } + if err := c.metadataCommand(ctx, snapshot, "rm", k, ""); err != nil { + return err + } + } + for k, v := range m { + if ov, ok := old[k]; ok && ov == v { + continue + } + if err := c.metadataCommand(ctx, snapshot, "set", k, v); err != nil { + return err + } + } + return nil +} +func (c ceph) metadataCommand(ctx context.Context, snapshot, op, key, value string) error { + args := []string{"fs", "subvolume"} + if snapshot != "" { + args = append(args, "snapshot") + } + args = append(args, "metadata", op, c.endpoint.Filesystem, c.endpoint.Subvolume) + if snapshot != "" { + args = append(args, snapshot) + } + args = append(args, "--key_name="+key) + if op == "set" { + args = append(args, "--value="+value) + } + if c.endpoint.Group != "" { + args = append(args, "--group_name", c.endpoint.Group) + } + _, err := c.call(ctx, args...) + return err +} diff --git a/internal/migration/config.go b/internal/migration/config.go new file mode 100644 index 0000000..802e93b --- /dev/null +++ b/internal/migration/config.go @@ -0,0 +1,130 @@ +package migration + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +type Endpoint struct { + User string `json:"user,omitempty"` + Config string `json:"config"` + Keyring string `json:"keyring"` + Filesystem string `json:"filesystem"` + Group string `json:"group"` + Subvolume string `json:"subvolume"` + Mount string `json:"mount,omitempty"` +} + +type Config struct { + Backend string `json:"backend,omitempty"` + Workers int `json:"workers,omitempty"` + Source Endpoint `json:"source"` + Target Endpoint `json:"target"` + BandwidthKiB int64 `json:"bandwidth_kib,omitempty"` +} + +func ReadConfig(path string) (Config, error) { + var c Config + f, err := os.Open(path) + if err != nil { + return c, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return c, err + } + if !st.Mode().IsRegular() || st.Size() > 1<<20 { + return c, errors.New("config must be a regular file of at most 1 MiB") + } + dec := json.NewDecoder(io.LimitReader(f, 1<<20)) + dec.DisallowUnknownFields() + if err = dec.Decode(&c); err != nil { + return c, fmt.Errorf("config: %w", err) + } + if err = dec.Decode(new(any)); !errors.Is(err, io.EOF) { + return c, errors.New("config must contain exactly one JSON object") + } + return c, c.Validate() +} + +func validName(s string) bool { + return s != "" && s != "." && s != ".." && !strings.HasPrefix(s, "-") && + !strings.ContainsAny(s, "/\x00\n\r") +} + +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.Workers < 0 || c.Workers > 64 { + return errors.New("workers must be between 0 and 64 (0 selects the default)") + } + for _, p := range []struct { + name string + e Endpoint + }{{"source", c.Source}, {"target", c.Target}} { + if p.e.User != "" && (!strings.HasPrefix(p.e.User, "client.") || !validName(p.e.User)) { + return fmt.Errorf("%s: user must be a client identity", p.name) + } + for _, s := range []string{p.e.Filesystem, p.e.Subvolume} { + if !validName(s) { + return fmt.Errorf("%s: invalid filesystem or subvolume name", p.name) + } + } + if p.e.Group != "" && !validName(p.e.Group) { + 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 { + if !filepath.IsAbs(path) || filepath.Clean(path) != path { + return fmt.Errorf("%s: paths must be absolute and clean: %q", p.name, path) + } + } + } + if c.BandwidthKiB < 0 || c.BandwidthKiB > (1<<63-1)/1024 { + 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) } + +// Resolve only real directories below the configured filesystem mount. 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 new file mode 100644 index 0000000..04c2d36 --- /dev/null +++ b/internal/migration/config_test.go @@ -0,0 +1,100 @@ +package migration + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +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"}} +} +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" }, + "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 }, + "overflow-rate": func(c *Config) { c.BandwidthKiB = 1 << 62 }, + "bad-backend": func(c *Config) { c.Backend = "raw" }, + "bad-workers": func(c *Config) { c.Workers = 65 }, + "invalid-user": func(c *Config) { c.Source.User = "osd.0" }, + } { + t.Run(name, func(t *testing.T) { + c := testConfig() + modify(&c) + if c.Validate() == nil { + t.Fatal("accepted invalid config") + } + }) + } + if err := testConfig().Validate(); err != nil { + t.Fatal(err) + } +} + +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) + } + changed := c + changed.Workers, changed.BandwidthKiB = 32, 100000 + if !sameMigrationIdentity(c, changed) { + t.Fatal("runtime settings invalidated resume identity") + } + changed.Target.Subvolume = "another" + if sameMigrationIdentity(c, changed) { + t.Fatal("accepted a different target") + } +} +func TestStrictJSONConfig(t *testing.T) { + b, _ := json.Marshal(testConfig()) + for name, data := range map[string]string{"unknown": strings.TrimSuffix(string(b), "}") + ", \"typo\": true}", "trailing": string(b) + " {}", "truncated": string(b[:len(b)-2])} { + t.Run(name, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(p, []byte(data), 0600); err != nil { + t.Fatal(err) + } + if _, err := ReadConfig(p); err == nil { + t.Fatal("accepted invalid JSON config") + } + }) + } +} +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 { + t.Fatal(err) + } + if err := privateDirectories(filepath.Join(root, "link", "new")); err == nil { + t.Fatal("followed symlink") + } + if _, err := os.Stat(filepath.Join(outside, "new")); !os.IsNotExist(err) { + t.Fatal("created directory through symlink") + } +} diff --git a/internal/migration/engine.go b/internal/migration/engine.go new file mode 100644 index 0000000..eba94f0 --- /dev/null +++ b/internal/migration/engine.go @@ -0,0 +1,591 @@ +package migration + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "syscall" + "time" +) + +type Engine struct { + Exec Executor + Transport Transport + Log io.Writer + Access Access +} + +type endpointInfo struct { + Path string `json:"path"` + State string `json:"state"` + BytesUsed uint64 `json:"bytes_used"` + CaseSensitive bool `json:"casesensitive"` + Normalization string `json:"normalization"` + Encryption string `json:"enctag"` + Earmark string `json:"earmark"` +} +type Inspection struct { + SourceFSID string `json:"source_fsid"` + TargetFSID string `json:"target_fsid"` + SourcePath string `json:"source_path"` + TargetPath string `json:"target_path"` + SourceBytes uint64 `json:"source_bytes"` + SourceSnapshots []string `json:"source_snapshots"` + NativeSnapshotIdentityPreserved bool `json:"native_snapshot_identity_preserved"` + Notes []string `json:"notes"` +} + +const SnapshotIdentityNote = "Native snapshot IDs and Ceph birthtimes are recreated at the target; original creation timestamps are recorded in the migration journal." + +func (e Engine) log(format string, args ...any) { + if e.Log != nil { + fmt.Fprintf(e.Log, format+"\n", args...) + } +} + +func queryEndpoint(ctx context.Context, c ceph) (string, endpointInfo, error) { + var info endpointInfo + b, err := c.call(ctx, "fsid") + if err != nil { + return "", info, err + } + fsid := strings.TrimSpace(string(b)) + if len(fsid) != 36 { + return "", info, errors.New("invalid cluster FSID") + } + b, err = c.sub(ctx, "info") + if err != nil { + return "", info, err + } + if err = json.Unmarshal(b, &info); err != nil { + return "", info, err + } + if info.State != "complete" || !info.CaseSensitive || info.Normalization != "none" || info.Encryption != "" || info.Earmark != "" { + return "", info, errors.New("subvolume must be complete, case-sensitive, unencrypted, without normalization or earmark") + } + 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 { + return "", err + } + 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 +} + +// 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) { + key := sha256.Sum256([]byte(fsid + "\x00" + ep.Filesystem + "\x00" + ep.Group + "\x00" + ep.Subvolume)) + 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, hex.EncodeToString(key[:])) + 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 + b, err := src.snap(ctx, "info", name) + if err != nil { + return s, err + } + var info struct { + CreatedAt string `json:"created_at"` + } + if err = json.Unmarshal(b, &info); err != nil { + return s, err + } + if _, err = time.Parse("2006-01-02 15:04:05.999999999", info.CreatedAt); err != nil { + return s, fmt.Errorf("invalid creation time for %s: %w", name, err) + } + s.CreatedAt = info.CreatedAt + s.Metadata, err = src.metadata(ctx, name) + return s, err +} + +func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool) error { + if err := c.Validate(); err != nil { + return err + } + e.log("note: %s", SnapshotIdentityNote) + if os.Geteuid() != 0 { + 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") + } + abs, err := filepath.Abs(statePath) + if err != nil { + 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 + } + resolved, err := filepath.EvalSymlinks(filepath.Dir(abs)) + if err != nil || resolved != filepath.Dir(abs) { + return errors.New("state directory must not contain symlinks") + } + lock, err := lockFile(abs + ".lock") + if err != nil { + return err + } + defer lock.Close() + inspection, err := e.Inspect(ctx, c) + if err != nil { + 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"} + s, err := LoadState(abs) + if errors.Is(err, os.ErrNotExist) { + if err = e.access().Empty(ctx, inspection.TargetPath); err != nil { + return err + } + names, err := dst.names(ctx) + if err != nil { + return err + } + if len(names) != 0 { + return errors.New("new migration requires a target without snapshots") + } + metadata, err := dst.metadata(ctx, "") + if err != nil { + return err + } + if len(metadata) != 0 { + return errors.New("new migration requires a target without custom metadata") + } + id, err := newID() + if err != nil { + return err + } + s = &State{ + Version: stateVersion, ID: id, Config: c, + SourceFSID: inspection.SourceFSID, TargetFSID: inspection.TargetFSID, + SourcePath: inspection.SourcePath, TargetPath: inspection.TargetPath, + Phase: "syncing", Notes: []string{SnapshotIdentityNote}, + } + if err = SaveState(abs, s); err != nil { + return err + } + } else if err != nil { + return err + } + if !sameMigrationIdentity(s.Config, c) || s.SourceFSID != inspection.SourceFSID || s.TargetFSID != inspection.TargetFSID || s.SourcePath != inspection.SourcePath || s.TargetPath != inspection.TargetPath { + return errors.New("config or cluster identity changed; refusing to reuse migration state") + } + claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID) + if err != nil { + return err + } + defer claim.Close() + s.Config = c + if !contains(s.Notes, SnapshotIdentityNote) { + s.Notes = append(s.Notes, SnapshotIdentityNote) + if err = SaveState(abs, s); err != nil { + return err + } + } + if s.Phase == "ready-for-cutover" { + if !final { + return errors.New("job is ready for cutover; sync is no longer allowed") + } + e.log("already ready for cutover; no new source snapshot created") + return nil + } + if s.Phase != "syncing" { + return fmt.Errorf("unsupported job phase %q", s.Phase) + } + known := make(map[string]bool, len(s.Snapshots)) + finalPending := false + for _, snap := range s.Snapshots { + known[snap.Name] = true + if snap.Final { + finalPending = true + } + } + if finalPending && !final { + return errors.New("a final round is pending; resume using finalize while writers remain stopped") + } + targetNames, err := dst.names(ctx) + if err != nil { + return err + } + for _, name := range targetNames { + if !known[name] { + return fmt.Errorf("unowned target snapshot %q; refusing to overwrite target", name) + } + } + // Discover newly created application snapshots on every invocation. + var discovered []Snapshot + for _, name := range inspection.SourceSnapshots { + if known[name] { + continue + } + snap, err := snapshotDetails(ctx, src, name) + if err != nil { + return err + } + discovered = append(discovered, snap) + } + sort.Slice(discovered, func(i, j int) bool { + if discovered[i].CreatedAt == discovered[j].CreatedAt { + return discovered[i].Name < discovered[j].Name + } + return discovered[i].CreatedAt < discovered[j].CreatedAt + }) + s.Snapshots = append(s.Snapshots, discovered...) + if err = SaveState(abs, s); err != nil { + return err + } + // Resume all intent records before capturing another live snapshot. + for i := range s.Snapshots { + if s.Snapshots[i].Done { + snap := &s.Snapshots[i] + if !contains(targetNames, snap.Name) { + return fmt.Errorf("completed target snapshot %q disappeared", snap.Name) + } + info, err := snapshotDetails(ctx, dst, snap.Name) + if err != nil { + return err + } + if info.CreatedAt != snap.TargetCreatedAt { + return fmt.Errorf("completed target snapshot %q was replaced", snap.Name) + } + if contains(inspection.SourceSnapshots, snap.Name) { + info, err = snapshotDetails(ctx, src, snap.Name) + if err != nil { + return err + } + if info.CreatedAt != snap.CreatedAt { + return fmt.Errorf("completed source snapshot %q was replaced", snap.Name) + } + if err = dst.setMetadata(ctx, snap.Name, info.Metadata); err != nil { + return err + } + snap.Metadata = info.Metadata + } + continue + } + if err := e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, i); err != nil { + return err + } + } + id, err := newID() + if err != nil { + return err + } + s.Snapshots = append(s.Snapshots, Snapshot{Name: "cephmig-" + s.ID[:12] + "-" + id[:12], Owned: true, Final: final}) + if err = SaveState(abs, s); err != nil { + return err + } + if err = e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, len(s.Snapshots)-1); err != nil { + return err + } + metadata, err := src.metadata(ctx, "") + if err != nil { + return err + } + if err = dst.setMetadata(ctx, "", metadata); err != nil { + return err + } + if final { + // Every source snapshot visible at finalization must have a completed record. + names, err := src.names(ctx) + if err != nil { + return err + } + completed := map[string]bool{} + for _, snap := range s.Snapshots { + if snap.Done { + completed[snap.Name] = true + } + } + for _, name := range names { + if !completed[name] { + return fmt.Errorf("source snapshot inventory changed during finalization (%s); retry finalize", name) + } + } + last := s.Snapshots[len(s.Snapshots)-1] + if !last.Final { + return errors.New("final snapshot is not the last transferred snapshot; retry requires operator review") + } + path, err := src.snapshotPath(ctx, last.Name) + if err != nil { + return err + } + if err = e.Transport.Verify(ctx, path, inspection.TargetPath); err != nil { + return err + } + if err = e.access().Verify(ctx, path, inspection.TargetPath, filepath.Dir(abs)); err != nil { + return err + } + s.Phase = "ready-for-cutover" + } + if err = SaveState(abs, s); err != nil { + return err + } + e.log("phase=%s snapshots=%d state=%s", s.Phase, len(s.Snapshots), abs) + return nil +} +func sameMigrationIdentity(a, b Config) bool { + a.Workers, b.Workers = 0, 0 + a.BandwidthKiB, b.BandwidthKiB = 0, 0 + return reflect.DeepEqual(a, b) +} + +func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath string, s *State, index int) error { + snap := &s.Snapshots[index] + e.log("snapshot=%s: resolving immutable source", snap.Name) + names, err := src.names(ctx) + if err != nil { + return err + } + if !contains(names, snap.Name) { + if !snap.Owned || snap.CreatedAt != "" { + return fmt.Errorf("source snapshot %q disappeared before transfer", snap.Name) + } + if _, err = src.snap(ctx, "create", snap.Name); err != nil { + return err + } + } + details, err := snapshotDetails(ctx, src, snap.Name) + if err != nil { + return err + } + if snap.CreatedAt != "" && snap.CreatedAt != details.CreatedAt { + return fmt.Errorf("source snapshot %q was replaced", snap.Name) + } + snap.CreatedAt, snap.Metadata = details.CreatedAt, details.Metadata + if err = SaveState(statePath, s); err != nil { + return err + } + from, err := src.snapshotPath(ctx, snap.Name) + if err != nil { + return err + } + targetNames, err := dst.names(ctx) + if err != nil { + return err + } + aware, isNative := e.Transport.(RoundTransport) + existed := contains(targetNames, snap.Name) + if isNative { + round := Round{SourcePath: from, TargetPath: target, Name: snap.Name, StatePath: statePath, BaseName: s.LiveSnapshot} + if s.LiveSnapshot != "" { + round.BaseSourcePath, err = src.snapshotPath(ctx, s.LiveSnapshot) + if err != nil { + return err + } + } + if err = aware.BeginRound(ctx, round); err != nil { + return err + } + } + created := false + if !existed || isNative { + // Clearing this durable marker before any target mutation makes interrupted + // rounds fall back to full reconstruction rather than trusting a partial base. + s.LiveSnapshot = "" + if err = SaveState(statePath, s); err != nil { + return err + } + e.log("snapshot=%s: copying", snap.Name) + if err = e.access().Prepare(ctx, from, target, filepath.Dir(statePath)); err != nil { + return err + } + if err = e.Transport.Copy(ctx, from, target); err != nil { + return err + } + if err = e.access().Apply(ctx, from, target); err != nil { + return err + } + e.log("snapshot=%s: verifying before publication", snap.Name) + if err = e.Transport.Verify(ctx, from, target); err != nil { + return err + } + if err = e.access().Verify(ctx, from, target, filepath.Dir(statePath)); err != nil { + return err + } + if !existed { + if _, err = dst.snap(ctx, "create", snap.Name); err != nil { + return err + } + created = true + } + } + // A crash may have occurred between snapshot creation and the state commit. + // Never trust an existing snapshot solely because its name matches. + to, err := dst.snapshotPath(ctx, snap.Name) + if err != nil { + return err + } + if isNative && created { + aware.Published(to) + } + if err = e.Transport.Verify(ctx, from, to); err != nil { + return err + } + if err = e.access().Verify(ctx, from, to, filepath.Dir(statePath)); err != nil { + return err + } + if err = dst.setMetadata(ctx, snap.Name, snap.Metadata); err != nil { + return err + } + targetInfo, err := snapshotDetails(ctx, dst, snap.Name) + if err != nil { + return err + } + snap.TargetCreatedAt = targetInfo.CreatedAt + if isNative { + if err = aware.Commit(ctx, snap.Name); err != nil { + return err + } + stats := aware.Statistics() + snap.Stats = &stats + } + snap.Done = true + s.LiveSnapshot = snap.Name + if err = SaveState(statePath, s); err != nil { + return err + } + e.log("snapshot=%s: verified and committed", snap.Name) + return nil +} +func contains(names []string, name string) bool { + for _, n := range names { + if n == name { + return true + } + } + return false +} diff --git a/internal/migration/hardlinks.go b/internal/migration/hardlinks.go new file mode 100644 index 0000000..04ad584 --- /dev/null +++ b/internal/migration/hardlinks.go @@ -0,0 +1,185 @@ +package migration + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "syscall" + "time" + + bolt "go.etcd.io/bbolt" +) + +type linkIndex struct { + db *bolt.DB + tx *bolt.Tx + observations int +} + +func openLinkIndex(path string) (*linkIndex, error) { + // Rebuildable scratch data only: never used as a durable migration checkpoint. + db, err := bolt.Open(path, 0600, &bolt.Options{Timeout: time.Second, NoSync: true}) + if err != nil { + return nil, err + } + tx, err := db.Begin(true) + if err != nil { + db.Close() + return nil, err + } + for _, name := range []string{"source", "target"} { + if _, err = tx.CreateBucket([]byte(name)); err != nil { + tx.Rollback() + db.Close() + return nil, err + } + } + return &linkIndex{db: db, tx: tx}, nil +} +func (x *linkIndex) close() error { + if x.tx != nil { + _ = x.tx.Rollback() + } + return x.db.Close() +} +func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) { + b := x.tx.Bucket([]byte(bucket)) + old := b.Get(key[:]) + same := true + if old == nil { + if err := b.Put(key[:], value[:]); err != nil { + return false, err + } + } else { + same = bytes.Equal(old, value[:]) + } + x.observations++ + // Limit dirty transaction state; the complete relation stays on disk. + if x.observations%4096 == 0 { + err := x.tx.Commit() + x.tx = nil + if err != nil { + return false, err + } + x.tx, err = x.db.Begin(true) + if err != nil { + return false, err + } + } + 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 +} + +// In repair mode remove 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 new file mode 100644 index 0000000..59e31ef --- /dev/null +++ b/internal/migration/hardlinks_test.go @@ -0,0 +1,143 @@ +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 { + t.Fatal(err) + } + defer x.close() + for i := uint64(0); i < 5000; i++ { + var key, value [16]byte + binary.BigEndian.PutUint64(key[:8], i) + binary.BigEndian.PutUint64(value[:8], i+1) + same, err := x.observe("target", key, value) + if err != nil || !same { + t.Fatalf("insert %d: %v", i, err) + } + } + var key, value [16]byte + binary.BigEndian.PutUint64(value[:8], 1) + if same, err := x.observe("target", key, value); err != nil || !same { + t.Fatalf("committed entry lost: %v", err) + } + value[15] = 1 + if same, err := x.observe("target", key, value); err != nil || same { + t.Fatalf("conflict missed: %v", err) + } +} diff --git a/internal/migration/linux.go b/internal/migration/linux.go new file mode 100644 index 0000000..c9094d2 --- /dev/null +++ b/internal/migration/linux.go @@ -0,0 +1,232 @@ +//go:build linux + +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") + } + current := "/" + for _, component := range strings.Split(strings.TrimPrefix(filepath.Clean(path), "/"), "/") { + if component == "" { + continue + } + current = filepath.Join(current, component) + if err := os.Mkdir(current, 0700); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + st, err := os.Lstat(current) + if err != nil { + return err + } + if !st.IsDir() { + return fmt.Errorf("directory contains a symlink or non-directory: %s", current) + } + } + 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"} + +// ReadDir batches keep a single very large directory from exhausting memory. +func walkDirectories(ctx context.Context, root string, visit func(string) error) error { + return walkTree(ctx, root, visit, nil) +} + +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 new file mode 100644 index 0000000..bf637c0 --- /dev/null +++ b/internal/migration/native_access.go @@ -0,0 +1,173 @@ +package migration + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + "syscall" + + "CephMig/internal/storage" +) + +type nativeAccess struct{ backend *nativeTransport } + +func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspection, error) { + if err := c.Validate(); err != nil { + return nil, err + } + sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x, native: true}) + if err != nil { + return nil, err + } + tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x, native: true}) + if err != nil { + return nil, err + } + if sf == tf { + return nil, errors.New("native source and target must be different clusters") + } + for _, p := range []struct { + fs storage.FS + path, fsid string + }{{a.backend.source, si.Path, sf}, {a.backend.target, ti.Path, tf}} { + if _, err := nativePath(p.path); err != nil { + return nil, err + } + if err := validateNativeDirectory(p.fs, p.path); err != nil { + return nil, err + } + id, err := p.fs.GetXattr(p.path, "ceph.cluster_fsid") + if err != nil { + return nil, err + } + if string(id) != p.fsid { + return nil, errors.New("native connection belongs to the wrong cluster") + } + } + names, err := (ceph{endpoint: c.Source, exec: x, native: true}).names(ctx) + if err != nil { + return nil, err + } + fingerprint := sha256.Sum256([]byte(sf + "\x00" + tf + "\x00" + si.Path + "\x00" + ti.Path)) + a.backend.identity = hex.EncodeToString(fingerprint[:]) + return &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: si.Path, TargetPath: ti.Path, + SourceBytes: si.BytesUsed, SourceSnapshots: names, Notes: []string{SnapshotIdentityNote}}, nil +} +func (a nativeAccess) Empty(ctx context.Context, p string) error { + if err := ctx.Err(); err != nil { + return err + } + d, err := a.backend.target.OpenDir(p) + if err != nil { + return err + } + defer d.Close() + _, err = d.Next() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + return errors.New("new native migration requires an empty target subvolume") +} +func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.Closer, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + fs := a.backend.target + current := "/" + for _, component := range []string{".cephmig", "claims"} { + current = path.Join(current, component) + n, err := fs.Stat(current) + if errors.Is(err, syscall.ENOENT) { + if err = fs.Mkdir(current, 0700); err != nil && !errors.Is(err, syscall.EEXIST) { + return nil, err + } + n, err = fs.Stat(current) + } + if err != nil { + return nil, err + } + if n.Kind() != storage.Directory { + return nil, errors.New("native claim directory contains a symlink or non-directory") + } + } + sum := sha256.Sum256([]byte(fsid + "\x00" + c.Target.Filesystem + "\x00" + c.Target.Group + "\x00" + c.Target.Subvolume)) + p := path.Join(current, hex.EncodeToString(sum[:])) + f, err := fs.Open(p, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600) + if err == nil { + if err = writeNativeAt(f, []byte(id+"\n"), 0); err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil { + err = closeErr + } + if err != nil { + return nil, err + } + } else if !errors.Is(err, syscall.EEXIST) { + return nil, err + } + n, err := fs.Stat(p) + if err != nil { + return nil, err + } + if n.Kind() != storage.Regular { + return nil, errors.New("native target claim is not a regular file") + } + f, err = fs.Open(p, syscall.O_RDWR|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, err + } + if err = f.Lock(1); err != nil { + f.Close() + return nil, fmt.Errorf("native target is locked: %w", err) + } + b := make([]byte, 256) + count, readErr := f.ReadAt(b, 0) + if readErr != nil && !errors.Is(readErr, io.EOF) { + f.Close() + return nil, readErr + } + if string(b[:count]) != id+"\n" { + f.Close() + return nil, errors.New("native target belongs to a different job") + } + return f, nil +} +func (a nativeAccess) Prepare(ctx context.Context, _, target, _ string) error { + return clearNativeQuotas(ctx, a.backend.target, target) +} +func (a nativeAccess) Apply(context.Context, string, string) error { return a.backend.target.Sync() } +func (a nativeAccess) Verify(context.Context, string, string, string) error { return nil } // Transport verifies all native metadata and links. + +type nativeVerifyIndex struct { + index *linkIndex + dir string +} + +func osNativeVerifyIndex(parent string) (*nativeVerifyIndex, error) { + dir, err := os.MkdirTemp(parent, "verify-") + if err != nil { + return nil, err + } + index, err := openLinkIndex(filepath.Join(dir, "links.bolt")) + if err != nil { + os.RemoveAll(dir) + return nil, err + } + return &nativeVerifyIndex{index: index, dir: dir}, nil +} +func (i *nativeVerifyIndex) cleanup() { _ = i.index.close(); _ = os.RemoveAll(i.dir) } +func options(ep Endpoint) storage.Options { + return storage.Options{Config: ep.Config, Keyring: ep.Keyring, User: strings.TrimPrefix(ep.User, "client."), Filesystem: ep.Filesystem} +} diff --git a/internal/migration/native_data.go b/internal/migration/native_data.go new file mode 100644 index 0000000..00b79e1 --- /dev/null +++ b/internal/migration/native_data.go @@ -0,0 +1,432 @@ +package migration + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "path" + "syscall" + "time" + + "CephMig/internal/storage" +) + +func readNativeAt(f storage.File, b []byte, offset int64) error { + n, err := f.ReadAt(b, offset) + if n != len(b) { + if err == nil { + err = io.ErrUnexpectedEOF + } + return err + } + if err != nil && !errors.Is(err, io.EOF) { + return err + } + return nil +} +func writeNativeAt(f storage.File, b []byte, offset int64) error { + n, err := f.WriteAt(b, offset) + if err != nil { + return err + } + if n != len(b) { + return io.ErrShortWrite + } + return nil +} +func allZero(b []byte) bool { + for _, v := range b { + if v != 0 { + return false + } + } + return true +} + +func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error { + if err := ctx.Err(); err != nil { + return err + } + from, to := path.Join(b.round.SourcePath, job.rel), path.Join(b.round.TargetPath, job.rel) + target, statErr := b.target.Stat(to) + if statErr != nil && !errors.Is(statErr, syscall.ENOENT) { + return statErr + } + exists := statErr == nil && target.Kind() == storage.Regular + var previous baseEntry + trusted := false + if b.delta && exists { + var ok bool + var err error + previous, ok, err = b.base.entry(job.rel) + if err != nil { + return err + } + trusted = ok && previous.Inode == job.node.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size + } + changed := true + if trusted && job.node.Version != 0 && job.node.Version == previous.Version && job.node.Size == previous.Size { + changedBytes, err := b.pending.get("changed", nativeInodeKey(job.node.Inode)) + if err != nil { + return err + } + changed = changedBytes != nil + } + if changed { + usedBlockDiff := false + if trusted && job.node.Size >= nativeBlockThreshold { + old, err := b.source.Stat(path.Join(b.round.BaseSourcePath, job.rel)) + if err == nil && old.Kind() == storage.Regular && old.Inode == job.node.Inode { + stream, err := b.source.BlockDiff(b.snapRoot, path.Join(b.snapRel, job.rel), b.round.BaseName, b.round.Name) + if err == nil { + usedBlockDiff = true + if err = b.copyBlocks(ctx, job, stream); err != nil { + return fmt.Errorf("native blockdiff %s: %w", job.rel, err) + } + b.blockFiles.Add(1) + } else if !errors.Is(err, syscall.ENOSYS) && !errors.Is(err, syscall.EOPNOTSUPP) && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.EINVAL) { + return err + } + } else if err != nil && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.ENOTDIR) { + return err + } + } + if !usedBlockDiff { + if err := b.copyFull(ctx, job); err != nil { + return fmt.Errorf("native full copy %s: %w", job.rel, err) + } + if err := b.pending.put("full", []byte(job.rel), []byte{1}); err != nil { + return err + } + } + b.copied.Add(1) + } + if err := syncNativeMetadata(b.source, b.target, from, to, job.node, false); err != nil { + return err + } + current, err := b.target.Stat(to) + if err != nil { + return err + } + return b.pending.put("paths", []byte(job.rel), encodeEntry(baseEntry{Inode: job.node.Inode, Version: job.node.Version, Size: job.node.Size, TargetInode: current.Inode})) +} + +func (b *nativeTransport) copyFull(ctx context.Context, job nativeJob) (result error) { + from, to := path.Join(b.round.SourcePath, job.rel), path.Join(b.round.TargetPath, job.rel) + source, err := b.source.Open(from, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer source.Close() + old, err := b.target.Stat(to) + if err != nil && !errors.Is(err, syscall.ENOENT) { + return err + } + if err == nil && old.Kind() == storage.Directory { + if err = removeNative(ctx, b.target, to); err != nil { + return err + } + } + id, err := newID() + if err != nil { + return err + } + temporary := path.Join(path.Dir(to), ".cephmig-file-"+id) + target, err := b.target.Open(temporary, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600) + if err != nil { + return err + } + defer func() { + if target != nil { + if err := target.Close(); result == nil { + result = err + } + } + if result != nil { + _ = b.target.Unlink(temporary) + } + }() + buffer := make([]byte, min(job.node.Size, uint64(nativeChunk))) + for off := uint64(0); off < job.node.Size; { + if err = ctx.Err(); err != nil { + return err + } + length := min(uint64(len(buffer)), job.node.Size-off) + chunk := buffer[:int(length)] + if err = readNativeAt(source, chunk, int64(off)); err != nil { + return err + } + if !allZero(chunk) { + if err = b.rate(ctx, len(chunk)); err != nil { + return err + } + if err = writeNativeAt(target, chunk, int64(off)); err != nil { + return err + } + b.written.Add(int64(length)) + } + off += length + } + if err = target.Truncate(int64(job.node.Size)); err != nil { + return err + } + if err = target.Sync(); err != nil { + return err + } + if err = target.Close(); err != nil { + return err + } + target = nil + return b.target.Rename(temporary, to) +} +func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks storage.BlockStream) (result error) { + defer func() { + if err := blocks.Close(); result == nil { + result = err + } + }() + source, err := b.source.Open(path.Join(b.round.SourcePath, job.rel), syscall.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer source.Close() + target, err := b.target.Open(path.Join(b.round.TargetPath, job.rel), syscall.O_RDWR|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer func() { + if err := target.Close(); result == nil { + result = err + } + }() + buffer := make([]byte, nativeChunk) + for { + if err = ctx.Err(); err != nil { + return err + } + ranges, err := blocks.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return err + } + for _, extent := range ranges { + if extent.Offset > job.node.Size { + continue + } + length := min(extent.Length, job.node.Size-extent.Offset) + if extent.Length > ^uint64(0)-extent.Offset { + return errors.New("blockdiff extent overflows") + } + for copied := uint64(0); copied < length; { + if err = ctx.Err(); err != nil { + return err + } + count := min(uint64(len(buffer)), length-copied) + chunk := buffer[:int(count)] + off := extent.Offset + copied + if err = readNativeAt(source, chunk, int64(off)); err != nil { + return err + } + punched := false + if allZero(chunk) { + err = target.PunchHole(int64(off), int64(count)) + if err == nil { + punched = true + } else if !errors.Is(err, syscall.EOPNOTSUPP) && !errors.Is(err, syscall.ENOSYS) && !errors.Is(err, syscall.EINVAL) { + return err + } + } + if !punched { + if err = b.rate(ctx, len(chunk)); err != nil { + return err + } + if err = writeNativeAt(target, chunk, int64(off)); err != nil { + return err + } + b.written.Add(int64(count)) + } + if err = b.pending.extent(job.rel, off, count); err != nil { + return err + } + copied += count + } + } + } + if err = target.Truncate(int64(job.node.Size)); err != nil { + return err + } + return target.Sync() +} + +func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { + if b.pending == nil || from != b.round.SourcePath { + return errors.New("native verification round is not initialized") + } + if err := b.pending.requireInventory(); err != nil { + return err + } + skipData := b.verified[to] + scratch, err := osNativeVerifyIndex(b.workspace) + if err != nil { + return err + } + defer scratch.cleanup() + index := scratch.index + lastProgress := time.Now() + var verifiedPaths uint64 + err = walkNative(ctx, b.source, from, func(p string, n storage.Node, _ int) error { + verifiedPaths++ + if b.log != nil && time.Since(lastProgress) >= 30*time.Second { + fmt.Fprintf(b.log, "native verifying paths=%d target=%s\n", verifiedPaths, to) + lastProgress = time.Now() + } + rel, err := relativeNative(from, p) + if err != nil { + return err + } + targetPath := path.Join(to, rel) + target, err := b.target.Stat(targetPath) + if err != nil { + return err + } + if err = syncNativeMetadataKnown(b.source, b.target, p, targetPath, n, target, true); err != nil { + return err + } + if n.Kind() != storage.Directory { + if n.Nlink > 1 { + same, err := index.observe("source", nodeKey(n.Inode), nodeKey(target.Inode)) + if err != nil { + return err + } + if !same { + return fmt.Errorf("native hardlink group was split at %s", rel) + } + } + if target.Nlink > 1 { + same, err := index.observe("target", nodeKey(target.Inode), nodeKey(n.Inode)) + if err != nil { + return err + } + if !same { + return fmt.Errorf("native unrelated files became hardlinked at %s", rel) + } + } + } + switch n.Kind() { + case storage.Directory: + case storage.Regular: + if n.Size != target.Size { + return fmt.Errorf("native size mismatch at %s", targetPath) + } + canonical, err := b.pending.get("groups", nativeInodeKey(n.Inode)) + if err != nil { + return err + } + if !skipData && string(canonical) == rel { + full, err := b.pending.get("full", []byte(rel)) + if err != nil { + return err + } + if full != nil { + if err = b.compareRange(ctx, p, targetPath, 0, n.Size); err != nil { + return err + } + } else { + if err = b.pending.ranges(rel, func(off, length uint64) error { return b.compareRange(ctx, p, targetPath, off, length) }); err != nil { + return err + } + } + } + // Only live target identities may be reused as the next blockdiff base. + if to == b.round.TargetPath && !skipData { + return b.pending.putEntryIfChanged(rel, baseEntry{Inode: n.Inode, Version: n.Version, Size: n.Size, TargetInode: target.Inode}) + } + case storage.Symlink: + a, err := b.source.Readlink(p) + if err != nil { + return err + } + v, err := b.target.Readlink(targetPath) + if err != nil { + return err + } + if a != v { + return fmt.Errorf("native symlink mismatch at %s", rel) + } + default: + if n.Rdev != target.Rdev { + return fmt.Errorf("native device mismatch at %s", rel) + } + } + return nil + }) + if err != nil { + return err + } + if err = b.verifyInventory(ctx, to); err == nil { + b.verified[to] = true + } + return err +} + +func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error { + if err := b.pending.requireInventory(); err != nil { + return err + } + // The source snapshot is immutable. Check the complete local inventory, + // including aliases/directories/special files, rather than stat every source + // path again. Target traversal still detects every unexpected entry. + return walkNative(ctx, b.target, to, func(p string, _ storage.Node, _ int) error { + rel, err := relativeNative(to, p) + if err != nil { + return err + } + present, err := b.pending.containsPath(rel) + if err != nil { + return err + } + if !present { + return fmt.Errorf("unexpected native target entry %s", rel) + } + return nil + }) +} +func (b *nativeTransport) compareRange(ctx context.Context, from, to string, offset, length uint64) error { + if length == 0 { + return nil + } + source, err := b.source.Open(from, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer source.Close() + target, err := b.target.Open(to, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer target.Close() + bufferSize := min(length, uint64(nativeChunk)) + a, v := make([]byte, bufferSize), make([]byte, bufferSize) + for done := uint64(0); done < length; { + if err = ctx.Err(); err != nil { + return err + } + count := min(uint64(len(a)), length-done) + if err = readNativeAt(source, a[:int(count)], int64(offset+done)); err != nil { + return err + } + if err = readNativeAt(target, v[:int(count)], int64(offset+done)); err != nil { + return err + } + if !bytes.Equal(a[:int(count)], v[:int(count)]) { + return fmt.Errorf("native content mismatch at %s offset %d", to, offset+done) + } + b.checked.Add(int64(count)) + done += count + } + return nil +} diff --git a/internal/migration/native_factory_ceph.go b/internal/migration/native_factory_ceph.go new file mode 100644 index 0000000..3b798a3 --- /dev/null +++ b/internal/migration/native_factory_ceph.go @@ -0,0 +1,27 @@ +//go:build ceph && cgo + +package migration + +import ( + "context" + "io" + + "CephMig/internal/cephfsnative" +) + +func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) { + if err := ctx.Err(); err != nil { + return Engine{}, nil, err + } + source, err := cephfsnative.Open(options(c.Source)) + if err != nil { + return Engine{}, nil, err + } + target, err := cephfsnative.Open(options(c.Target)) + if err != nil { + source.Close() + return Engine{}, nil, err + } + backend := &nativeTransport{source: source, target: target, config: c, log: log} + return Engine{Exec: x, Log: log, Transport: backend, Access: nativeAccess{backend}}, backend, nil +} diff --git a/internal/migration/native_factory_stub.go b/internal/migration/native_factory_stub.go new file mode 100644 index 0000000..1f067c5 --- /dev/null +++ b/internal/migration/native_factory_stub.go @@ -0,0 +1,13 @@ +//go:build !ceph || !cgo + +package migration + +import ( + "context" + "errors" + "io" +) + +func openNativeEngine(context.Context, Config, Executor, io.Writer) (Engine, io.Closer, error) { + return Engine{}, nil, errors.New("native backend is not compiled in; use the ceph-tagged build with libcephfs (make dev-native-build)") +} diff --git a/internal/migration/native_helpers.go b/internal/migration/native_helpers.go new file mode 100644 index 0000000..67e5311 --- /dev/null +++ b/internal/migration/native_helpers.go @@ -0,0 +1,264 @@ +package migration + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "path" + "strings" + "syscall" + + "CephMig/internal/storage" +) + +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 { + if err := ctx.Err(); err != nil { + return err + } + if depth > 128 { + return errors.New("native directory depth exceeds 128") + } + if err := visit(p, n, depth); err != nil { + return err + } + if n.Kind() != storage.Directory { + return nil + } + dir, err := fs.OpenDir(p) + if err != nil { + return err + } + defer dir.Close() + for { + e, err := dir.Next() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + if e == nil || e.Name == "" || strings.ContainsAny(e.Name, "/\x00") || e.Name == "." || e.Name == ".." || e.Name == ".snap" { + return errors.New("invalid native directory entry") + } + if err = walk(path.Join(p, e.Name), e.Node, depth+1); err != nil { + return err + } + } + } + n, err := fs.Stat(root) + if err != nil { + return err + } + return walk(root, n, 0) +} +func removeNative(ctx context.Context, fs storage.FS, p string) error { + if err := ctx.Err(); err != nil { + return err + } + n, err := fs.Stat(p) + if errors.Is(err, syscall.ENOENT) { + return nil + } + if err != nil { + return err + } + if n.Kind() != storage.Directory { + return fs.Unlink(p) + } + d, err := fs.OpenDir(p) + if err != nil { + return err + } + // Re-open after each bounded batch, so deleting while iterating does not skip + // entries on directory streams whose offsets change after removal. + for { + var names []string + for len(names) < 128 { + e, err := d.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + d.Close() + return err + } + names = append(names, e.Name) + } + if err = d.Close(); err != nil { + return err + } + if len(names) == 0 { + break + } + for _, s := range names { + if err = removeNative(ctx, fs, path.Join(p, s)); err != nil { + return err + } + } + d, err = fs.OpenDir(p) + if err != nil { + return err + } + } + return fs.Rmdir(p) +} +func nativeQuota(fs storage.FS, p, key string) ([]byte, error) { + b, err := fs.GetXattr(p, key) + if errors.Is(err, syscall.ENODATA) { + return []byte("0"), nil + } + return b, err +} +func clearNativeQuotas(ctx context.Context, fs storage.FS, root string) error { + return walkNative(ctx, fs, root, func(p string, n storage.Node, _ int) error { + if n.Kind() != storage.Directory { + return nil + } + for _, key := range quotaKeys { + b, err := nativeQuota(fs, p, key) + if err != nil { + return err + } + if string(b) != "0" { + if err = fs.SetXattr(p, key, []byte("0")); err != nil { + return err + } + } + } + return nil + }) +} +func portableXattr(s string) bool { + return !strings.HasPrefix(s, "ceph.") && (!strings.HasPrefix(s, "system.") || s == "system.posix_acl_access" || s == "system.posix_acl_default") +} +func nativeAttrs(fs storage.FS, p string) (map[string][]byte, error) { + names, err := fs.ListXattr(p) + if err != nil { + return nil, err + } + attrs := make(map[string][]byte, len(names)) + for _, key := range names { + if !portableXattr(key) { + continue + } + value, err := fs.GetXattr(p, key) + if err != nil { + return nil, err + } + attrs[key] = value + } + return attrs, nil +} +func syncNativeMetadata(src, dst storage.FS, from, to string, n storage.Node, verify bool) error { + target, err := dst.Stat(to) + if err != nil { + return err + } + return syncNativeMetadataKnown(src, dst, from, to, n, target, verify) +} + +// Reuse a no-follow stat just read by the caller. No other writer is permitted +// in the target while a migration owns it. +func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target storage.Node, verify bool) error { + if n.Kind() != target.Kind() { + return fmt.Errorf("native type mismatch at %s", to) + } + different := n.Mode != target.Mode || n.UID != target.UID || n.GID != target.GID || !n.Mtime.Equal(target.Mtime) + if different { + if verify { + return fmt.Errorf("native metadata mismatch at %s", to) + } + if err := dst.SetAttr(to, n); err != nil { + return fmt.Errorf("native setattr %s: %w", to, err) + } + } + attrs, err := nativeAttrs(src, from) + if err != nil { + return err + } + old, err := nativeAttrs(dst, to) + if err != nil { + return err + } + for k, v := range old { + value, exists := attrs[k] + if verify { + if !exists || !bytes.Equal(value, v) { + return fmt.Errorf("native xattr mismatch at %s: %s", to, k) + } + } else if !exists { + if err = dst.RemoveXattr(to, k); err != nil { + return err + } + } + } + for k, v := range attrs { + if verify { + if actual, ok := old[k]; !ok || !bytes.Equal(v, actual) { + return fmt.Errorf("native xattr mismatch at %s: %s", to, k) + } + } else if actual, exists := old[k]; !exists || !bytes.Equal(actual, v) { + if err = dst.SetXattr(to, k, v); err != nil { + return fmt.Errorf("native setxattr %s: %w", k, err) + } + } + } + if n.Kind() == storage.Directory { + for _, key := range quotaKeys { + value, err := nativeQuota(src, from, key) + if err != nil { + return err + } + actual, err := nativeQuota(dst, to, key) + if err != nil { + return err + } + if bytes.Equal(value, actual) { + continue + } + if verify { + return fmt.Errorf("native quota mismatch at %s: %s", to, key) + } + if err = dst.SetXattr(to, key, value); err != nil { + return err + } + } + } + return nil +} +func ensureNativeDirectory(ctx context.Context, fs storage.FS, p string) error { + st, err := fs.Stat(p) + if err == nil && st.Kind() == storage.Directory { + return nil + } + if err != nil && !errors.Is(err, syscall.ENOENT) { + return err + } + if err == nil { + if err = removeNative(ctx, fs, p); err != nil { + return err + } + } + return fs.Mkdir(p, 0700) +} +func validateNativeDirectory(fs storage.FS, p string) error { + current := "/" + for _, part := range strings.Split(strings.TrimPrefix(p, "/"), "/") { + if part == "" || part == "." || part == ".." { + return fmt.Errorf("invalid native path %q", p) + } + current = path.Join(current, part) + n, err := fs.Stat(current) + if err != nil { + return err + } + if n.Kind() != storage.Directory { + return fmt.Errorf("native path contains non-directory %s", current) + } + } + return nil +} diff --git a/internal/migration/native_index.go b/internal/migration/native_index.go new file mode 100644 index 0000000..01ac140 --- /dev/null +++ b/internal/migration/native_index.go @@ -0,0 +1,229 @@ +package migration + +import ( + "bytes" + "encoding/binary" + "errors" + "os" + "path/filepath" + "time" + + bolt "go.etcd.io/bbolt" +) + +var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete"} + +type nativeIndex struct { + db *bolt.DB + path string +} +type baseEntry struct{ Inode, Version, Size, TargetInode uint64 } + +func encodeEntry(e baseEntry) []byte { + b := make([]byte, 32) + binary.BigEndian.PutUint64(b, e.Inode) + binary.BigEndian.PutUint64(b[8:], e.Version) + binary.BigEndian.PutUint64(b[16:], e.Size) + binary.BigEndian.PutUint64(b[24:], e.TargetInode) + return b +} +func decodeEntry(b []byte) (baseEntry, bool) { + if len(b) != 32 { + return baseEntry{}, false + } + return baseEntry{binary.BigEndian.Uint64(b), binary.BigEndian.Uint64(b[8:]), binary.BigEndian.Uint64(b[16:]), binary.BigEndian.Uint64(b[24:])}, true +} +func createNativeIndex(parent string) (*nativeIndex, error) { + f, err := os.CreateTemp(parent, "pending-*.bolt") + if err != nil { + return nil, err + } + p := f.Name() + if err = f.Close(); err != nil { + return nil, err + } + db, err := bolt.Open(p, 0600, &bolt.Options{Timeout: time.Second, NoSync: true}) + if err != nil { + os.Remove(p) + return nil, err + } + err = db.Update(func(tx *bolt.Tx) error { + for _, s := range nativeBuckets { + if _, err := tx.CreateBucketIfNotExists([]byte(s)); err != nil { + return err + } + } + return nil + }) + if err != nil { + db.Close() + os.Remove(p) + return nil, err + } + return &nativeIndex{db: db, path: p}, nil +} +func openNativeIndex(path string) (*nativeIndex, error) { + db, err := bolt.Open(path, 0600, &bolt.Options{ReadOnly: true, Timeout: time.Second}) + if err != nil { + return nil, err + } + return &nativeIndex{db: db, path: path}, nil +} +func (x *nativeIndex) close() error { + if x == nil || x.db == nil { + return nil + } + err := x.db.Close() + x.db = nil + return err +} +func (x *nativeIndex) get(bucket string, key []byte) ([]byte, error) { + var b []byte + err := x.db.View(func(tx *bolt.Tx) error { + k := tx.Bucket([]byte(bucket)) + if k == nil { + return errors.New("invalid native index") + } + b = bytes.Clone(k.Get(key)) + return nil + }) + return b, err +} +func (x *nativeIndex) put(bucket string, key, value []byte) error { + return x.db.Update(func(tx *bolt.Tx) error { return tx.Bucket([]byte(bucket)).Put(key, value) }) +} +func (x *nativeIndex) entry(rel string) (baseEntry, bool, error) { + b, err := x.get("paths", []byte(rel)) + if err != nil { + return baseEntry{}, false, err + } + e, ok := decodeEntry(b) + return e, ok, nil +} + +// Source inventory entries also cover directories and special files. A zero +// target inode marks entries that cannot yet serve as a verified data base. +func (x *nativeIndex) containsPath(rel string) (bool, error) { + b, err := x.get("paths", []byte(rel)) + if err != nil || b == nil { + return false, err + } + if _, ok := decodeEntry(b); !ok { + return false, errors.New("invalid source inventory entry") + } + return true, nil +} + +func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error { + previous, ok, err := x.entry(rel) + if err != nil { + return err + } + if ok && previous == entry { + return nil + } + return x.put("paths", []byte(rel), encodeEntry(entry)) +} + +func (x *nativeIndex) requireInventory() error { + complete, err := x.get("meta", []byte("inventory_complete")) + if err != nil { + return err + } + if !bytes.Equal(complete, []byte{1}) { + return errors.New("source inventory is not complete") + } + return nil +} +func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byte) error) error { + // The read transaction deliberately spans the iteration. Callbacks must not + // write to this same DB (which could deadlock a mmap resize). + return x.db.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte(bucket)) + if b == nil { + return errors.New("missing native index bucket") + } + c := b.Cursor() + var k, v []byte + if reverse { + k, v = c.Last() + } else { + k, v = c.First() + } + for k != nil { + if err := visit(k, v); err != nil { + return err + } + if reverse { + k, v = c.Prev() + } else { + k, v = c.Next() + } + } + return nil + }) +} +func (x *nativeIndex) ranges(rel string, visit func(uint64, uint64) error) error { + prefix := append([]byte(rel), 0) + return x.db.View(func(tx *bolt.Tx) error { + c := tx.Bucket([]byte("ranges")).Cursor() + for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { + if len(k) != len(prefix)+8 || len(v) != 8 { + return errors.New("invalid native extent record") + } + if err := visit(binary.BigEndian.Uint64(k[len(prefix):]), binary.BigEndian.Uint64(v)); err != nil { + return err + } + } + return nil + }) +} +func (x *nativeIndex) extent(rel string, off, length uint64) error { + key := make([]byte, len(rel)+1+8) + copy(key, rel) + binary.BigEndian.PutUint64(key[len(rel)+1:], off) + value := make([]byte, 8) + binary.BigEndian.PutUint64(value, length) + return x.put("ranges", key, value) +} +func nativeInodeKey(ino uint64) []byte { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, ino) + return b +} +func nativeDirKey(rel string, depth int) []byte { + b := make([]byte, 2+len(rel)) + binary.BigEndian.PutUint16(b, uint16(depth)) + copy(b[2:], rel) + return b +} +func (x *nativeIndex) commit(parent, name string) error { + if err := x.put("meta", []byte("snapshot"), []byte(name)); err != nil { + return err + } + if err := x.db.Sync(); err != nil { + return err + } + if err := x.close(); err != nil { + return err + } + final := filepath.Join(parent, "base.bolt") + if err := os.Rename(x.path, final); err != nil { + return err + } + d, err := os.Open(parent) + if err != nil { + return err + } + err = d.Sync() + d.Close() + if err != nil { + return err + } + read, err := openNativeIndex(final) + if err != nil { + return err + } + x.path, x.db = read.path, read.db + return nil +} diff --git a/internal/migration/native_inventory_test.go b/internal/migration/native_inventory_test.go new file mode 100644 index 0000000..7f5f0f5 --- /dev/null +++ b/internal/migration/native_inventory_test.go @@ -0,0 +1,159 @@ +package migration + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "CephMig/internal/storage" +) + +type inventorySourceFS struct { + storage.FS + calls int +} + +func (f *inventorySourceFS) Stat(string) (storage.Node, error) { + f.calls++ + return storage.Node{}, errors.New("source path lookup must use immutable inventory") +} + +type inventoryTargetFS struct{ storage.FS } + +func (f inventoryTargetFS) Stat(p string) (storage.Node, error) { + var s syscall.Stat_t + err := syscall.Lstat(p, &s) + return storage.Node{Mode: s.Mode, Inode: s.Ino, Nlink: s.Nlink, Size: uint64(s.Size), UID: s.Uid, GID: s.Gid, + Mtime: time.Unix(s.Mtim.Sec, s.Mtim.Nsec)}, err +} +func (f inventoryTargetFS) OpenDir(p string) (storage.DirectoryStream, error) { + d, err := os.Open(p) + if err != nil { + return nil, err + } + return &inventoryDir{file: d, path: p}, nil +} +func (inventoryTargetFS) Unlink(p string) error { return syscall.Unlink(p) } +func (inventoryTargetFS) Rmdir(p string) error { return syscall.Rmdir(p) } + +type inventoryDir struct { + file *os.File + path string +} + +func (d *inventoryDir) Next() (*storage.Entry, error) { + es, err := d.file.ReadDir(1) + if len(es) == 0 { + if err == nil { + err = io.EOF + } + return nil, err + } + n, err := (inventoryTargetFS{}).Stat(filepath.Join(d.path, es[0].Name())) + return &storage.Entry{Name: es[0].Name(), Node: n}, err +} +func (d *inventoryDir) Close() error { return d.file.Close() } + +func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) { + x, err := createNativeIndex(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer x.close() + root, outside := t.TempDir(), t.TempDir() + for _, dir := range []string{"dir", "obsolete"} { + if err := os.Mkdir(filepath.Join(root, dir), 0700); err != nil { + t.Fatal(err) + } + } + for _, rel := range []string{"keep", "dir/file", "obsolete/nested"} { + if err := os.WriteFile(filepath.Join(root, rel), []byte("data"), 0600); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(outside, "sentinel"), []byte("untouched"), 0600); err != nil { + t.Fatal(err) + } + for _, rel := range []string{"link", "obsolete-link"} { + if err := os.Symlink(outside, filepath.Join(root, rel)); err != nil { + t.Fatal(err) + } + } + for _, rel := range []string{".", "keep", "dir", "dir/file", "link"} { + if err := x.put("paths", []byte(rel), encodeEntry(baseEntry{Inode: 1})); err != nil { + t.Fatal(err) + } + } + source := &inventorySourceFS{} + b := nativeTransport{source: source, target: inventoryTargetFS{}, pending: x, round: Round{SourcePath: "/immutable"}} + if err := b.prune(context.Background(), "/immutable", root); err == nil { + t.Fatal("pruned without complete inventory") + } + if _, err := os.Stat(filepath.Join(root, "obsolete/nested")); err != nil { + t.Fatal("incomplete inventory deleted target data") + } + if err := x.put("meta", []byte("inventory_complete"), []byte{1}); err != nil { + t.Fatal(err) + } + if err := b.verifyInventory(context.Background(), root); err == nil { + t.Fatal("unexpected entries were not detected") + } + if err := b.prune(context.Background(), "/immutable", root); err != nil { + t.Fatal(err) + } + if err := b.verifyInventory(context.Background(), root); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(filepath.Join(root, "obsolete")); !os.IsNotExist(err) { + t.Fatal("obsolete directory survived", err) + } + if _, err := os.Lstat(filepath.Join(root, "obsolete-link")); !os.IsNotExist(err) { + t.Fatal("obsolete symlink survived", err) + } + if data, err := os.ReadFile(filepath.Join(outside, "sentinel")); err != nil || string(data) != "untouched" { + t.Fatal("followed symlink outside target") + } + if source.calls != 0 { + t.Fatalf("performed %d redundant source stats", source.calls) + } + if err := os.WriteFile(filepath.Join(root, "dir/foreign"), nil, 0600); err != nil { + t.Fatal(err) + } + if err := b.verifyInventory(context.Background(), root); err == nil { + t.Fatal("extra target path was ignored") + } +} + +func TestNativeInventoryRejectsCorruptionAndUnchangedIndexIsReadOnly(t *testing.T) { + dir := t.TempDir() + x, err := createNativeIndex(dir) + if err != nil { + t.Fatal(err) + } + defer x.close() + if err := x.put("paths", []byte("broken"), []byte{1}); err != nil { + t.Fatal(err) + } + if _, err := x.containsPath("broken"); err == nil { + t.Fatal("corrupt source inventory accepted") + } + entry := baseEntry{Inode: 1, Version: 2, Size: 128, TargetInode: 3} + if err := x.putEntryIfChanged("file", entry); err != nil { + t.Fatal(err) + } + if err := x.commit(dir, "snapshot"); err != nil { + t.Fatal(err) + } + if err := x.putEntryIfChanged("file", entry); err != nil { + t.Fatal("unchanged entry attempted a write", err) + } + entry.TargetInode++ + if err := x.putEntryIfChanged("file", entry); err == nil { + t.Fatal("changed entry silently ignored on read-only index") + } +} diff --git a/internal/migration/native_test.go b/internal/migration/native_test.go new file mode 100644 index 0000000..d05f460 --- /dev/null +++ b/internal/migration/native_test.go @@ -0,0 +1,234 @@ +package migration + +import ( + "bytes" + "context" + "errors" + "io" + "path/filepath" + "reflect" + "syscall" + "testing" + "time" + + "CephMig/internal/storage" +) + +type emptyNativeDiff struct{} + +func (emptyNativeDiff) Next() (string, error) { return "", io.EOF } +func (emptyNativeDiff) Close() error { return nil } + +type diffTestFS struct { + storage.FS + err error +} + +func (f diffTestFS) SnapDiff(_, _, _, _ string) (storage.DiffStream, error) { + return emptyNativeDiff{}, f.err +} + +// A durable base is useful only if BOTH the journal and the filesystem identity +// match. An interrupted in-place block copy must never become the next base. +func TestNativeBaseTrust(t *testing.T) { + for _, tc := range []struct { + name, journal, identity string + apiError error + wantDelta bool + }{ + {"committed", "previous", "cluster-paths", nil, true}, + {"interrupted-target", "", "cluster-paths", nil, false}, + {"wrong-round", "other", "cluster-paths", nil, false}, + {"recreated-subvolume", "previous", "new-path", nil, false}, + {"unsupported-api", "previous", "cluster-paths", syscall.ENOSYS, false}, + } { + t.Run(tc.name, func(t *testing.T) { + state := filepath.Join(t.TempDir(), "job.json") + b := &nativeTransport{source: diffTestFS{err: tc.apiError}, identity: "cluster-paths"} + r := Round{SourcePath: "/sub/.snap/previous/uuid", Name: "previous", StatePath: state} + if err := b.BeginRound(context.Background(), r); err != nil { + t.Fatal(err) + } + entry := baseEntry{Inode: 42, Version: 7, Size: 1 << 30, TargetInode: 77} + if err := b.pending.put("paths", []byte("file\nname"), encodeEntry(entry)); err != nil { + t.Fatal(err) + } + if err := b.Commit(context.Background(), "previous"); err != nil { + t.Fatal(err) + } + b.identity = tc.identity + r.Name, r.SourcePath, r.BaseName = "current", "/sub/.snap/current/uuid", tc.journal + if err := b.BeginRound(context.Background(), r); err != nil { + t.Fatal(err) + } + defer b.pending.close() + if b.base != nil { + defer b.base.close() + } + if b.delta != tc.wantDelta { + t.Fatalf("delta=%v; want %v", b.delta, tc.wantDelta) + } + if b.delta { + got, ok, err := b.base.entry("file\nname") + if err != nil || !ok || got != entry { + t.Fatalf("entry=%+v ok=%v err=%v", got, ok, err) + } + } + }) + } +} + +func TestNativeExtentIsolation(t *testing.T) { + x, err := createNativeIndex(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer x.close() + for _, e := range []struct { + name string + offset, size uint64 + }{ + {"a", 9000, 100}, {"a", 0, 4096}, {"ab", 12, 900}, {"a\n", 11, 1}, + } { + if err := x.extent(e.name, e.offset, e.size); err != nil { + t.Fatal(err) + } + } + var got []storage.Extent + if err := x.ranges("a", func(off, length uint64) error { + got = append(got, storage.Extent{Offset: off, Length: length}) + return nil + }); err != nil { + t.Fatal(err) + } + want := []storage.Extent{{Offset: 0, Length: 4096}, {Offset: 9000, Length: 100}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v want %v", got, want) + } +} + +type attrsTestFS struct { + storage.FS + n storage.Node + attrs map[string][]byte + setCalls int +} + +func (f *attrsTestFS) Stat(string) (storage.Node, error) { return f.n, nil } +func (f *attrsTestFS) SetAttr(_ string, n storage.Node) error { f.setCalls++; f.n = n; return nil } +func (f *attrsTestFS) ListXattr(string) ([]string, error) { + var keys []string + for k := range f.attrs { + keys = append(keys, k) + } + return keys, nil +} +func (f *attrsTestFS) GetXattr(_, key string) ([]byte, error) { + if v, ok := f.attrs[key]; ok { + return v, nil + } + return nil, syscall.ENODATA +} +func (f *attrsTestFS) SetXattr(_, key string, value []byte) error { + f.attrs[key] = bytes.Clone(value) + return nil +} +func (f *attrsTestFS) RemoveXattr(_, key string) error { delete(f.attrs, key); return nil } + +func TestNativeMetadataEmptyXattrAndDeletion(t *testing.T) { + n := storage.Node{Mode: storage.Regular | 0640, UID: 123, GID: 456, Mtime: time.Unix(123, 45)} + src := &attrsTestFS{n: n, attrs: map[string][]byte{"user.empty": {}, "user.data": []byte("content"), "ceph.layout": []byte("source-pool")}} + dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.old": []byte("delete"), "ceph.layout": []byte("target-pool")}} + if err := syncNativeMetadata(src, dst, "/src", "/dst", n, false); err != nil { + t.Fatal(err) + } + if _, ok := dst.attrs["user.empty"]; !ok { + t.Fatal("empty xattr was not created") + } + if _, ok := dst.attrs["user.old"]; ok { + t.Fatal("obsolete xattr survived") + } + if string(dst.attrs["ceph.layout"]) != "target-pool" { + t.Fatal("source internal Ceph layout leaked into target") + } + if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err != nil { + t.Fatal(err) + } + dst.n.UID++ + if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err == nil { + t.Fatal("owner mismatch not detected") + } +} + +func TestNativeCancellationAndPaths(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + b := nativeTransport{config: Config{BandwidthKiB: 1}, started: time.Now()} + if err := b.rate(ctx, 4096); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + for _, bad := range []string{"", ".", "..", ".snap", "a/b", "a\x00b"} { + if validNativeEntry(bad) { + t.Fatalf("accepted %q", bad) + } + } + if !validNativeEntry("with spaces\nand newline") { + t.Fatal("valid filename rejected") + } + if _, err := relativeNative("/volume", "/volume-other/file"); err == nil { + t.Fatal("path escaped subvolume") + } +} + +func TestNativeMetadataOnlyWritesChangedAttributes(t *testing.T) { + n := storage.Node{Mode: storage.Regular | 0640, UID: 12, GID: 34, Mtime: time.Unix(123, 0)} + src := &attrsTestFS{n: n, attrs: map[string][]byte{"user.new": []byte("value")}} + dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.old": []byte("remove")}} + if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil { + t.Fatal(err) + } + if dst.setCalls != 0 { + t.Fatal("unchanged ownership, mode and mtime were rewritten") + } + if !reflect.DeepEqual(src.attrs, dst.attrs) { + t.Fatal("xattrs must still be synchronized") + } + dst.n.UID++ + if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil { + t.Fatal(err) + } + if dst.setCalls != 1 || dst.n.UID != n.UID { + t.Fatal("changed ownership was not restored") + } +} + +func TestNativeVerifyCommittedRound(t *testing.T) { + workspace := t.TempDir() + index, err := createNativeIndex(workspace) + if err != nil { + t.Fatal(err) + } + defer index.close() + n := storage.Node{Mode: storage.Regular | 0640, Inode: 7, Version: 1, Nlink: 1, Mtime: time.Unix(123, 0)} + src := &attrsTestFS{n: n, attrs: map[string][]byte{}} + dst := &attrsTestFS{n: n, attrs: map[string][]byte{}} + if err := index.put("groups", nativeInodeKey(n.Inode), []byte(".")); err != nil { + t.Fatal(err) + } + if err := index.put("paths", []byte("."), encodeEntry(baseEntry{Inode: n.Inode, Version: n.Version})); err != nil { + t.Fatal(err) + } + if err := index.put("meta", []byte("inventory_complete"), []byte{1}); err != nil { + t.Fatal(err) + } + if err := index.commit(workspace, "final"); err != nil { + t.Fatal(err) + } + b := nativeTransport{source: src, target: dst, pending: index, workspace: workspace, + round: Round{SourcePath: "/snapshot", TargetPath: "/live"}, verified: map[string]bool{"/live": true}} + // Finalization repeats metadata/topology verification after the durable base + // index has become read-only. It must not rewrite inode records at this stage. + if err := b.Verify(context.Background(), "/snapshot", "/live"); err != nil { + t.Fatal(err) + } +} diff --git a/internal/migration/native_transport.go b/internal/migration/native_transport.go new file mode 100644 index 0000000..e1adca1 --- /dev/null +++ b/internal/migration/native_transport.go @@ -0,0 +1,461 @@ +package migration + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "os" + "path" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + + "CephMig/internal/storage" +) + +const nativeChunk = 4 << 20 +const nativeBlockThreshold = 16 << 20 + +type nativeTransport struct { + source, target storage.FS + config Config + log io.Writer + identity string + round Round + workspace string + pending, base *nativeIndex + delta bool + snapRoot, snapRel string + verified map[string]bool + visited, copied, written, checked, blockFiles, diffEntries atomic.Int64 + rateBytes atomic.Int64 + started time.Time +} + +func (b *nativeTransport) Close() error { + var errs []error + if b.pending != nil { + errs = append(errs, b.pending.close()) + } + if b.base != nil { + errs = append(errs, b.base.close()) + } + errs = append(errs, b.source.Close(), b.target.Close()) + return errors.Join(errs...) +} +func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error { + if b.pending != nil { + if err := b.pending.close(); err != nil { + return err + } + } + if b.base != nil { + if err := b.base.close(); err != nil { + return err + } + b.base = nil + } + b.round = r + b.workspace = r.StatePath + ".native" + if err := privateDirectories(b.workspace); err != nil { + return err + } + files, err := os.ReadDir(b.workspace) + if err != nil { + return err + } + for _, f := range files { + if strings.HasPrefix(f.Name(), "pending-") && strings.HasSuffix(f.Name(), ".bolt") { + if !f.Type().IsRegular() { + return errors.New("native scratch path is not a regular file") + } + if err = os.Remove(filepath.Join(b.workspace, f.Name())); err != nil { + return err + } + } + } + b.pending, err = createNativeIndex(b.workspace) + if err != nil { + return err + } + if err = b.pending.put("meta", []byte("identity"), []byte(b.identity)); err != nil { + return err + } + b.delta = false + b.verified = map[string]bool{} + b.visited.Store(0) + b.copied.Store(0) + b.written.Store(0) + b.checked.Store(0) + b.blockFiles.Store(0) + b.diffEntries.Store(0) + b.rateBytes.Store(0) + b.started = time.Now() + marker := "/.snap/" + r.Name + at := strings.LastIndex(r.SourcePath, marker) + if at < 0 { + return errors.New("native source snapshot path does not contain its snapshot name") + } + b.snapRoot = r.SourcePath[:at] + b.snapRel = r.SourcePath[at+len(marker):] + if b.snapRel == "" { + b.snapRel = "/" + } + if r.BaseName != "" { + base, err := openNativeIndex(filepath.Join(b.workspace, "base.bolt")) + if err == nil { + name, e1 := base.get("meta", []byte("snapshot")) + identity, e2 := base.get("meta", []byte("identity")) + if e1 == nil && e2 == nil && string(name) == r.BaseName && string(identity) == b.identity { + b.base = base + b.delta = true + } else { + base.close() + } + } else if !errors.Is(err, os.ErrNotExist) && b.log != nil { + fmt.Fprintf(b.log, "native base index unavailable; rebuilding full snapshot: %v\n", err) + } + } + if b.delta { + if err := b.collectChanges(ctx, b.snapRel, r.SourcePath, 0); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + b.delta = false + if b.log != nil { + fmt.Fprintf(b.log, "native snapdiff unavailable for this pair; full reconstruction: %v\n", err) + } + } + } + if b.log != nil { + fmt.Fprintf(b.log, "native snapshot=%s mode=%s\n", r.Name, b.Statistics().Mode) + } + return nil +} +func (b *nativeTransport) collectChanges(ctx context.Context, rel, current string, depth int) error { + if err := ctx.Err(); err != nil { + return err + } + if depth > 128 { + return errors.New("snapdiff depth exceeds 128") + } + d, err := b.source.SnapDiff(b.snapRoot, rel, b.round.BaseName, b.round.Name) + if errors.Is(err, syscall.ENOENT) { + return nil + } // A newly created subtree has no base paths. + if err != nil { + return err + } + defer d.Close() + for { + if err := ctx.Err(); err != nil { + return err + } + name, err := d.Next() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + if !validNativeEntry(name) { + return fmt.Errorf("invalid snapdiff entry %q", name) + } + b.diffEntries.Add(1) + child := path.Join(current, name) + n, err := b.source.Stat(child) + if errors.Is(err, syscall.ENOENT) { + continue + } + if err != nil { + return err + } + if n.Kind() == storage.Directory { + if err = b.collectChanges(ctx, path.Join(rel, name), child, depth+1); err != nil { + return err + } + } else if n.Kind() == storage.Regular { + if err = b.pending.put("changed", nativeInodeKey(n.Inode), []byte{1}); err != nil { + return err + } + } + } +} +func validNativeEntry(name string) bool { + return name != "" && name != "." && name != ".." && name != ".snap" && !strings.ContainsAny(name, "/\x00") +} +func relativeNative(root, p string) (string, error) { + if p == root { + return ".", nil + } + if !strings.HasPrefix(p, root+"/") { + return "", fmt.Errorf("native path escapes root: %s", p) + } + return strings.TrimPrefix(p, root+"/"), nil +} + +type nativeJob struct { + rel string + node storage.Node +} + +func (b *nativeTransport) Copy(ctx context.Context, from, to string) error { + var err error + if b.pending == nil || from != b.round.SourcePath || to != b.round.TargetPath { + return errors.New("native copy round is not initialized") + } + copyCtx, cancel := context.WithCancel(ctx) + defer cancel() + workers := b.config.Workers + if workers == 0 { + workers = 8 + } + jobs := make(chan nativeJob, workers*2) + errorsOut := make(chan error, 1) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for job := range jobs { + if err := b.copyRegular(copyCtx, job); err != nil { + select { + case errorsOut <- err: + default: + } + cancel() + } + } + }() + } + lastProgress := time.Now() + walkErr := walkNative(copyCtx, b.source, from, func(p string, n storage.Node, depth int) error { + b.visited.Add(1) + if b.log != nil && time.Since(lastProgress) >= 30*time.Second { + fmt.Fprintf(b.log, "native copying visited=%d copied=%d bytes_written=%d\n", b.visited.Load(), b.copied.Load(), b.written.Load()) + lastProgress = time.Now() + } + rel, err := relativeNative(from, p) + if err != nil { + return err + } + target := path.Join(to, rel) + // Record every immutable source entry before dispatching work. This local + // inventory replaces source path lookups during pruning and verification. + if err = b.pending.put("paths", []byte(rel), encodeEntry(baseEntry{ + Inode: n.Inode, Version: n.Version, Size: n.Size, + })); err != nil { + return err + } + // POSIX hardlinks can also refer to symlinks and special files. Track all + // non-directory inodes, then create their aliases after canonical entries. + if n.Kind() != storage.Directory { + first, err := b.pending.get("groups", nativeInodeKey(n.Inode)) + if err != nil { + return err + } + if first != nil { + return b.pending.put("aliases", []byte(rel), first) + } + if err = b.pending.put("groups", nativeInodeKey(n.Inode), []byte(rel)); err != nil { + return err + } + } + switch n.Kind() { + case storage.Directory: + if err = ensureNativeDirectory(copyCtx, b.target, target); err != nil { + return err + } + return b.pending.put("dirs", nativeDirKey(rel, depth), []byte(rel)) + case storage.Regular: + if n.Size > math.MaxInt64 { + return errors.New("file exceeds supported signed offset range") + } + select { + case jobs <- nativeJob{rel, n}: + return nil + case <-copyCtx.Done(): + return copyCtx.Err() + } + case storage.Symlink, storage.FIFO, storage.Socket, storage.CharDevice, storage.BlockDevice: + return b.copySpecial(copyCtx, rel, n) + default: + return fmt.Errorf("unsupported native file type %o at %s", n.Mode, p) + } + }) + close(jobs) + wg.Wait() + select { + case err := <-errorsOut: + return err + default: + } + if walkErr != nil { + return walkErr + } + if err = b.pending.put("meta", []byte("inventory_complete"), []byte{1}); err != nil { + return err + } + if err = ctx.Err(); err != nil { + return err + } + // Complete links only after every canonical file is durable. + if err = b.pending.each("aliases", false, func(k, v []byte) error { + if err := ctx.Err(); err != nil { + return err + } + dst, canonical := path.Join(to, string(k)), path.Join(to, string(v)) + a, err := b.target.Stat(canonical) + if err != nil { + return err + } + old, err := b.target.Stat(dst) + if err == nil && old.Kind() == a.Kind() && old.Inode == a.Inode { + return nil + } + if err != nil && !errors.Is(err, syscall.ENOENT) { + return err + } + if err == nil { + if err = removeNative(ctx, b.target, dst); err != nil { + return err + } + } + if err := b.target.Link(canonical, dst); err != nil { + return fmt.Errorf("native hardlink %s -> %s: %w", string(k), string(v), err) + } + return nil + }); err != nil { + return err + } + if err = b.prune(ctx, from, to); err != nil { + return err + } + // Child creation/deletion has finished; restore directory metadata last. + if err = b.pending.each("dirs", true, func(_, v []byte) error { + if err := ctx.Err(); err != nil { + return err + } + rel := string(v) + src, dst := path.Join(from, rel), path.Join(to, rel) + n, err := b.source.Stat(src) + if err != nil { + return err + } + return syncNativeMetadata(b.source, b.target, src, dst, n, false) + }); err != nil { + return err + } + return b.target.Sync() +} +func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage.Node) error { + src, dst := path.Join(b.round.SourcePath, rel), path.Join(b.round.TargetPath, rel) + _, err := b.target.Stat(dst) + if err != nil && !errors.Is(err, syscall.ENOENT) { + return err + } + exists := err == nil + var text string + if n.Kind() == storage.Symlink { + text, err = b.source.Readlink(src) + if err != nil { + return err + } + } + // Recreate canonical special inodes so previously linked, now independent + // source entries cannot remain accidentally linked at the target. + if exists { + if err = removeNative(ctx, b.target, dst); err != nil { + return err + } + } + if n.Kind() == storage.Symlink { + err = b.target.Symlink(text, dst) + } else { + err = b.target.Mknod(dst, n.Mode, n.Rdev) + } + if err != nil { + return err + } + return syncNativeMetadata(b.source, b.target, src, dst, n, false) +} +func (b *nativeTransport) prune(ctx context.Context, from, to string) error { + if from != b.round.SourcePath { + return errors.New("source inventory belongs to a different round") + } + if err := b.pending.requireInventory(); err != nil { + return err + } + // Store deletions on disk and apply after closing the directory streams. + err := walkNative(ctx, b.target, to, func(p string, _ storage.Node, _ int) error { + rel, err := relativeNative(to, p) + if err != nil { + return err + } + if rel == "." { + return nil + } + present, err := b.pending.containsPath(rel) + if err != nil { + return err + } + if !present { + return b.pending.put("delete", []byte(rel), []byte{1}) + } + return nil + }) + if err != nil { + return err + } + return b.pending.each("delete", true, func(k, _ []byte) error { return removeNative(ctx, b.target, path.Join(to, string(k))) }) +} +func (b *nativeTransport) Published(p string) { b.verified[p] = true } +func (b *nativeTransport) Commit(ctx context.Context, name string) error { + if err := ctx.Err(); err != nil { + return err + } + if b.base != nil { + if err := b.base.close(); err != nil { + return err + } + b.base = nil + } + return b.pending.commit(b.workspace, name) +} +func (b *nativeTransport) Statistics() TransferStats { + mode := "full" + base := "" + if b.delta { + mode = "snapdiff" + base = b.round.BaseName + } + return TransferStats{Mode: mode, BaseSnapshot: base, FilesVisited: b.visited.Load(), + FilesCopied: b.copied.Load(), BytesCopied: b.written.Load(), BytesVerified: b.checked.Load(), + BlockDiffFiles: b.blockFiles.Load(), SnapDiffEntries: b.diffEntries.Load()} +} +func (b *nativeTransport) rate(ctx context.Context, n int) error { + if b.config.BandwidthKiB == 0 { + return nil + } + total := b.rateBytes.Add(int64(n)) + seconds := float64(total) / float64(b.config.BandwidthKiB*1024) + wait := time.Duration(seconds*float64(time.Second)) - time.Since(b.started) + if wait <= 0 { + return nil + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-timer.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} +func nodeKey(ino uint64) [16]byte { var b [16]byte; binary.BigEndian.PutUint64(b[:], ino); return b } diff --git a/internal/migration/process.go b/internal/migration/process.go new file mode 100644 index 0000000..b1fdeec --- /dev/null +++ b/internal/migration/process.go @@ -0,0 +1,92 @@ +package migration + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "strings" + "syscall" + "time" +) + +type Executor interface { + Exec(context.Context, io.Writer, string, ...string) error +} +type Process struct{ Stderr io.Writer } + +type ProcessError struct { + Name string + Err error + Diagnostic string +} + +func (e *ProcessError) Error() string { return fmt.Sprintf("%s failed: %v", e.Name, e.Err) } +func (e *ProcessError) Unwrap() error { return e.Err } + +type tailBuffer struct{ data []byte } + +func (b *tailBuffer) Write(p []byte) (int, error) { + const limit = 4096 + n := len(p) + if n >= limit { + b.data = append(b.data[:0], p[n-limit:]...) + return n, nil + } + if len(b.data)+n > limit { + b.data = append(b.data[:0], b.data[len(b.data)+n-limit:]...) + } + b.data = append(b.data, p...) + return n, nil +} + +func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...string) error { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Stdout = out + var diagnostic tailBuffer + cmd.Stderr = &diagnostic + if p.Stderr != nil { + cmd.Stderr = io.MultiWriter(p.Stderr, &diagnostic) + } + cmd.Env = append(os.Environ(), "LC_ALL=C") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + err := syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + if errors.Is(err, syscall.ESRCH) { + return os.ErrProcessDone + } + return err + } + cmd.WaitDelay = 5 * time.Second + if err := cmd.Run(); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + // Do not print arguments: Ceph metadata values may be confidential. + return &ProcessError{Name: name, Err: err, Diagnostic: strings.TrimSpace(string(diagnostic.data))} + } + return nil +} + +type limitedBuffer struct { + bytes.Buffer + limit int +} + +func (b *limitedBuffer) Write(p []byte) (int, error) { + if len(p) > b.limit-b.Len() { + return 0, errors.New("command output exceeds configured limit") + } + return b.Buffer.Write(p) +} + +func output(ctx context.Context, x Executor, name string, args ...string) ([]byte, error) { + b := &limitedBuffer{limit: 16 << 20} + if err := x.Exec(ctx, b, name, args...); err != nil { + return nil, err + } + return b.Bytes(), nil +} diff --git a/internal/migration/rsync.go b/internal/migration/rsync.go new file mode 100644 index 0000000..e500a19 --- /dev/null +++ b/internal/migration/rsync.go @@ -0,0 +1,66 @@ +package migration + +import ( + "context" + "errors" + "fmt" + "io" + "os/exec" + "strconv" + "strings" +) + +type Transport interface { + Copy(context.Context, string, string) error + Verify(context.Context, string, string) error +} + +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+"/") +} +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 } + +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 new file mode 100644 index 0000000..c989cf0 --- /dev/null +++ b/internal/migration/rsync_test.go @@ -0,0 +1,147 @@ +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.go b/internal/migration/state.go new file mode 100644 index 0000000..a97e884 --- /dev/null +++ b/internal/migration/state.go @@ -0,0 +1,146 @@ +package migration + +import ( + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "syscall" +) + +const stateVersion = 1 + +type Snapshot struct { + Name string `json:"name"` + CreatedAt string `json:"source_created_at"` + TargetCreatedAt string `json:"target_created_at,omitempty"` + Owned bool `json:"owned"` + Final bool `json:"final,omitempty"` + Done bool `json:"done"` + Metadata map[string]string `json:"metadata,omitempty"` + Stats *TransferStats `json:"transfer,omitempty"` +} + +type State struct { + Version int `json:"version"` + ID string `json:"id"` + Config Config `json:"config"` + SourceFSID string `json:"source_fsid"` + TargetFSID string `json:"target_fsid"` + SourcePath string `json:"source_path"` + TargetPath string `json:"target_path"` + Phase string `json:"phase"` + Snapshots []Snapshot `json:"snapshots"` + Notes []string `json:"notes,omitempty"` + LiveSnapshot string `json:"live_snapshot,omitempty"` +} + +func LoadState(path string) (*State, error) { + f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, err + } + defer f.Close() + var s State + d := json.NewDecoder(f) + d.DisallowUnknownFields() + if err := d.Decode(&s); err != nil { + return nil, fmt.Errorf("state: %w", err) + } + if err := d.Decode(new(any)); !errors.Is(err, io.EOF) { + return nil, errors.New("state must contain exactly one JSON object") + } + id, err := hex.DecodeString(s.ID) + if s.Version != stateVersion || err != nil || len(id) != 16 { + return nil, errors.New("unsupported or invalid state") + } + if s.Phase != "syncing" && s.Phase != "ready-for-cutover" { + return nil, errors.New("invalid state phase") + } + names := map[string]bool{} + for _, snap := range s.Snapshots { + if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) { + return nil, errors.New("invalid snapshot state") + } + names[snap.Name] = true + } + if s.LiveSnapshot != "" { + confirmed := false + for _, snap := range s.Snapshots { + if snap.Name == s.LiveSnapshot && snap.Done { + confirmed = true + break + } + } + if !confirmed { + return nil, errors.New("live base must reference a completed snapshot") + } + } + if s.Phase == "ready-for-cutover" { + if len(s.Snapshots) == 0 { + return nil, errors.New("ready state has no snapshots") + } + for _, snap := range s.Snapshots { + if !snap.Done { + return nil, errors.New("ready state has incomplete snapshots") + } + } + if !s.Snapshots[len(s.Snapshots)-1].Final { + return nil, errors.New("ready state has no final snapshot") + } + } + if err := s.Config.Validate(); err != nil { + return nil, fmt.Errorf("state config: %w", err) + } + return &s, nil +} + +func SaveState(path string, s *State) error { + return atomicJSON(path, s) +} + +func atomicJSON(path string, v any) error { + dir := filepath.Dir(path) + f, err := os.CreateTemp(dir, ".cephmig-state-*") + if err != nil { + return err + } + name := f.Name() + defer os.Remove(name) + defer f.Close() + enc := json.NewEncoder(f) + enc.SetIndent("", " ") + if err = enc.Encode(v); err != nil { + return err + } + if err = f.Sync(); err != nil { + return err + } + if err = f.Close(); err != nil { + return err + } + if err = os.Rename(name, path); err != nil { + return err + } + d, err := os.Open(dir) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} + +func lockFile(path string) (*os.File, error) { + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) + 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("another process holds lock %s: %w", path, err) + } + return f, nil +} diff --git a/internal/migration/state_test.go b/internal/migration/state_test.go new file mode 100644 index 0000000..9f7d54d --- /dev/null +++ b/internal/migration/state_test.go @@ -0,0 +1,141 @@ +package migration + +import ( + "encoding/json" + "os" + "path/filepath" + "sync" + "testing" +) + +func testState() *State { + return &State{Version: stateVersion, ID: "1234567890abcdef1234567890abcdef", Config: testConfig(), Phase: "syncing"} +} +func TestStateAtomicAndPrivate(t *testing.T) { + p := filepath.Join(t.TempDir(), "state.json") + s := testState() + s.Notes = []string{SnapshotIdentityNote} + if err := SaveState(p, s); err != nil { + t.Fatal(err) + } + st, err := os.Stat(p) + if err != nil || st.Mode().Perm() != 0600 { + t.Fatalf("state permissions: %v, %v", st, err) + } + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 40; i++ { + if err := SaveState(p, s); err != nil { + t.Error(err) + return + } + } + }() + for i := 0; i < 100; i++ { + got, err := LoadState(p) + if err != nil { + t.Fatalf("reader observed partial state: %v", err) + } + if got.ID != s.ID { + t.Fatal("state identity changed") + } + if len(got.Notes) != 1 || got.Notes[0] != SnapshotIdentityNote { + t.Fatal("snapshot identity note was lost") + } + } + wg.Wait() +} +func TestStateRejectsCorruption(t *testing.T) { + for name, modify := range map[string]func(*State){ + "version": func(s *State) { s.Version++ }, + "short-id": func(s *State) { s.ID = "bad" }, + "phase": func(s *State) { s.Phase = "finished" }, + "ready-without-final": func(s *State) { s.Phase = "ready-for-cutover" }, + "duplicate": func(s *State) { s.Snapshots = []Snapshot{{Name: "a"}, {Name: "a"}} }, + "invalid-done": func(s *State) { s.Snapshots = []Snapshot{{Name: "a", Done: true}} }, + "missing-live-base": func(s *State) { s.LiveSnapshot = "missing" }, + "pending-live-base": func(s *State) { + s.Snapshots = []Snapshot{{Name: "pending"}} + s.LiveSnapshot = "pending" + }, + } { + t.Run(name, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "state.json") + s := testState() + modify(s) + if err := SaveState(p, s); err != nil { + t.Fatal(err) + } + if _, err := LoadState(p); err == nil { + t.Fatal("accepted corrupt state") + } + }) + } + p := filepath.Join(t.TempDir(), "state.json") + b, _ := json.Marshal(testState()) + if err := os.WriteFile(p, append(b, []byte(" {}")...), 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadState(p); err == nil { + t.Fatal("accepted trailing data") + } +} +func TestLockExclusionAndRelease(t *testing.T) { + p := filepath.Join(t.TempDir(), "lock") + first, err := lockFile(p) + if err != nil { + t.Fatal(err) + } + if second, err := lockFile(p); err == nil { + second.Close() + t.Fatal("second process acquired lock") + } + first.Close() + third, err := lockFile(p) + if err != nil { + t.Fatal(err) + } + 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") + if err := SaveState(real, testState()); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "link") + if err := os.Symlink(real, link); err != nil { + t.Fatal(err) + } + if _, err := LoadState(link); err == nil { + t.Fatal("followed state symlink") + } + if f, err := lockFile(link); err == nil { + f.Close() + t.Fatal("followed lock symlink") + } +} diff --git a/internal/storage/fs.go b/internal/storage/fs.go new file mode 100644 index 0000000..f51cea1 --- /dev/null +++ b/internal/storage/fs.go @@ -0,0 +1,79 @@ +// Package storage defines the native filesystem operations used by the copier. +package storage + +import ( + "io" + "time" +) + +type Node struct { + Mode uint32 + Inode, Version, Nlink, Size, Rdev uint64 + UID, GID uint32 + Mtime time.Time +} + +const ( + TypeMask uint32 = 0170000 + Regular uint32 = 0100000 + Directory uint32 = 0040000 + Symlink uint32 = 0120000 + FIFO uint32 = 0010000 + Socket uint32 = 0140000 + BlockDevice uint32 = 0060000 + CharDevice uint32 = 0020000 +) + +func (n Node) Kind() uint32 { return n.Mode & TypeMask } + +type Entry struct { + Name string + Node Node +} +type DirectoryStream interface { + Next() (*Entry, error) + Close() error +} +type File interface { + io.ReaderAt + io.WriterAt + io.Closer + Truncate(int64) error + Sync() error + Lock(uint64) error + PunchHole(int64, int64) error +} +type DiffStream interface { + Next() (string, error) + Close() error +} +type Extent struct{ Offset, Length uint64 } +type BlockStream interface { + Next() ([]Extent, error) + Close() error +} + +type FS interface { + Stat(string) (Node, error) // Never follows the final symlink. + Open(string, int, uint32) (File, error) + OpenDir(string) (DirectoryStream, error) + Mkdir(string, uint32) error + Unlink(string) error + Rmdir(string) error + Rename(string, string) error + Link(string, string) error + Symlink(string, string) error + Readlink(string) (string, error) + Mknod(string, uint32, uint64) error + SetAttr(string, Node) error // Numeric owner, mode and mtime; no symlink following. + ListXattr(string) ([]string, error) + GetXattr(string, string) ([]byte, error) + SetXattr(string, string, []byte) error + RemoveXattr(string, string) error + SnapDiff(string, string, string, string) (DiffStream, error) + BlockDiff(string, string, string, string) (BlockStream, error) + Sync() error + Close() error +} + +type Options struct{ Config, Keyring, User, Filesystem string } diff --git a/main.go b/main.go new file mode 100644 index 0000000..3bc8750 --- /dev/null +++ b/main.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "os/signal" + "syscall" + "time" + + "CephMig/internal/migration" +) + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := run(ctx, os.Args[1:], os.Stdout, os.Stderr); err != nil { + fmt.Fprintln(os.Stderr, "cephmig:", err) + os.Exit(1) + } +} + +const usage = "usage: cephmig doctor | inspect --config FILE | sync --config FILE --state FILE | finalize --config FILE --state FILE --writers-stopped | status --state FILE" + +func run(ctx context.Context, args []string, out, log io.Writer) error { + if len(args) == 0 { + return errors.New(usage) + } + if args[0] == "help" || args[0] == "--help" || args[0] == "-h" { + fmt.Fprintln(out, usage) + return nil + } + if args[0] == "doctor" { + if len(args) != 1 { + return errors.New(usage) + } + return doctor(ctx, out, log) + } + switch args[0] { + case "inspect", "sync", "finalize", "status": + default: + return errors.New(usage) + } + 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)") + 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) { + return nil + } + return err + } + if flags.NArg() != 0 { + return errors.New("unexpected positional arguments") + } + if args[0] == "status" { + if *statePath == "" { + return errors.New("--state is required") + } + s, err := migration.LoadState(*statePath) + if err != nil { + return err + } + return json.NewEncoder(out).Encode(s) + } + if *configPath == "" { + return errors.New("--config is required") + } + c, err := migration.ReadConfig(*configPath) + if err != nil { + return err + } + process := migration.Process{Stderr: log} + if args[0] != "inspect" && *statePath == "" { + return errors.New("--state is required") + } + if args[0] == "finalize" && !*stopped { + return errors.New("finalize requires --writers-stopped; stop and flush all application writers first") + } + if args[0] != "finalize" && *stopped { + return errors.New("--writers-stopped is only valid with finalize") + } + if c.Backend != "native" && args[0] != "inspect" { + 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 + } + defer closeEngine.Close() + if args[0] == "inspect" { + info, err := engine.Inspect(ctx, c) + if err != nil { + return err + } + return json.NewEncoder(out).Encode(info) + } + if err = engine.Sync(ctx, c, *statePath, args[0] == "finalize"); err != nil { + return err + } + s, err := migration.LoadState(*statePath) + if err != nil { + return err + } + return json.NewEncoder(out).Encode(s) +} + +func doctor(ctx context.Context, out, log io.Writer) error { + checks := []struct { + name string + args []string + }{ + {"go", []string{"version"}}, + {"docker", []string{"compose", "version"}}, + {"docker", []string{"info", "--format", "Docker server: {{.ServerVersion}}"}}, + } + for _, check := range checks { + checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + cmd := exec.CommandContext(checkCtx, check.name, check.args...) + cmd.Stdout, cmd.Stderr = out, log + err := cmd.Run() + cancel() + if err != nil { + return fmt.Errorf("check %s: %w", check.name, err) + } + } + return nil +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..fecc696 --- /dev/null +++ b/main_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" +) + +func TestCLIRejectsFinalizationWithoutWriterStop(t *testing.T) { + var out, log bytes.Buffer + err := run(context.Background(), []string{"finalize", "--config", "dev/migration.example.json", "--state", "/tmp/unused-state"}, &out, &log) + if err == nil || !strings.Contains(err.Error(), "--writers-stopped") { + t.Fatalf("got %v", err) + } +} +func TestCLIUsage(t *testing.T) { + var out, log bytes.Buffer + if err := run(context.Background(), []string{"--help"}, &out, &log); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "finalize") { + t.Fatal("help missing") + } + for _, args := range [][]string{nil, {"unknown"}, {"sync"}, {"status"}, {"sync", "--config", "x", "extra"}} { + if err := run(context.Background(), args, &out, &log); err == nil { + t.Fatalf("accepted %v", args) + } + } +}