From 907d4007655f5bb595e952f2851675df15c197e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Thu, 3 Dec 2026 19:52:13 +0100 Subject: [PATCH] feat: remove cephmig snapshots during sync and add cleanup command Users of a subvolume should not see traces of the migration. Each sync round now deletes the older cephmig-* round snapshots at source and target and keeps only the newest one as base for the next round. The new command `cephmig cleanup` deletes the remaining one after the cutover. Application snapshots are never touched. The journal marks a snapshot as removed before deleting it, so an interrupted run finishes the deletion instead of reporting a vanished snapshot. Co-Authored-By: Claude Opus 5.5 --- cmd/cephmig/main.go | 20 +++-- cmd/cephmig/main_test.go | 2 +- dev/migration-test.sh | 8 +- dev/native-fixture.py | 24 ++++++ dev/native-test.sh | 6 +- internal/migration/cleanup.go | 120 +++++++++++++++++++++++++++ internal/migration/cleanup_test.go | 128 +++++++++++++++++++++++++++++ internal/migration/engine.go | 9 ++ internal/migration/state.go | 24 +++--- 9 files changed, 322 insertions(+), 19 deletions(-) create mode 100644 internal/migration/cleanup.go create mode 100644 internal/migration/cleanup_test.go diff --git a/cmd/cephmig/main.go b/cmd/cephmig/main.go index 6788d25..982d12e 100644 --- a/cmd/cephmig/main.go +++ b/cmd/cephmig/main.go @@ -7,12 +7,15 @@ // cephmig inspect --config FILE // cephmig sync --config FILE --state FILE // cephmig finalize --config FILE --state FILE --writers-stopped +// cephmig cleanup --config FILE --state FILE // cephmig status --state FILE // // inspect checks both clusters without changing them. sync copies the // current state and may be repeated. finalize performs the last round after -// all writers are stopped and marks the job ready for cutover. status prints -// the migration journal. All results are written to standard output as JSON. +// all writers are stopped and marks the job ready for cutover. cleanup +// deletes the snapshots cephmig created, at source and target, once the +// cutover is done. status prints the migration journal. All results are +// written to standard output as JSON. package main import ( @@ -40,7 +43,7 @@ func main() { } } -const usage = "usage: cephmig doctor | inspect --config FILE | sync --config FILE --state FILE | finalize --config FILE --state FILE --writers-stopped | status --state FILE" +const usage = "usage: cephmig doctor | inspect --config FILE | sync --config FILE --state FILE | finalize --config FILE --state FILE --writers-stopped | cleanup --config FILE --state FILE | status --state FILE" func run(ctx context.Context, args []string, out, log io.Writer) error { if len(args) == 0 { @@ -61,7 +64,7 @@ func run(ctx context.Context, args []string, out, log io.Writer) error { } switch args[0] { - case "inspect", "sync", "finalize", "status": + case "inspect", "sync", "finalize", "cleanup", "status": default: return errors.New(usage) } @@ -118,7 +121,7 @@ func run(ctx context.Context, args []string, out, log io.Writer) error { return errors.New("--writers-stopped is only valid with finalize") } - if c.Backend != "native" && args[0] != "inspect" { + if c.Backend != "native" && args[0] != "inspect" && args[0] != "cleanup" { if _, err = exec.LookPath("rsync"); err != nil { return fmt.Errorf("rsync is required: %w", err) } @@ -139,7 +142,12 @@ func run(ctx context.Context, args []string, out, log io.Writer) error { return json.NewEncoder(out).Encode(info) } - if err = engine.Sync(ctx, c, *statePath, args[0] == "finalize"); err != nil { + if args[0] == "cleanup" { + err = engine.Cleanup(ctx, c, *statePath) + } else { + err = engine.Sync(ctx, c, *statePath, args[0] == "finalize") + } + if err != nil { return err } diff --git a/cmd/cephmig/main_test.go b/cmd/cephmig/main_test.go index 65be916..1c27962 100644 --- a/cmd/cephmig/main_test.go +++ b/cmd/cephmig/main_test.go @@ -25,7 +25,7 @@ func TestCLIUsage(t *testing.T) { t.Fatal("help missing") } - for _, args := range [][]string{nil, {"unknown"}, {"sync"}, {"status"}, {"sync", "--config", "x", "extra"}} { + for _, args := range [][]string{nil, {"unknown"}, {"sync"}, {"status"}, {"cleanup"}, {"cleanup", "--config", "../../dev/migration.example.json"}, {"sync", "--config", "x", "extra"}} { if err := run(context.Background(), args, &out, &log); err == nil { t.Fatalf("accepted %v", args) } diff --git a/dev/migration-test.sh b/dev/migration-test.sh index 38a3998..426c9bb 100644 --- a/dev/migration-test.sh +++ b/dev/migration-test.sh @@ -209,6 +209,12 @@ for snap in history-1 history-2; do test "$a" = "$b" done python3 /lab/snapshot-identity.py --config "$config" --snapshot history-1 +"$binary" cleanup --config "$config" --state "$state" > "$work/cleaned.json" +for side in source_ceph target_ceph; do + names=$("$side" fs subvolume snapshot ls cephfs "$name" --group_name migration | + python3 -c 'import json,sys; print(" ".join(sorted(x["name"] for x in json.load(sys.stdin))))') + test "$names" = "history-1 history-2" +done completed=true -echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization' +echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization, snapshot cleanup' diff --git a/dev/native-fixture.py b/dev/native-fixture.py index 61f286e..87a0608 100644 --- a/dev/native-fixture.py +++ b/dev/native-fixture.py @@ -29,6 +29,10 @@ def snapshot(cluster, *args): return volume(cluster, "snapshot", *args) +def snapshot_names(cluster): + return {x["name"] for x in json.loads(snapshot(cluster, "ls", "cephfs", name))} + + def acl(): entries = [(1, 6, 0xffffffff), (2, 4, 12345), (4, 0, 0xffffffff), (16, 4, 0xffffffff), (32, 0, 0xffffffff)] @@ -247,8 +251,16 @@ elif action in ("verify", "final"): compare(roots["source"], roots["target"]) compare_times(roots["source"], roots["target"], atime=False) s = json.load(open(state)) + listed = {c: snapshot_names(c) for c in ("source", "target")} + # Only the newest round snapshot remains as base; older ones are removed. + kept = [x["name"] for x in s["snapshots"] if x["owned"] and not x.get("removed")] + assert kept == [s["live_snapshot"]], (kept, s["live_snapshot"]) + for c in ("source", "target"): + assert {n for n in listed[c] if n.startswith("cephmig-")} == set(kept), (c, listed[c]) for snap in s["snapshots"]: assert snap["done"], snap + if snap.get("removed"): + continue a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath", "cephfs", name, snap["name"], "migration") for c in ("source", "target")] compare(a, b) @@ -264,6 +276,18 @@ elif action in ("verify", "final"): assert s["phase"] == "ready-for-cutover" and len(s["snapshots"]) == 5, s assert s["snapshots"][-1]["transfer"]["bytes_copied"] == 0, s["snapshots"][-1] print(json.dumps({"phase": s["phase"], "rounds": len(s["snapshots"]), "history_2": h2})) +elif action == "cleaned": + roots = json.load(open(fixture)) + compare(roots["source"], roots["target"]) + compare_times(roots["source"], roots["target"], atime=False) + s = json.load(open(state)) + assert s["phase"] == "ready-for-cutover" and not s.get("live_snapshot"), s + assert all(x.get("removed") for x in s["snapshots"] if x["owned"]), s + application = {x["name"] for x in s["snapshots"] if not x["owned"]} + assert application == {"history-1", "history-2"}, application + for c in ("source", "target"): + assert snapshot_names(c) == application, (c, snapshot_names(c)) + print(json.dumps({"remaining_snapshots": sorted(application)})) elif action == "busy": # An unrelated source subvolume remains writable throughout migration/finalization. p = "/mnt/source/" + name diff --git a/dev/native-test.sh b/dev/native-test.sh index 160537f..3eee12a 100644 --- a/dev/native-test.sh +++ b/dev/native-test.sh @@ -90,5 +90,9 @@ assert json.loads((p/"before.json").read_text()) == json.loads((p/"idempotent.js assert int((p/"busy-count").read_text()) > int((p/"busy-before-final").read_text()) > 20 PY SH +# Remove all cephmig snapshots; a second run must find nothing left to do. +"${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state" +"${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state" +fixture cleaned "$name" completed=true -echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization' +echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization, snapshot cleanup' diff --git a/internal/migration/cleanup.go b/internal/migration/cleanup.go new file mode 100644 index 0000000..01afa51 --- /dev/null +++ b/internal/migration/cleanup.go @@ -0,0 +1,120 @@ +package migration + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" +) + +// removeOwnedSnapshots deletes the completed snapshots that cephmig created +// itself, except keep, at source and target. Snapshots of the application +// are never touched. +// +// Every snapshot is first marked Removed in the journal and deleted after +// that, so an interrupted run finishes the deletion next time instead of +// reporting a vanished snapshot. +func removeOwnedSnapshots(ctx context.Context, src, dst ceph, statePath string, s *State, keep string) error { + marked := false + for i := range s.Snapshots { + snap := &s.Snapshots[i] + if snap.Owned && snap.Done && !snap.Removed && snap.Name != keep { + snap.Removed = true + marked = true + } + } + + if marked { + if err := SaveState(statePath, s); err != nil { + return err + } + } + + for _, side := range []ceph{dst, src} { + names, err := side.names(ctx) + if err != nil { + return err + } + + for _, snap := range s.Snapshots { + if !snap.Removed || !slices.Contains(names, snap.Name) { + continue + } + + if _, err = side.snap(ctx, "rm", snap.Name); err != nil { + return err + } + } + } + + return nil +} + +// Cleanup deletes all snapshots cephmig created, at source and target, after +// the job is ready for cutover. Afterwards the subvolumes hold only the +// snapshots of the application. This includes the final round snapshot, so +// run it only after the cutover has been checked. +func (e Engine) Cleanup(ctx context.Context, c Config, statePath string) error { + if err := c.Validate(); err != nil { + return err + } + + if e.Exec == nil { + return errors.New("missing executor") + } + + abs, err := filepath.Abs(statePath) + if err != nil { + return err + } + + lock, err := lockFile(abs + ".lock") + if err != nil { + return err + } + + defer lock.Close() + s, err := LoadState(abs) + if errors.Is(err, os.ErrNotExist) { + return errors.New("no migration state; nothing to clean up") + } + if err != nil { + return err + } + + if s.Phase != "ready-for-cutover" { + return fmt.Errorf("cleanup requires phase ready-for-cutover, not %q; run finalize first", s.Phase) + } + + inspection, err := e.Inspect(ctx, c) + 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 use migration state") + } + + claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID) + if err != nil { + return err + } + + defer claim.Close() + native := c.Backend == "native" + src, dst := ceph{endpoint: c.Source, exec: e.Exec, native: native}, ceph{endpoint: c.Target, exec: e.Exec, native: native} + s.LiveSnapshot = "" + if err = removeOwnedSnapshots(ctx, src, dst, abs, s, ""); err != nil { + return err + } + + if err = SaveState(abs, s); err != nil { + return err + } + + e.log("cleanup: removed cephmig snapshots at source and target; state=%s", abs) + return nil +} diff --git a/internal/migration/cleanup_test.go b/internal/migration/cleanup_test.go new file mode 100644 index 0000000..edad11c --- /dev/null +++ b/internal/migration/cleanup_test.go @@ -0,0 +1,128 @@ +package migration + +import ( + "context" + "encoding/json" + "errors" + "io" + "path/filepath" + "slices" + "testing" +) + +// snapshotCeph fakes "ceph fs subvolume snapshot ls|rm" for two clusters, +// told apart by the --conf argument. +type snapshotCeph struct { + snaps map[string][]string + failRm string + removed []string +} + +func (f *snapshotCeph) Exec(_ context.Context, out io.Writer, _ string, args ...string) error { + conf := args[1] + i := slices.Index(args, "snapshot") + switch args[i+1] { + case "ls": + var list []map[string]string + for _, n := range f.snaps[conf] { + list = append(list, map[string]string{"name": n}) + } + + return json.NewEncoder(out).Encode(list) + case "rm": + name := args[i+4] + if name == f.failRm { + return errors.New("injected failure") + } + + f.snaps[conf] = slices.DeleteFunc(f.snaps[conf], func(n string) bool { return n == name }) + f.removed = append(f.removed, conf+":"+name) + return nil + } + + return errors.New("unexpected command") +} + +func TestRemoveOwnedSnapshots(t *testing.T) { + all := []string{"app-1", "cephmig-a", "cephmig-b", "cephmig-c"} + newState := func() *State { + s := testState() + for _, n := range all { + s.Snapshots = append(s.Snapshots, Snapshot{Name: n, Owned: n != "app-1", Done: true, + CreatedAt: "2026-01-01 00:00:00", TargetCreatedAt: "2026-01-01 00:00:01"}) + } + + s.LiveSnapshot = "cephmig-c" + return s + } + + statePath := filepath.Join(t.TempDir(), "state.json") + f := &snapshotCeph{snaps: map[string][]string{"src.conf": slices.Clone(all), "dst.conf": slices.Clone(all)}} + src := ceph{endpoint: Endpoint{Config: "src.conf", Filesystem: "fs", Subvolume: "v"}, exec: f} + dst := ceph{endpoint: Endpoint{Config: "dst.conf", Filesystem: "fs", Subvolume: "v"}, exec: f} + + // An interrupted run leaves the journal marked, and the retry finishes. + s := newState() + f.failRm = "cephmig-b" + if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, s, s.LiveSnapshot); err == nil { + t.Fatal("injected failure not reported") + } + + loaded, err := LoadState(statePath) + if err != nil { + t.Fatal(err) + } + + if !loaded.Snapshots[1].Removed || !loaded.Snapshots[2].Removed || loaded.Snapshots[3].Removed || loaded.Snapshots[0].Removed { + t.Fatalf("journal marks: %+v", loaded.Snapshots) + } + + f.failRm = "" + if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, loaded, loaded.LiveSnapshot); err != nil { + t.Fatal(err) + } + + for conf, names := range f.snaps { + if !slices.Equal(names, []string{"app-1", "cephmig-c"}) { + t.Fatalf("%s keeps %v", conf, names) + } + } + + // Cleanup removes the base too, but never application snapshots. + loaded.LiveSnapshot = "" + if err := removeOwnedSnapshots(context.Background(), src, dst, statePath, loaded, ""); err != nil { + t.Fatal(err) + } + + for conf, names := range f.snaps { + if !slices.Equal(names, []string{"app-1"}) { + t.Fatalf("%s keeps %v", conf, names) + } + } + + if _, err := LoadState(statePath); err != nil { + t.Fatal(err) + } +} + +func TestStateRejectsInvalidRemoval(t *testing.T) { + done := Snapshot{Name: "a", Owned: true, Done: true, Removed: true, CreatedAt: "x", TargetCreatedAt: "y"} + for name, modify := range map[string]func(*State){ + "application snapshot": func(s *State) { d := done; d.Owned = false; s.Snapshots = []Snapshot{d} }, + "incomplete": func(s *State) { s.Snapshots = []Snapshot{{Name: "a", Owned: true, Removed: true}} }, + "removed live base": func(s *State) { s.Snapshots = []Snapshot{done}; s.LiveSnapshot = "a" }, + } { + 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 invalid removal") + } + }) + } +} diff --git a/internal/migration/engine.go b/internal/migration/engine.go index 026ebd2..13f7d0f 100644 --- a/internal/migration/engine.go +++ b/internal/migration/engine.go @@ -450,6 +450,10 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool // Resume all intent records before capturing another live snapshot. for i := range s.Snapshots { + if s.Snapshots[i].Removed { + continue + } + if s.Snapshots[i].Done { snap := &s.Snapshots[i] if !slices.Contains(targetNames, snap.Name) { @@ -504,6 +508,11 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool return err } + // Only the newest round snapshot serves as base for the next round. + if err = removeOwnedSnapshots(ctx, src, dst, abs, s, s.LiveSnapshot); err != nil { + return err + } + metadata, err := src.metadata(ctx, "") if err != nil { return err diff --git a/internal/migration/state.go b/internal/migration/state.go index 46f0508..62a4b88 100644 --- a/internal/migration/state.go +++ b/internal/migration/state.go @@ -16,14 +16,17 @@ const stateVersion = 1 // Snapshot is the journal record of one source snapshot and its transfer // to the target. 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"` + 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"` + // Removed marks an owned snapshot that is deleted, or is about to be + // deleted, at source and target. + Removed bool `json:"removed,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + Stats *TransferStats `json:"transfer,omitempty"` } // State is the persistent migration journal. It is written atomically @@ -73,7 +76,8 @@ func LoadState(path string) (*State, error) { names := map[string]bool{} for _, snap := range s.Snapshots { - if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) { + if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) || + (snap.Removed && (!snap.Owned || !snap.Done)) { return nil, errors.New("invalid snapshot state") } @@ -83,7 +87,7 @@ func LoadState(path string) (*State, error) { if s.LiveSnapshot != "" { confirmed := false for _, snap := range s.Snapshots { - if snap.Name == s.LiveSnapshot && snap.Done { + if snap.Name == s.LiveSnapshot && snap.Done && !snap.Removed { confirmed = true break }