package migration import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "reflect" "slices" "sort" "strings" "syscall" "time" ) // Engine runs the snapshot-based migration workflow. Transport moves the // data; Access, if nil, defaults to mounted filesystem access. 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"` } // Inspection is the result of Engine.Inspect. 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"` } // SnapshotIdentityNote documents the accepted deviation that native // snapshot identities are not preserved at the target. 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 } // 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) { dir := filepath.Join(root, ".cephmig", "claims") if err := privateDirectories(dir); err != nil { return nil, err } resolved, err := filepath.EvalSymlinks(dir) if err != nil || resolved != dir { return nil, errors.New("claim directory contains symlinks") } path := filepath.Join(dir, claimName(fsid, ep)) f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) if err == nil { if _, err = f.WriteString(id + "\n"); err == nil { err = f.Sync() } if closeErr := f.Close(); err == nil { err = closeErr } if err != nil { return nil, err } } else if !errors.Is(err, os.ErrExist) { return nil, err } st, err := os.Lstat(path) if err != nil { return nil, err } if !st.Mode().IsRegular() { return nil, errors.New("target claim is not a regular file") } f, err = os.OpenFile(path, os.O_RDWR|syscall.O_NOFOLLOW, 0) if err != nil { return nil, err } if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { f.Close() return nil, fmt.Errorf("target is being migrated by another process: %w", err) } b, err := io.ReadAll(io.LimitReader(f, 256)) if err != nil || string(b) != id+"\n" { f.Close() return nil, errors.New("target is claimed by a different job or claim is incomplete; preserve the original state file") } return f, nil } func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, error) { var s Snapshot s.Name = name 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 } // Sync performs one migration round: it resumes unfinished snapshots, // transfers newly discovered ones and then a fresh snapshot of the live // subvolume. With final set, writers must be stopped; Sync then verifies // the complete inventory and marks the job ready for cutover. 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") } 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 } defer claim.Close() s.Config = c if !slices.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].Removed { continue } if s.Snapshots[i].Done { snap := &s.Snapshots[i] if !slices.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 slices.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 } // 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 } 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 a.FullScan, b.FullScan = false, false 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 !slices.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 := slices.Contains(targetNames, snap.Name) if isNative { // Only intermediate round snapshots may skip unchanged subtrees. They are // deleted later, and finalize scans everything again. round := Round{SourcePath: from, TargetPath: target, Name: snap.Name, StatePath: statePath, BaseName: s.LiveSnapshot, SkipUnchanged: snap.Owned && !snap.Final && !s.Config.FullScan} 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 }