fix!: remove skipping of unchanged subtrees

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>
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-12-03 22:17:47 +01:00
1 parent 82c64f9908
commit 6dcb7b676f
16 files changed
+113 -444

No files matched your search

+4 -6
View File
@@ -123,9 +123,8 @@ sequenceDiagram
The detailed sequence is in [docs/migration.md](docs/migration.md#workflow-in-detail). The detailed sequence is in [docs/migration.md](docs/migration.md#workflow-in-detail).
Intermediate `sync` rounds skip subtrees whose recursive change time Every round reads the metadata of the whole subvolume; only changed file
(`ceph.dir.rctime`) did not change, so a round reads only the changed parts. contents are copied.
`finalize` always reads everything.
Each round creates a snapshot `cephmig-<job>-<round>` at source and target; Each round creates a snapshot `cephmig-<job>-<round>` at source and target;
`sync` deletes the older ones as soon as a newer round is complete. Users of `sync` deletes the older ones as soon as a newer round is complete. Users of
@@ -157,9 +156,8 @@ The configuration is a JSON file, here
``` ```
Optional fields are `user` (Ceph client identity, e.g. `client.migration`), Optional fields are `user` (Ceph client identity, e.g. `client.migration`),
`workers` (0 to 64; 0 selects the default) and `full_scan` (`true` makes and `workers` (0 to 64; 0 selects the default). `backend` may be omitted;
every round read all metadata instead of skipping unchanged subtrees). its only value is `native`.
`backend` may be omitted; its only value is `native`.
## Examples ## Examples
+1 -5
View File
@@ -75,7 +75,7 @@ def populate(root):
os.setxattr(root + "/d", "ceph.quota.max_bytes", b"33554432") os.setxattr(root + "/d", "ceph.quota.max_bytes", b"33554432")
os.setxattr(root + "/d", "ceph.quota.max_files", b"1000") os.setxattr(root + "/d", "ceph.quota.max_files", b"1000")
os.setxattr(root, "ceph.quota.max_bytes", b"268435456") os.setxattr(root, "ceph.quota.max_bytes", b"268435456")
# A subtree no round changes; sync rounds skip it by its rctime. # A subtree no round changes.
os.makedirs(root + "/static/deep/deeper") os.makedirs(root + "/static/deep/deeper")
pathlib.Path(root + "/static/deep/deeper/file").write_bytes(b"static" * 1000) pathlib.Path(root + "/static/deep/deeper/file").write_bytes(b"static" * 1000)
os.link(root + "/static/deep/deeper/file", root + "/static/alias") os.link(root + "/static/deep/deeper/file", root + "/static/alias")
@@ -277,10 +277,6 @@ elif action in ("verify", "final"):
assert compare_times(a, b, atime=True) > 10 assert compare_times(a, b, atime=True) > 10
assert snapshot("source", "metadata", "ls", "cephfs", name, snap["name"]) == snapshot( assert snapshot("source", "metadata", "ls", "cephfs", name, snap["name"]) == snapshot(
"target", "metadata", "ls", "cephfs", name, snap["name"]) "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"] 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["mode"] == "snapdiff" and h2["blockdiff_files"] > 0, h2
assert h2["bytes_copied"] < 64 << 20, h2 assert h2["bytes_copied"] < 64 << 20, h2
+5 -2
View File
@@ -236,10 +236,13 @@ def main():
state = json.loads(journal.read_text()) state = json.loads(journal.read_text())
started = time.monotonic() started = time.monotonic()
checked = compare(roots["source"], roots["target"]) checked = compare(roots["source"], roots["target"])
if checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4: # sync removes older round snapshots; only the final one remains.
present = [s for s in state["snapshots"] if not s.get("removed")]
if (checked != count + 100 or state["phase"] != "ready-for-cutover" or len(state["snapshots"]) != 4 or
[s["name"] for s in present if s.get("owned")] != [state["snapshots"][-1]["name"]]):
raise AssertionError("unexpected file count or incomplete migration") raise AssertionError("unexpected file count or incomplete migration")
snapshots = [] snapshots = []
for s in state["snapshots"]: for s in present:
a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath", a, b = [f"/mnt/{c}-fs" + ceph(c, "fs", "subvolume", "snapshot", "getpath",
"cephfs", name, s["name"], "migration") for c in ("source", "target")] "cephfs", name, s["name"], "migration") for c in ("source", "target")]
snapshot_checked = compare(a, b, s["name"]) snapshot_checked = compare(a, b, s["name"])
+2 -2
View File
@@ -84,8 +84,8 @@ effective throughput and a fixed upper bound for the write stop will be
determined later. The local environment verifies functionality but does not determined later. The local environment verifies functionality but does not
reproduce this amount of data. The native copier uses bounded workers and reproduce this amount of data. The native copier uses bounded workers and
buffers, a persistent index on local disk and optional bandwidth limiting. buffers, a persistent index on local disk and optional bandwidth limiting.
Intermediate rounds skip unchanged subtrees; the final round still scans all Every round, the final one included, scans all metadata. Evidence for
metadata. Evidence for memory, index size, memory, index size,
runtime and the final write stop is missing. runtime and the final write stop is missing.
1. Check source, target, permissions, capacity and required metadata. 1. Check source, target, permissions, capacity and required metadata.
+25 -48
View File
@@ -48,8 +48,8 @@ limits concurrent file copies and verification checks (default 8, at most 64),
`bandwidth_kib` limits the total payload bytes written per second. Both values `bandwidth_kib` limits the total payload bytes written per second. Both values
may be changed when resuming. may be changed when resuming.
The `transfer` statistics in the journal report the mode, the base The `transfer` statistics in the journal report the mode, the base
snapshot, visited and copied files, bytes written and read for verification, snapshot, visited and copied files, bytes written and read for verification
skipped subtrees and the duration of the round in seconds. `bytes_copied` counts payload writes without skipped zero and the duration of the round in seconds. `bytes_copied` counts payload writes without skipped zero
ranges; it does not measure the total network traffic including protocol and ranges; it does not measure the total network traffic including protocol and
verification. verification.
@@ -82,42 +82,25 @@ snapshots and then a new source snapshot. Further changes are caught up by
running `sync` again. CephMig uses snapdiff and the Ceph inode version, so it running `sync` again. CephMig uses snapdiff and the Ceph inode version, so it
also detects data changes with the same size and mtime. also detects data changes with the same size and mtime.
### Skipping unchanged subtrees ### Metadata scan
Reading all metadata of a large subvolume in every round is the main cost of Every round reads the metadata of all entries of its snapshot. This is the
a round: in the [one-million-file test](million-local.md), even an unchanged main cost of a round: in the [one-million-file test](million-local.md), even
finalization took 1 h 20 min and 19.3 million MDS requests. Snapdiff cannot an unchanged finalization took 1 h 20 min and 19.3 million MDS requests.
replace this scan; in the lab it reported every directory and missed pure Snapdiff cannot replace this scan; in the lab it reported every directory and
chmod, xattr changes and writes through a hardlink alias. missed pure chmod, xattr changes and writes through a hardlink alias.
Intermediate `sync` rounds therefore skip a subdirectory when, compared with An earlier version skipped a subdirectory in intermediate rounds when its
the base snapshot of the previous round, it has inode version and its `ceph.dir.rctime` matched the previous round. It was
removed because it missed changes. In the 10,000-file test on 2026-12-03, a
- the same inode and the same inode version, which changes at once with round snapshot taken seconds after changes skipped the directory `tree/`
every entry added or removed and every change of its own metadata, and with about 250 changed files in its subdirectories: the inode version of
- the same `ceph.dir.rctime`, the newest ctime in the whole subtree. `tree/` changes only with its own entries, and Ceph had not yet propagated
the rctime of the grandchildren to it. That target snapshot was incomplete,
The index takes over the entries of a skipped subtree from the previous base and its verification did not notice, because it skipped the same subtrees;
and marks them `carried`. Snapdiff, copy, pruning and verification all leave only `finalize`, which always scanned everything, closed the gap. Base index
the subtree out. The journal reports the number per round as entries that this version marked `carried` are never trusted; such files are
`skipped_subtrees`. copied in full in the next round.
The rctime is not exact. Ceph propagates it to the parent directories with a
delay; in the lab, a change made milliseconds before a snapshot was not yet
visible in that snapshot's rctime. A client whose clock lags behind can also
stamp a change with a ctime older than the newest one in the subtree. An
intermediate round can therefore miss content changes deep inside a subtree.
The following design limits the effect to extra work:
- `finalize` always scans and verifies everything; it never skips.
- A carried entry describes an older round than the base snapshot, so it never
serves as base for a block delta: a changed carried file is copied in full.
- Snapshots discovered at the source (application snapshots) are always
transferred with a full scan. Only the `cephmig-*` round snapshots, which
are deleted later, can be incomplete.
`"full_scan": true` in the configuration disables the shortcut for all
rounds. It may be changed when resuming.
`finalize` relies solely on the operator's explicit confirmation of the write `finalize` relies solely on the operator's explicit confirmation of the write
stop; it does not stop or lock any application itself. All writers must stay stop; it does not stop or lock any application itself. All writers must stay
@@ -149,8 +132,7 @@ next time.
The diagram shows one migration with the native backend: an intermediate The diagram shows one migration with the native backend: an intermediate
`sync` round, `finalize` and `cleanup`. Application snapshots discovered at `sync` round, `finalize` and `cleanup`. Application snapshots discovered at
the source are transferred like a round, but always with a full scan and the source are transferred like a round, but are never deleted.
without being deleted.
```mermaid ```mermaid
sequenceDiagram sequenceDiagram
@@ -173,16 +155,11 @@ sequenceDiagram
M->>I: open base R(n-1), create pending index M->>I: open base R(n-1), create pending index
M->>S: snapdiff R(n-1) to R(n) M->>S: snapdiff R(n-1) to R(n)
loop every directory, from the root down loop every entry, from the root down
M->>S: stat dir, ceph.dir.rctime in R(n) and R(n-1)
alt same inode, inode version and rctime (sync rounds only)
M->>I: carry subtree entries, marked carried
else changed
M->>I: record path inventory M->>I: record path inventory
M->>T: mkdir, copy changed files (blockdiff or full), symlinks, FIFOs M->>T: mkdir, copy changed files (blockdiff or full), symlinks, FIFOs
M->>T: xattrs and quotas, then setattr and ctime stamp M->>T: xattrs and quotas, then setattr and ctime stamp
end end
end
M->>T: hardlink aliases, prune surplus entries M->>T: hardlink aliases, prune surplus entries
M->>T: restore directory metadata, deepest first M->>T: restore directory metadata, deepest first
@@ -201,7 +178,7 @@ sequenceDiagram
Note over Op,S: all writers stopped Note over Op,S: all writers stopped
Op->>M: finalize --writers-stopped Op->>M: finalize --writers-stopped
M->>S: create final snapshot F M->>S: create final snapshot F
Note over M,T: same round, but a full scan: no subtree is skipped Note over M,T: same steps as a sync round
M->>J: mark F done, R(n) removed M->>J: mark F done, R(n) removed
M->>S: remove snapshot R(n) M->>S: remove snapshot R(n)
M->>T: remove snapshot R(n) M->>T: remove snapshot R(n)
@@ -425,9 +402,9 @@ files and short verification ranges. Unchanged owner, mode and timestamps do
not trigger another `setattr` call; a target stat read just before is reused not trigger another `setattr` call; a target stat read just before is reused
for the metadata check. Path and hardlink mappings live on local disk. for the metadata check. Path and hardlink mappings live on local disk.
Snapdiff and blockdiff avoid repeated full transfers and full reads of Snapdiff and blockdiff avoid repeated full transfers and full reads of
unchanged file contents. Intermediate rounds skip unchanged subtrees, but unchanged file contents. Every round, `finalize` included, still scans all
`finalize` still scans all metadata, including the full topology and quota metadata, including the full topology and quota check, so the write stop
check, so the write stop scales with the total number of entries. Renamed scales with the total number of entries. Renamed
files may be copied again in full. Single transactions of the native index are not yet optimized files may be copied again in full. Single transactions of the native index are not yet optimized
for 200 million paths. for 200 million paths.
+6 -8
View File
@@ -87,10 +87,10 @@ Consequences for cephmig:
- With `CEPH_SNAPDIFF_CTIME`, snapdiff2 should report the changes v1 missed - With `CEPH_SNAPDIFF_CTIME`, snapdiff2 should report the changes v1 missed
in the lab (chmod, xattr changes, writes through a hardlink alias, in the lab (chmod, xattr changes, writes through a hardlink alias,
overwrites with a reset mtime), because all of them change the ctime. overwrites with a reset mtime), because all of them change the ctime.
- It compares the two snapshots in the MDS, so unlike the rctime shortcut it - It compares the two snapshots in the MDS, so unlike the removed rctime
depends neither on delayed rctime propagation nor on client clocks. It shortcut (see [metadata scan](migration.md#metadata-scan)) it depends
could therefore replace the rctime check in intermediate rounds and, after neither on delayed rctime propagation nor on client clocks. After a lab
a lab proof, possibly shorten `finalize`. proof, it could shorten rounds and possibly `finalize`.
- Open: v1 reported every directory, including unchanged ones. The sources - Open: v1 reported every directory, including unchanged ones. The sources
do not say whether snapdiff2 behaves differently; without that, it cannot do not say whether snapdiff2 behaves differently; without that, it cannot
be used to skip subtrees. be used to skip subtrees.
@@ -128,10 +128,8 @@ state is reconstructed fully and natively. There is no fallback to another
transfer method. transfer method.
Snapdiff cannot replace the metadata scan (see Snapdiff cannot replace the metadata scan (see
[skipping unchanged subtrees](migration.md#skipping-unchanged-subtrees)). [metadata scan](migration.md#metadata-scan)). Every round scans all metadata
Intermediate rounds skip subtrees whose recursive ctime did not change; and checks the full hardlink topology.
application snapshots and the final round still scan all metadata and check
the full hardlink topology.
Data verification reads all bytes for the first state and only the copied Data verification reads all bytes for the first state and only the copied
ranges for confirmed later states. Unchanged ranges are taken from the ranges for confirmed later states. Unchanged ranges are taken from the
previously verified base. The target must belong exclusively to the previously verified base. The target must belong exclusively to the
+2 -2
View File
@@ -70,8 +70,8 @@ Everything the migration promises, without relying on earlier rounds:
- the custom metadata of the final snapshot and of the subvolume as it was - the custom metadata of the final snapshot and of the subvolume as it was
at `finalize` (the journal holds the values) at `finalize` (the journal holds the values)
The journal, the native base index and the `carried` markers are not used: The journal and the native base index are not used: the point is an
the point is an independent check. independent check.
## Preconditions and behaviour ## Preconditions and behaviour
+1 -4
View File
@@ -50,13 +50,11 @@ type Transport interface {
// Round describes one snapshot transfer handed to a RoundTransport. // Round describes one snapshot transfer handed to a RoundTransport.
// BaseName and BaseSourcePath name the last completed snapshot, if any, // BaseName and BaseSourcePath name the last completed snapshot, if any,
// which allows an incremental transfer. SkipUnchanged permits skipping // which allows an incremental transfer.
// subtrees whose recursive ctime did not change since the base.
type Round struct { type Round struct {
SourcePath, TargetPath string SourcePath, TargetPath string
BaseName, BaseSourcePath string BaseName, BaseSourcePath string
Name, StatePath string Name, StatePath string
SkipUnchanged bool
} }
// RoundTransport is a Transport that keeps state across a snapshot round, // RoundTransport is a Transport that keeps state across a snapshot round,
@@ -78,7 +76,6 @@ type TransferStats struct {
BytesVerified int64 `json:"bytes_verified"` BytesVerified int64 `json:"bytes_verified"`
BlockDiffFiles int64 `json:"blockdiff_files"` BlockDiffFiles int64 `json:"blockdiff_files"`
SnapDiffEntries int64 `json:"snapdiff_entries"` SnapDiffEntries int64 `json:"snapdiff_entries"`
SkippedSubtrees int64 `json:"skipped_subtrees,omitempty"`
// Seconds is the duration of the round from its start to the commit, // Seconds is the duration of the round from its start to the commit,
// including verification and snapshot creation. // including verification and snapshot creation.
Seconds float64 `json:"seconds"` Seconds float64 `json:"seconds"`
-4
View File
@@ -29,10 +29,6 @@ type Config struct {
Source Endpoint `json:"source"` Source Endpoint `json:"source"`
Target Endpoint `json:"target"` Target Endpoint `json:"target"`
BandwidthKiB int64 `json:"bandwidth_kib,omitempty"` 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, // ReadConfig reads exactly one JSON object from the regular file at path,
+1 -5
View File
@@ -433,7 +433,6 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
func sameMigrationIdentity(a, b Config) bool { func sameMigrationIdentity(a, b Config) bool {
a.Workers, b.Workers = 0, 0 a.Workers, b.Workers = 0, 0
a.BandwidthKiB, b.BandwidthKiB = 0, 0 a.BandwidthKiB, b.BandwidthKiB = 0, 0
a.FullScan, b.FullScan = false, false
// "" and "native" select the same backend. // "" and "native" select the same backend.
a.Backend, b.Backend = "", "" a.Backend, b.Backend = "", ""
return reflect.DeepEqual(a, b) return reflect.DeepEqual(a, b)
@@ -484,10 +483,7 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
aware, isNative := e.Transport.(RoundTransport) aware, isNative := e.Transport.(RoundTransport)
existed := slices.Contains(targetNames, snap.Name) existed := slices.Contains(targetNames, snap.Name)
if isNative { if isNative {
// Only intermediate round snapshots may skip unchanged subtrees. They are round := Round{SourcePath: from, TargetPath: target, Name: snap.Name, StatePath: statePath, BaseName: s.LiveSnapshot}
// 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 != "" { if s.LiveSnapshot != "" {
round.BaseSourcePath, err = src.snapshotPath(ctx, s.LiveSnapshot) round.BaseSourcePath, err = src.snapshotPath(ctx, s.LiveSnapshot)
if err != nil { if err != nil {
+14 -12
View File
@@ -54,6 +54,14 @@ func allZero(b []byte) bool {
return true return true
} }
// baseTrusted reports whether the base entry previous still describes the
// source node n and its target copy, so the copy may be skipped or patched.
// A carried entry was written by an earlier version that skipped subtrees;
// it may describe an older round and is never trusted.
func baseTrusted(previous baseEntry, n, target storage.Node) bool {
return !previous.Carried && previous.Inode == n.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size
}
func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error { func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error {
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return err return err
@@ -80,7 +88,7 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
return err return err
} }
trusted = ok && previous.Inode == job.node.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size trusted = ok && baseTrusted(previous, job.node, target)
} }
changed := true changed := true
@@ -95,9 +103,7 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
if changed { if changed {
usedBlockDiff := false usedBlockDiff := false
// A carried entry describes an older round than the base snapshot, so if trusted && job.node.Size >= nativeBlockThreshold {
// 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)) old, err := b.source.Stat(path.Join(b.round.BaseSourcePath, job.rel))
if err == nil && old.Kind() == storage.Regular && old.Inode == job.node.Inode { 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) stream, err := b.source.BlockDiff(b.snapRoot, path.Join(b.snapRel, job.rel), b.round.BaseName, b.round.Name)
@@ -361,8 +367,8 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
defer scratch.cleanup() defer scratch.cleanup()
v := &nativeVerification{b: b, to: to, skipData: skipData, index: scratch.index} v := &nativeVerification{b: b, to: to, skipData: skipData, index: scratch.index}
// The walk and the directories stay serial, so subtree skips apply in walk // The walk and the directories stay serial; every other entry is checked by
// order. Every other entry is checked by one of the workers. // one of the workers.
ctx, cancel := context.WithCancelCause(ctx) ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil) defer cancel(nil)
workers := b.config.Workers workers := b.config.Workers
@@ -408,11 +414,7 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
} }
if n.Kind() == storage.Directory { if n.Kind() == storage.Directory {
if err = v.entry(ctx, p, rel, n); err != nil { return v.entry(ctx, p, rel, n)
return err
}
return b.skipped(rel)
} }
select { select {
@@ -576,7 +578,7 @@ func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error
return fmt.Errorf("unexpected native target entry %s", rel) return fmt.Errorf("unexpected native target entry %s", rel)
} }
return b.skipped(rel) return nil
}) })
} }
+1 -7
View File
@@ -14,10 +14,6 @@ import (
"git.zb-server.de/Sebi/CephfsMig/internal/storage" "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")
// quotaKeys are the directory quota xattrs that the migration copies. // quotaKeys are the directory quota xattrs that the migration copies.
var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"} var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"}
@@ -32,9 +28,7 @@ func walkNative(ctx context.Context, fs storage.FS, root string, visit func(stri
return errors.New("native directory depth exceeds 128") return errors.New("native directory depth exceeds 128")
} }
if err := visit(p, n, depth); errors.Is(err, errSkipSubtree) && n.Kind() == storage.Directory { if err := visit(p, n, depth); err != nil {
return nil
} else if err != nil {
return err return err
} }
+4 -66
View File
@@ -11,7 +11,7 @@ import (
bolt "go.etcd.io/bbolt" bolt "go.etcd.io/bbolt"
) )
var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete", "relinked", "subtrees"} var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete", "relinked"}
type nativeIndex struct { type nativeIndex struct {
db *bolt.DB db *bolt.DB
@@ -19,9 +19,9 @@ type nativeIndex struct {
} }
// baseEntry is the inventory record of one source path. Carried marks an // baseEntry is the inventory record of one source path. Carried marks an
// entry taken over unexamined from the previous base because its subtree was // entry that an earlier version took over unexamined when it skipped an
// skipped: it still describes the state of an older round, so it must not // unchanged-looking subtree. Such an entry may describe an older round, so
// serve as base for a block delta. // it is never trusted. Current versions do not write it.
type baseEntry struct { type baseEntry struct {
Inode, Version, Size, TargetInode uint64 Inode, Version, Size, TargetInode uint64
Carried bool Carried bool
@@ -163,68 +163,6 @@ func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error {
return x.put("paths", []byte(rel), encodeEntry(entry)) 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 { func (x *nativeIndex) requireInventory() error {
complete, err := x.get("meta", []byte("inventory_complete")) complete, err := x.get("meta", []byte("inventory_complete"))
if err != nil { if err != nil {
+46
View File
@@ -0,0 +1,46 @@
package migration
import (
"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 TestBaseTrustRejectsCarriedEntries(t *testing.T) {
n := storage.Node{Inode: 1, Size: 3}
target := storage.Node{Inode: 4, Size: 3}
e := baseEntry{Inode: 1, Version: 2, Size: 3, TargetInode: 4}
if !baseTrusted(e, n, target) {
t.Fatal("matching entry not trusted")
}
e.Carried = true
if baseTrusted(e, n, target) {
t.Fatal("carried entry trusted")
}
e.Carried = false
target.Inode = 5
if baseTrusted(e, n, target) {
t.Fatal("entry of a replaced target trusted")
}
}
-128
View File
@@ -1,128 +0,0 @@
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")
}
}
+1 -145
View File
@@ -1,7 +1,6 @@
package migration package migration
import ( import (
"bytes"
"context" "context"
"encoding/binary" "encoding/binary"
"errors" "errors"
@@ -49,7 +48,6 @@ type nativeTransport struct {
visited, copied, written atomic.Int64 visited, copied, written atomic.Int64
checked, blockFiles atomic.Int64 checked, blockFiles atomic.Int64
diffEntries, rateBytes atomic.Int64 diffEntries, rateBytes atomic.Int64
skippedSubtrees atomic.Int64
} }
func (b *nativeTransport) Close() error { func (b *nativeTransport) Close() error {
@@ -122,7 +120,6 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
b.blockFiles.Store(0) b.blockFiles.Store(0)
b.diffEntries.Store(0) b.diffEntries.Store(0)
b.rateBytes.Store(0) b.rateBytes.Store(0)
b.skippedSubtrees.Store(0)
b.started = time.Now() b.started = time.Now()
marker := "/.snap/" + r.Name marker := "/.snap/" + r.Name
at := strings.LastIndex(r.SourcePath, marker) at := strings.LastIndex(r.SourcePath, marker)
@@ -218,20 +215,6 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
} }
if n.Kind() == storage.Directory { 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 { if err = b.collectChanges(ctx, path.Join(rel, name), child, depth+1); err != nil {
return err return err
} }
@@ -311,22 +294,6 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
} }
target := path.Join(to, rel) 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 // Record every immutable source entry before dispatching work. This local
// inventory replaces source path lookups during pruning and verification. // inventory replaces source path lookups during pruning and verification.
if err = b.pending.put("paths", []byte(rel), encodeEntry(baseEntry{ if err = b.pending.put("paths", []byte(rel), encodeEntry(baseEntry{
@@ -535,7 +502,7 @@ func (b *nativeTransport) prune(ctx context.Context, from, to string) error {
} }
if present { if present {
return b.skipped(rel) return nil
} }
// Removing one name of a hardlinked inode resets its ctime; the // Removing one name of a hardlinked inode resets its ctime; the
@@ -629,120 +596,9 @@ func (b *nativeTransport) Statistics() TransferStats {
return TransferStats{Mode: mode, BaseSnapshot: base, FilesVisited: b.visited.Load(), return TransferStats{Mode: mode, BaseSnapshot: base, FilesVisited: b.visited.Load(),
FilesCopied: b.copied.Load(), BytesCopied: b.written.Load(), BytesVerified: b.checked.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(),
Seconds: math.Round(time.Since(b.started).Seconds()*1000) / 1000} Seconds: math.Round(time.Since(b.started).Seconds()*1000) / 1000}
} }
// 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 { func (b *nativeTransport) rate(ctx context.Context, n int) error {
if b.config.BandwidthKiB == 0 { if b.config.BandwidthKiB == 0 {
return nil return nil