diff --git a/dev/native-fixture.py b/dev/native-fixture.py index 87a0608..bd7092e 100644 --- a/dev/native-fixture.py +++ b/dev/native-fixture.py @@ -70,6 +70,12 @@ def populate(root): os.setxattr(root + "/d", "ceph.quota.max_bytes", b"33554432") os.setxattr(root + "/d", "ceph.quota.max_files", b"1000") os.setxattr(root, "ceph.quota.max_bytes", b"268435456") + # A subtree no round changes; sync rounds skip it by its rctime. + os.makedirs(root + "/static/deep/deeper") + pathlib.Path(root + "/static/deep/deeper/file").write_bytes(b"static" * 1000) + os.link(root + "/static/deep/deeper/file", root + "/static/alias") + os.setxattr(root + "/static/deep", "user.static", b"kept") + os.symlink("deep/deeper/file", root + "/static/link") def edit_large(root, offset, data): @@ -267,6 +273,10 @@ elif action in ("verify", "final"): assert compare_times(a, b, atime=True) > 10 assert snapshot("source", "metadata", "ls", "cephfs", name, snap["name"]) == snapshot( "target", "metadata", "ls", "cephfs", name, snap["name"]) + owned = [x for x in s["snapshots"] if x["owned"]] + # Intermediate rounds skip the untouched subtree; finalize never skips. + assert all(x["transfer"].get("skipped_subtrees", 0) >= 1 for x in owned if not x.get("final")), owned + assert all(x["transfer"].get("skipped_subtrees", 0) == 0 for x in owned if x.get("final")), owned h2 = next(x for x in s["snapshots"] if x["name"] == "history-2")["transfer"] assert h2["mode"] == "snapdiff" and h2["blockdiff_files"] > 0, h2 assert h2["bytes_copied"] < 64 << 20, h2 diff --git a/internal/migration/access.go b/internal/migration/access.go index f8d7fcd..015d59e 100644 --- a/internal/migration/access.go +++ b/internal/migration/access.go @@ -74,11 +74,13 @@ func (e Engine) Inspect(ctx context.Context, c Config) (*Inspection, error) { // Round describes one snapshot transfer handed to a RoundTransport. // BaseName and BaseSourcePath name the last completed snapshot, if any, -// which allows an incremental transfer. +// which allows an incremental transfer. SkipUnchanged permits skipping +// subtrees whose recursive ctime did not change since the base. type Round struct { SourcePath, TargetPath string BaseName, BaseSourcePath string Name, StatePath string + SkipUnchanged bool } // RoundTransport is a Transport that keeps state across a snapshot round, @@ -100,6 +102,7 @@ type TransferStats struct { BytesVerified int64 `json:"bytes_verified"` BlockDiffFiles int64 `json:"blockdiff_files"` SnapDiffEntries int64 `json:"snapdiff_entries"` + SkippedSubtrees int64 `json:"skipped_subtrees,omitempty"` } // NewEngine returns an Engine for c.Backend and a Closer that releases its diff --git a/internal/migration/config.go b/internal/migration/config.go index c8d8f66..1ba93e2 100644 --- a/internal/migration/config.go +++ b/internal/migration/config.go @@ -31,6 +31,10 @@ type Config struct { Source Endpoint `json:"source"` Target Endpoint `json:"target"` BandwidthKiB int64 `json:"bandwidth_kib,omitempty"` + + // FullScan disables the rctime shortcut of the native backend, so every + // round reads all metadata. finalize always does. + FullScan bool `json:"full_scan,omitempty"` } // ReadConfig reads exactly one JSON object from the regular file at path, diff --git a/internal/migration/engine.go b/internal/migration/engine.go index 13f7d0f..07e18de 100644 --- a/internal/migration/engine.go +++ b/internal/migration/engine.go @@ -574,6 +574,7 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool 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) } @@ -622,7 +623,10 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s 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} + // 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 { diff --git a/internal/migration/native_data.go b/internal/migration/native_data.go index 5e09d78..7df0846 100644 --- a/internal/migration/native_data.go +++ b/internal/migration/native_data.go @@ -94,7 +94,9 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error if changed { usedBlockDiff := false - if trusted && job.node.Size >= nativeBlockThreshold { + // A carried entry describes an older round than the base snapshot, so + // a block delta against the base could miss changes. + if trusted && !previous.Carried && 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) @@ -377,6 +379,10 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { return err } + if n.Kind() == storage.Directory { + return b.skipped(rel) + } + if n.Kind() != storage.Directory { if n.Nlink > 1 { same, err := index.observe("source", nodeKey(n.Inode), nodeKey(target.Inode)) @@ -492,7 +498,7 @@ func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error return fmt.Errorf("unexpected native target entry %s", rel) } - return nil + return b.skipped(rel) }) } diff --git a/internal/migration/native_helpers.go b/internal/migration/native_helpers.go index 88dade1..eda8b46 100644 --- a/internal/migration/native_helpers.go +++ b/internal/migration/native_helpers.go @@ -14,6 +14,10 @@ import ( "git.zb-server.de/Sebi/CephfsMig/internal/storage" ) +// errSkipSubtree, returned by a walkNative visitor for a directory, skips +// the entries below it. +var errSkipSubtree = errors.New("skip subtree") + 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 { @@ -25,7 +29,9 @@ func walkNative(ctx context.Context, fs storage.FS, root string, visit func(stri return errors.New("native directory depth exceeds 128") } - if err := visit(p, n, depth); err != nil { + if err := visit(p, n, depth); errors.Is(err, errSkipSubtree) && n.Kind() == storage.Directory { + return nil + } else if err != nil { return err } diff --git a/internal/migration/native_index.go b/internal/migration/native_index.go index 9e54487..54d4631 100644 --- a/internal/migration/native_index.go +++ b/internal/migration/native_index.go @@ -11,30 +11,45 @@ import ( bolt "go.etcd.io/bbolt" ) -var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete", "relinked"} +var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete", "relinked", "subtrees"} type nativeIndex struct { db *bolt.DB path string } -type baseEntry struct{ Inode, Version, Size, TargetInode uint64 } +// baseEntry is the inventory record of one source path. Carried marks an +// entry taken over unexamined from the previous base because its subtree was +// skipped: it still describes the state of an older round, so it must not +// serve as base for a block delta. +type baseEntry struct { + Inode, Version, Size, TargetInode uint64 + Carried bool +} func encodeEntry(e baseEntry) []byte { - b := make([]byte, 32) + b := make([]byte, 33) 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) + if e.Carried { + b[32] = 1 + } + return b } +// decodeEntry also accepts the 32-byte records written before Carried existed. func decodeEntry(b []byte) (baseEntry, bool) { - if len(b) != 32 { + if len(b) != 32 && (len(b) != 33 || b[32] > 1) { 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 + e := baseEntry{Inode: binary.BigEndian.Uint64(b), Version: binary.BigEndian.Uint64(b[8:]), + Size: binary.BigEndian.Uint64(b[16:]), TargetInode: binary.BigEndian.Uint64(b[24:])} + e.Carried = len(b) == 33 && b[32] == 1 + return e, true } func createNativeIndex(parent string) (*nativeIndex, error) { @@ -148,6 +163,68 @@ func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error { return x.put("paths", []byte(rel), encodeEntry(entry)) } +// carry copies the inventory of the subtree rel, including rel itself, from +// base and marks every entry Carried. It writes in bounded transactions. +func (x *nativeIndex) carry(base *nativeIndex, rel string) error { + type record struct{ k, v []byte } + prefix := []byte(rel + "/") + next := []byte(rel) + for next != nil { + var batch []record + err := base.db.View(func(tx *bolt.Tx) error { + c := tx.Bucket([]byte("paths")).Cursor() + k, v := c.Seek(next) + next = nil + for ; k != nil && len(batch) < 4096; k, v = c.Next() { + if string(k) != rel && !bytes.HasPrefix(k, prefix) { + if string(k) > rel && bytes.Compare(k, prefix) < 0 { + // Siblings such as "a b" sort between "a" and "a/". + k, v = c.Seek(prefix) + if k == nil || !bytes.HasPrefix(k, prefix) { + return nil + } + } else { + return nil + } + } + + e, ok := decodeEntry(v) + if !ok { + return errors.New("invalid base inventory entry") + } + + e.Carried = true + batch = append(batch, record{bytes.Clone(k), encodeEntry(e)}) + } + + if k != nil && bytes.HasPrefix(k, prefix) { + next = bytes.Clone(k) + } + + return nil + }) + if err != nil { + return err + } + + err = x.db.Update(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("paths")) + for _, r := range batch { + if err := b.Put(r.k, r.v); err != nil { + return err + } + } + + return nil + }) + if err != nil { + return err + } + } + + return nil +} + func (x *nativeIndex) requireInventory() error { complete, err := x.get("meta", []byte("inventory_complete")) if err != nil { diff --git a/internal/migration/native_skip_test.go b/internal/migration/native_skip_test.go new file mode 100644 index 0000000..b63b969 --- /dev/null +++ b/internal/migration/native_skip_test.go @@ -0,0 +1,128 @@ +package migration + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" + + "git.zb-server.de/Sebi/CephfsMig/internal/storage" +) + +func TestEntryEncodingCarriedAndLegacy(t *testing.T) { + e := baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4, Carried: true} + got, ok := decodeEntry(encodeEntry(e)) + if !ok || got != e { + t.Fatalf("round trip: %+v %v", got, ok) + } + + legacy := encodeEntry(baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4})[:32] + if got, ok := decodeEntry(legacy); !ok || got.Carried || got.TargetInode != 4 { + t.Fatalf("legacy record: %+v %v", got, ok) + } + + for _, bad := range [][]byte{make([]byte, 31), append(make([]byte, 32), 2)} { + if _, ok := decodeEntry(bad); ok { + t.Fatalf("accepted %d-byte record", len(bad)) + } + } +} + +func TestCarryCopiesExactlyTheSubtree(t *testing.T) { + dir := t.TempDir() + base, err := createNativeIndex(dir) + if err != nil { + t.Fatal(err) + } + + defer base.close() + // "a b", "a-x" and "a.x" sort between "a" and "a/"; "ab" sorts after it. + paths := []string{".", "a", "a b", "a b/x", "a-x", "a.x", "a/1", "a/2/3", "ab", "b"} + for i := 0; i < 5000; i++ { + paths = append(paths, filepath.Join("a/many", string(rune('a'+i%26)), string(rune('a'+i/26%26)), string(rune('a'+i/676)))) + } + + for i, p := range paths { + if err := base.put("paths", []byte(p), encodeEntry(baseEntry{Inode: uint64(i + 1), TargetInode: 9})); err != nil { + t.Fatal(err) + } + } + + pending, err := createNativeIndex(dir) + if err != nil { + t.Fatal(err) + } + + defer pending.close() + if err := pending.carry(base, "a"); err != nil { + t.Fatal(err) + } + + var carried []string + if err := pending.each("paths", false, func(k, v []byte) error { + e, ok := decodeEntry(v) + if !ok || !e.Carried || e.TargetInode != 9 { + t.Fatalf("entry %s: %+v", k, e) + } + + carried = append(carried, string(k)) + return nil + }); err != nil { + t.Fatal(err) + } + + var want []string + for _, p := range paths { + if p == "a" || len(p) > 2 && p[:2] == "a/" { + want = append(want, p) + } + } + + slices.Sort(want) + want = slices.Compact(want) + if !slices.Equal(carried, want) { + t.Fatalf("carried %d entries, want %d; first difference near %v", len(carried), len(want), carried[:min(5, len(carried))]) + } +} + +func TestWalkNativeSkipsSubtree(t *testing.T) { + root := t.TempDir() + for _, p := range []string{"keep/x", "skip/deep/y", "z"} { + if err := os.MkdirAll(filepath.Join(root, filepath.Dir(p)), 0700); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(root, p), nil, 0600); err != nil { + t.Fatal(err) + } + } + + var seen []string + err := walkNative(context.Background(), inventoryTargetFS{}, root, func(p string, _ storage.Node, _ int) error { + rel, _ := filepath.Rel(root, p) + seen = append(seen, rel) + if rel == "skip" { + return errSkipSubtree + } + + return nil + }) + if err != nil { + t.Fatal(err) + } + + slices.Sort(seen) + if !slices.Equal(seen, []string{".", "keep", "keep/x", "skip", "z"}) { + t.Fatalf("visited %v", seen) + } +} + +func TestFullScanMayChangeOnResume(t *testing.T) { + a := testConfig() + b := a + b.FullScan = true + if !sameMigrationIdentity(a, b) { + t.Fatal("full_scan must not change the migration identity") + } +} diff --git a/internal/migration/native_transport.go b/internal/migration/native_transport.go index 7d8e4c8..3032d1e 100644 --- a/internal/migration/native_transport.go +++ b/internal/migration/native_transport.go @@ -1,6 +1,7 @@ package migration import ( + "bytes" "context" "encoding/binary" "errors" @@ -48,6 +49,7 @@ type nativeTransport struct { visited, copied, written atomic.Int64 checked, blockFiles atomic.Int64 diffEntries, rateBytes atomic.Int64 + skippedSubtrees atomic.Int64 } func (b *nativeTransport) Close() error { @@ -120,6 +122,7 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error { b.blockFiles.Store(0) b.diffEntries.Store(0) b.rateBytes.Store(0) + b.skippedSubtrees.Store(0) b.started = time.Now() marker := "/.snap/" + r.Name at := strings.LastIndex(r.SourcePath, marker) @@ -215,6 +218,20 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin } if n.Kind() == storage.Directory { + sourceRel, err := relativeNative(b.round.SourcePath, child) + if err != nil { + return err + } + + unchanged, err := b.subtreeUnchanged(sourceRel, n) + if err != nil { + return err + } + + if unchanged { + continue + } + if err = b.collectChanges(ctx, path.Join(rel, name), child, depth+1); err != nil { return err } @@ -294,6 +311,22 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error { } target := path.Join(to, rel) + if n.Kind() == storage.Directory { + unchanged, err := b.subtreeUnchanged(rel, n) + if err != nil { + return err + } + + if unchanged { + b.skippedSubtrees.Add(1) + if err = b.pending.carry(b.base, rel); err != nil { + return err + } + + return errSkipSubtree + } + } + // 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{ @@ -502,7 +535,7 @@ func (b *nativeTransport) prune(ctx context.Context, from, to string) error { } if present { - return nil + return b.skipped(rel) } // Removing one name of a hardlinked inode resets its ctime; the @@ -595,7 +628,118 @@ func (b *nativeTransport) Statistics() TransferStats { 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()} + BlockDiffFiles: b.blockFiles.Load(), SnapDiffEntries: b.diffEntries.Load(), + SkippedSubtrees: b.skippedSubtrees.Load()} +} + +// subtreeUnchanged reports whether the source directory rel, with node n, +// may be skipped in this round. That requires a round that permits it, a +// confirmed base, the same directory inode and inode version in the base +// snapshot, an equal ceph.dir.rctime there, a base inventory entry and a +// target directory. +// +// Changes deeper in the subtree are seen only through the rctime, which Ceph +// propagates with a delay, and through client clocks. A round may therefore +// miss them; the next round or the full scan of finalize catches them, and +// carried entries never serve as base for a block delta. The result is +// cached per round. +func (b *nativeTransport) subtreeUnchanged(rel string, n storage.Node) (bool, error) { + if !b.round.SkipUnchanged || !b.delta || rel == "." { + return false, nil + } + + cached, err := b.pending.get("subtrees", []byte(rel)) + if err != nil || cached != nil { + return len(cached) == 1 && cached[0] == 1, err + } + + unchanged, err := b.compareSubtree(rel, n) + if err != nil { + return false, err + } + + flag := []byte{0} + if unchanged { + flag[0] = 1 + } + + return unchanged, b.pending.put("subtrees", []byte(rel), flag) +} + +func (b *nativeTransport) compareSubtree(rel string, n storage.Node) (bool, error) { + missing := func(err error) bool { + return errors.Is(err, syscall.ENOENT) || errors.Is(err, syscall.ENOTDIR) || errors.Is(err, syscall.ENODATA) + } + + basePath := path.Join(b.round.BaseSourcePath, rel) + old, err := b.source.Stat(basePath) + if missing(err) { + return false, nil + } + if err != nil { + return false, err + } + + // The directory's own inode version changes at once with every entry + // added or removed and every change of its own metadata; the rctime + // reaches the snapshot only after a delay (measured in the lab). + if old.Kind() != storage.Directory || old.Inode != n.Inode || n.Version == 0 || old.Version != n.Version { + return false, nil + } + + entry, known, err := b.base.entry(rel) + if err != nil || !known || entry.Inode != n.Inode { + return false, err + } + + target, err := b.target.Stat(path.Join(b.round.TargetPath, rel)) + if missing(err) { + return false, nil + } + if err != nil { + return false, err + } + + if target.Kind() != storage.Directory { + return false, nil + } + + now, err := b.source.GetXattr(path.Join(b.round.SourcePath, rel), "ceph.dir.rctime") + if missing(err) { + return false, nil + } + if err != nil { + return false, err + } + + then, err := b.source.GetXattr(basePath, "ceph.dir.rctime") + if missing(err) { + return false, nil + } + if err != nil { + return false, err + } + + return len(now) > 0 && bytes.Equal(now, then), nil +} + +// skipped returns errSkipSubtree for a directory rel that this round skipped, +// so walks of the target or of a snapshot leave it out as well. +func (b *nativeTransport) skipped(rel string) error { + if !b.round.SkipUnchanged || rel == "." { + return nil + } + + v, err := b.pending.get("subtrees", []byte(rel)) + if err != nil { + return err + } + + if len(v) == 1 && v[0] == 1 { + return errSkipSubtree + } + + return nil } func (b *nativeTransport) rate(ctx context.Context, n int) error {