Intermediate rounds skipped a directory when its inode version and its ceph.dir.rctime matched the previous round. In the 10,000-file lab test a round snapshot taken seconds after changes skipped tree/ with about 250 changed files in its subdirectories: the inode version of tree/ changes only with its own entries, and Ceph had not yet propagated the rctime of the grandchildren. The target snapshot of that round was incomplete, and its verification skipped the same subtrees; only finalize closed the gap. Every round now scans all metadata again. Base index entries that the old version marked carried are never trusted, so such files are copied in full in the next round. The smallfiles verification now checks only snapshots that sync did not remove. BREAKING CHANGE: the configuration field "full_scan" and the transfer statistic "skipped_subtrees" are removed; a configuration with "full_scan" is rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
586 lines
14 KiB
Go
586 lines
14 KiB
Go
package migration
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Engine runs the snapshot-based migration workflow. Transport moves the
|
|
// data; Access reaches both clusters for everything else. Both are required.
|
|
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 newID() (string, error) {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return hex.EncodeToString(b[:]), 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[:])
|
|
}
|
|
|
|
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 || e.Access == nil {
|
|
return errors.New("missing executor, transport or access")
|
|
}
|
|
|
|
abs, err := filepath.Abs(statePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
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}, ceph{endpoint: c.Target, exec: e.Exec}
|
|
s, err := LoadState(abs)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
if err = e.access().Empty(ctx, inspection.TargetPath); err != nil {
|
|
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
|
|
// "" and "native" select the same backend.
|
|
a.Backend, b.Backend = "", ""
|
|
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 {
|
|
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
|
|
}
|