From a6e7bbb17e0f6ab136451da82abc83f177e18b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Thu, 3 Dec 2026 20:37:20 +0100 Subject: [PATCH] feat: release the target claim in cleanup cleanup now deletes the claim file under .cephmig/claims as its last step, if it holds the job's own ID, and removes the claim directories when they are empty. A cleaned-up job is finished: cleanup and finalize do nothing and do not claim the target again, and sync is refused. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- dev/migration-test.sh | 1 + dev/native-fixture.py | 12 +++++- dev/native-test.sh | 3 ++ docs/migration.md | 10 ++++- internal/migration/access.go | 41 ++++++++++++++++++ internal/migration/cleanup.go | 34 ++++++++++++--- internal/migration/cleanup_test.go | 67 +++++++++++++++++++++++++++++ internal/migration/engine.go | 19 +++++++- internal/migration/native_access.go | 43 +++++++++++++++++- 10 files changed, 218 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 53badf9..1e27032 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ cephmig status --state FILE | `inspect` | checks source and target without changing anything | | `sync` | transfers the current state; can be repeated any number of times | | `finalize` | last round after the write stop, then ready for cutover | -| `cleanup` | deletes the snapshots cephmig created, at source and target | +| `cleanup` | deletes the snapshots cephmig created and its claim on the target | | `status` | prints the journal | All results are written to standard output as JSON. The state file must be diff --git a/dev/migration-test.sh b/dev/migration-test.sh index 426c9bb..f82aee7 100644 --- a/dev/migration-test.sh +++ b/dev/migration-test.sh @@ -215,6 +215,7 @@ for side in source_ceph target_ceph; do python3 -c 'import json,sys; print(" ".join(sorted(x["name"] for x in json.load(sys.stdin))))') test "$names" = "history-1 history-2" done +test ! -e "/mnt/target-fs/.cephmig/claims/$(python3 -c 'import hashlib,sys; print(hashlib.sha256("\0".join(sys.argv[1:]).encode()).hexdigest())' "$(target_ceph fsid)" cephfs migration "$name")" completed=true echo 'PASS: Go migration, historical snapshots, live catch-up, quotas, ACLs, xattrs, sparse-file contents, crash/error resume, exclusive target, finalization, snapshot cleanup' diff --git a/dev/native-fixture.py b/dev/native-fixture.py index bd7092e..01553b4 100644 --- a/dev/native-fixture.py +++ b/dev/native-fixture.py @@ -29,6 +29,11 @@ def snapshot(cluster, *args): return volume(cluster, "snapshot", *args) +def claim_path(): + claim = hashlib.sha256("\0".join([ceph("target", "fsid"), "cephfs", "migration", name]).encode()).hexdigest() + return "/mnt/target-fs/.cephmig/claims/" + claim + + def snapshot_names(cluster): return {x["name"] for x in json.loads(snapshot(cluster, "ls", "cephfs", name))} @@ -297,6 +302,7 @@ elif action == "cleaned": assert application == {"history-1", "history-2"}, application for c in ("source", "target"): assert snapshot_names(c) == application, (c, snapshot_names(c)) + assert not os.path.exists(claim_path()), "claim not released" print(json.dumps({"remaining_snapshots": sorted(application)})) elif action == "busy": # An unrelated source subvolume remains writable throughout migration/finalization. @@ -318,8 +324,10 @@ elif action == "cleanup": 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) + try: + os.unlink(claim_path()) + except FileNotFoundError: + pass # cleanup released it shutil.rmtree(work) else: raise ValueError(action) diff --git a/dev/native-test.sh b/dev/native-test.sh index 3eee12a..52c7d5b 100644 --- a/dev/native-test.sh +++ b/dev/native-test.sh @@ -94,5 +94,8 @@ SH "${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state" "${compose[@]}" exec -T native "$binary" cleanup --config "$config" --state "$state" fixture cleaned "$name" +# A finished job stays finished and does not claim the target again. +"${compose[@]}" exec -T native "$binary" finalize --config "$config" --state "$state" --writers-stopped +fixture cleaned "$name" completed=true echo 'PASS: native libcephfs without FUSE/rsync, blockdiff, snapshots, links, ACLs, xattrs, quotas, cancellation, SIGKILL resume, unrelated writers, finalization, snapshot cleanup' diff --git a/docs/migration.md b/docs/migration.md index 3c7def6..d162f00 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -137,7 +137,10 @@ the subvolume therefore see at most one migration snapshot at a time. after the job is `ready-for-cutover`. Afterwards the subvolumes hold only the snapshots of the application. Since the final snapshot is the immutable reference of the last round, run `cleanup` only after the cutover has been -checked. `cleanup` is idempotent. +checked. As its last step, `cleanup` deletes the target claim (see below) and +the directories `.cephmig/claims` and `.cephmig` if they are empty. The job +is then finished: `cleanup` and `finalize` do nothing more, and `sync` is +refused. `cleanup` is idempotent. Application snapshots are never deleted. The journal marks a snapshot as `removed` before deleting it, so an interrupted run completes the deletion @@ -370,7 +373,10 @@ space is required for it. Path depths beyond 128 directories are currently rejected. After a hard process abort during an index run, temporary index directories can remain; they are never used as checkpoints. -Journal and claim must be kept for resumption. An incomplete claim after a +Journal and claim must be kept for resumption; `cleanup` deletes the claim +only after the job is finished, and only if it holds the job's own ID. The +lock is an advisory CephFS `flock`: it excludes other cephmig processes, but +does not block any application. An incomplete claim after a crash during its very first creation is deliberately not repaired automatically; that requires checking the original job ID. diff --git a/internal/migration/access.go b/internal/migration/access.go index 015d59e..ac1d82d 100644 --- a/internal/migration/access.go +++ b/internal/migration/access.go @@ -2,10 +2,14 @@ package migration import ( "context" + "errors" "fmt" "io" + "os" "path" + "path/filepath" "strings" + "syscall" ) func nativePath(p string) (string, error) { @@ -24,6 +28,9 @@ type Access interface { Prepare(context.Context, string, string, string) error Apply(context.Context, string, string) error Verify(context.Context, string, string, string) error + // Release deletes the claim of job id, and the claim directories if + // they are empty. A missing claim is not an error. + Release(context.Context, Config, string, string) error } type mountedAccess struct{} @@ -38,6 +45,40 @@ func (mountedAccess) Claim(_ context.Context, c Config, fsid, id string) (io.Clo return claimTarget(c.Target.Mount, fsid, c.Target, id) } +func (mountedAccess) Release(_ context.Context, c Config, fsid, id string) error { + dir := filepath.Join(c.Target.Mount, ".cephmig", "claims") + p := filepath.Join(dir, claimName(fsid, c.Target)) + f, err := os.OpenFile(p, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + + b, err := io.ReadAll(io.LimitReader(f, 256)) + f.Close() + if err != nil { + return err + } + + if string(b) != id+"\n" { + return errors.New("target claim belongs to a different job; not removed") + } + + if err = os.Remove(p); err != nil { + return err + } + + for _, d := range []string{dir, filepath.Dir(dir)} { + if err := os.Remove(d); err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.ENOTEMPTY) && !errors.Is(err, syscall.EEXIST) { + return err + } + } + + return nil +} + func (mountedAccess) Prepare(ctx context.Context, src, dst, scratch string) error { if err := clearQuotas(ctx, dst); err != nil { return err diff --git a/internal/migration/cleanup.go b/internal/migration/cleanup.go index 01afa51..712a478 100644 --- a/internal/migration/cleanup.go +++ b/internal/migration/cleanup.go @@ -98,12 +98,16 @@ func (e Engine) Cleanup(ctx context.Context, c Config, statePath string) error { 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 + // A completed cleanup has released the claim; do not create it again. + if !cleanedUp(s) { + claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID) + if err != nil { + return err + } + + defer claim.Close() } - 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 = "" @@ -115,6 +119,26 @@ func (e Engine) Cleanup(ctx context.Context, c Config, statePath string) error { return err } - e.log("cleanup: removed cephmig snapshots at source and target; state=%s", abs) + // Last step: the job no longer protects the target. + if err = e.access().Release(ctx, c, s.TargetFSID, s.ID); err != nil { + return err + } + + e.log("cleanup: removed cephmig snapshots and the target claim; state=%s", abs) return nil } + +// cleanedUp reports whether Cleanup completed its snapshot removal for s. +func cleanedUp(s *State) bool { + if s.Phase != "ready-for-cutover" || s.LiveSnapshot != "" { + return false + } + + for _, snap := range s.Snapshots { + if snap.Owned && !snap.Removed { + return false + } + } + + return true +} diff --git a/internal/migration/cleanup_test.go b/internal/migration/cleanup_test.go index edad11c..38de46e 100644 --- a/internal/migration/cleanup_test.go +++ b/internal/migration/cleanup_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "io" + "os" "path/filepath" "slices" "testing" @@ -126,3 +127,69 @@ func TestStateRejectsInvalidRemoval(t *testing.T) { }) } } + +func TestReleaseRemovesOnlyOwnClaim(t *testing.T) { + root := t.TempDir() + c := testConfig() + c.Target.Mount = root + other := c + other.Target.Subvolume = "other" + for _, x := range []struct { + c Config + id string + }{{c, "job-one"}, {other, "job-two"}} { + f, err := claimTarget(root, "fsid", x.c.Target, x.id) + if err != nil { + t.Fatal(err) + } + + f.Close() + } + + access := mountedAccess{} + if err := access.Release(context.Background(), c, "fsid", "job-two"); err == nil { + t.Fatal("removed the claim of a different job") + } + + if err := access.Release(context.Background(), c, "fsid", "job-one"); err != nil { + t.Fatal(err) + } + + claims := filepath.Join(root, ".cephmig", "claims") + if _, err := os.Stat(filepath.Join(claims, claimName("fsid", c.Target))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("own claim still present: %v", err) + } + + if _, err := os.Stat(filepath.Join(claims, claimName("fsid", other.Target))); err != nil { + t.Fatalf("claim of another job removed: %v", err) + } + + if err := access.Release(context.Background(), other, "fsid", "job-two"); err != nil { + t.Fatal(err) + } + + if _, err := os.Stat(filepath.Join(root, ".cephmig")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("empty claim directories kept: %v", err) + } + + // Releasing again is a no-op. + if err := access.Release(context.Background(), c, "fsid", "job-one"); err != nil { + t.Fatal(err) + } +} + +func TestCleanedUp(t *testing.T) { + s := testState() + s.Phase = "ready-for-cutover" + s.Snapshots = []Snapshot{{Name: "app", Done: true}, {Name: "cephmig-x", Owned: true, Done: true, Final: true}} + s.LiveSnapshot = "cephmig-x" + if cleanedUp(s) { + t.Fatal("ready job reported as cleaned up") + } + + s.LiveSnapshot = "" + s.Snapshots[1].Removed = true + if !cleanedUp(s) { + t.Fatal("cleaned job not recognized") + } +} diff --git a/internal/migration/engine.go b/internal/migration/engine.go index 07e18de..da0ab4a 100644 --- a/internal/migration/engine.go +++ b/internal/migration/engine.go @@ -190,10 +190,16 @@ func emptyDirectory(path string) error { return nil } +// claimName is the file name of the claim for the target subvolume ep in +// the cluster fsid, below .cephmig/claims at the file system root. +func claimName(fsid string, ep Endpoint) string { + key := sha256.Sum256([]byte(fsid + "\x00" + ep.Filesystem + "\x00" + ep.Group + "\x00" + ep.Subvolume)) + return hex.EncodeToString(key[:]) +} + // claimTarget locks the target subvolume for the job id. The claim is outside // the migrated tree and survives deletion of the local journal. O_EXCL prevents two different jobs from adopting the same target. func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) { - 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 @@ -204,7 +210,7 @@ func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) { return nil, errors.New("claim directory contains symlinks") } - path := filepath.Join(dir, hex.EncodeToString(key[:])) + path := filepath.Join(dir, claimName(fsid, ep)) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) if err == nil { if _, err = f.WriteString(id + "\n"); err == nil { @@ -369,6 +375,15 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool return errors.New("config or cluster identity changed; refusing to reuse migration state") } + if cleanedUp(s) { + if final { + e.log("job is cleaned up; nothing to do") + return nil + } + + return errors.New("job is cleaned up; sync is no longer allowed") + } + claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID) if err != nil { return err diff --git a/internal/migration/native_access.go b/internal/migration/native_access.go index 4251932..cc058f6 100644 --- a/internal/migration/native_access.go +++ b/internal/migration/native_access.go @@ -118,8 +118,7 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io. } } - sum := sha256.Sum256([]byte(fsid + "\x00" + c.Target.Filesystem + "\x00" + c.Target.Group + "\x00" + c.Target.Subvolume)) - p := path.Join(current, hex.EncodeToString(sum[:])) + p := path.Join(current, claimName(fsid, c.Target)) 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 { @@ -171,6 +170,46 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io. return f, nil } +func (a nativeAccess) Release(ctx context.Context, c Config, fsid, id string) error { + if err := ctx.Err(); err != nil { + return err + } + + fs := a.backend.target + dir := "/.cephmig/claims" + p := path.Join(dir, claimName(fsid, c.Target)) + f, err := fs.Open(p, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0) + if errors.Is(err, syscall.ENOENT) { + return nil + } + if err != nil { + return err + } + + b := make([]byte, 256) + n, err := f.ReadAt(b, 0) + f.Close() + if err != nil && !errors.Is(err, io.EOF) { + return err + } + + if string(b[:n]) != id+"\n" { + return errors.New("native target claim belongs to a different job; not removed") + } + + if err = fs.Unlink(p); err != nil { + return err + } + + for _, d := range []string{dir, "/.cephmig"} { + if err := fs.Rmdir(d); err != nil && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.ENOTEMPTY) { + return err + } + } + + return nil +} + func (a nativeAccess) Prepare(ctx context.Context, _, target, _ string) error { return clearNativeQuotas(ctx, a.backend.target, target) }