Files
CephfsMig/internal/migration/native_transport.go
T
Sebastian UnterschützandClaude Opus 5.5 e2c4549ade fix(native): replace the writing client before verification
The writing client kept the caps of the files it wrote last. Every
lookup of the verification client on one of them made the MDS recall
the caps entry by entry, which cost about five seconds per lookup in
the lab and stalled a 100,000-file verification near its end.

Verify now opens a fresh target client, closes the writer, which
returns all caps at once, and keeps writing through the fresh client.
The claim lock is held through a client of its own, so it survives the
change.

Verify also checks non-directory entries in parallel with the
configured number of workers. The walk and the directories stay
serial, so skipped subtrees are handled in walk order.

Transfer statistics report the duration of each round in seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:50:35 +01:00

774 lines
18 KiB
Go

package migration
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"git.zb-server.de/Sebi/CephfsMig/internal/storage"
)
const nativeChunk = 4 << 20
const nativeBlockThreshold = 16 << 20
type nativeTransport struct {
source, target storage.FS
config Config
// openTarget opens another client of the target. Claim holds its lock
// through one, so that Verify can replace the writing client: Verify
// closes the writer, which returns all its caps, and continues with a
// fresh client. Nil means Verify and Claim use target as it is.
openTarget func() (storage.FS, error)
log io.Writer
identity string
// State of the current round.
round Round
workspace string
pending, base *nativeIndex
delta bool
snapRoot, snapRel string
verified map[string]bool
started time.Time
// Counters reported by Statistics and used for rate limiting.
visited, copied, written atomic.Int64
checked, blockFiles atomic.Int64
diffEntries, rateBytes atomic.Int64
skippedSubtrees atomic.Int64
}
func (b *nativeTransport) Close() error {
var errs []error
if b.pending != nil {
errs = append(errs, b.pending.close())
}
if b.base != nil {
errs = append(errs, b.base.close())
}
errs = append(errs, b.source.Close(), b.target.Close())
return errors.Join(errs...)
}
func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
if b.pending != nil {
if err := b.pending.close(); err != nil {
return err
}
}
if b.base != nil {
if err := b.base.close(); err != nil {
return err
}
b.base = nil
}
b.round = r
b.workspace = r.StatePath + ".native"
if err := privateDirectories(b.workspace); err != nil {
return err
}
files, err := os.ReadDir(b.workspace)
if err != nil {
return err
}
for _, f := range files {
if strings.HasPrefix(f.Name(), "pending-") && strings.HasSuffix(f.Name(), ".bolt") {
if !f.Type().IsRegular() {
return errors.New("native scratch path is not a regular file")
}
if err = os.Remove(filepath.Join(b.workspace, f.Name())); err != nil {
return err
}
}
}
b.pending, err = createNativeIndex(b.workspace)
if err != nil {
return err
}
if err = b.pending.put("meta", []byte("identity"), []byte(b.identity)); err != nil {
return err
}
b.delta = false
b.verified = map[string]bool{}
b.visited.Store(0)
b.copied.Store(0)
b.written.Store(0)
b.checked.Store(0)
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)
if at < 0 {
return errors.New("native source snapshot path does not contain its snapshot name")
}
b.snapRoot = r.SourcePath[:at]
b.snapRel = r.SourcePath[at+len(marker):]
if b.snapRel == "" {
b.snapRel = "/"
}
if r.BaseName != "" {
base, err := openNativeIndex(filepath.Join(b.workspace, "base.bolt"))
if err == nil {
name, e1 := base.get("meta", []byte("snapshot"))
identity, e2 := base.get("meta", []byte("identity"))
if e1 == nil && e2 == nil && string(name) == r.BaseName && string(identity) == b.identity {
b.base = base
b.delta = true
} else {
base.close()
}
} else if !errors.Is(err, os.ErrNotExist) && b.log != nil {
fmt.Fprintf(b.log, "native base index unavailable; rebuilding full snapshot: %v\n", err)
}
}
if b.delta {
if err := b.collectChanges(ctx, b.snapRel, r.SourcePath, 0); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
b.delta = false
if b.log != nil {
fmt.Fprintf(b.log, "native snapdiff unavailable for this pair; full reconstruction: %v\n", err)
}
}
}
if b.log != nil {
fmt.Fprintf(b.log, "native snapshot=%s mode=%s\n", r.Name, b.Statistics().Mode)
}
return nil
}
func (b *nativeTransport) collectChanges(ctx context.Context, rel, current string, depth int) error {
if err := ctx.Err(); err != nil {
return err
}
if depth > 128 {
return errors.New("snapdiff depth exceeds 128")
}
d, err := b.source.SnapDiff(b.snapRoot, rel, b.round.BaseName, b.round.Name)
if errors.Is(err, syscall.ENOENT) {
return nil
} // A newly created subtree has no base paths.
if err != nil {
return err
}
defer d.Close()
for {
if err := ctx.Err(); err != nil {
return err
}
name, err := d.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if !validNativeEntry(name) {
return fmt.Errorf("invalid snapdiff entry %q", name)
}
b.diffEntries.Add(1)
child := path.Join(current, name)
n, err := b.source.Stat(child)
if errors.Is(err, syscall.ENOENT) {
continue
}
if err != nil {
return err
}
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
}
} else if n.Kind() == storage.Regular {
if err = b.pending.put("changed", nativeInodeKey(n.Inode), []byte{1}); err != nil {
return err
}
}
}
}
func validNativeEntry(name string) bool {
return name != "" && name != "." && name != ".." && name != ".snap" && !strings.ContainsAny(name, "/\x00")
}
func relativeNative(root, p string) (string, error) {
if p == root {
return ".", nil
}
if !strings.HasPrefix(p, root+"/") {
return "", fmt.Errorf("native path escapes root: %s", p)
}
return strings.TrimPrefix(p, root+"/"), nil
}
type nativeJob struct {
rel string
node storage.Node
}
func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
var err error
if b.pending == nil || from != b.round.SourcePath || to != b.round.TargetPath {
return errors.New("native copy round is not initialized")
}
copyCtx, cancel := context.WithCancel(ctx)
defer cancel()
workers := b.config.Workers
if workers == 0 {
workers = 8
}
jobs := make(chan nativeJob, workers*2)
errorsOut := make(chan error, 1)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
if err := b.copyRegular(copyCtx, job); err != nil {
select {
case errorsOut <- err:
default:
}
cancel()
}
}
}()
}
lastProgress := time.Now()
walkErr := walkNative(copyCtx, b.source, from, func(p string, n storage.Node, depth int) error {
b.visited.Add(1)
if b.log != nil && time.Since(lastProgress) >= 30*time.Second {
fmt.Fprintf(b.log, "native copying visited=%d copied=%d bytes_written=%d\n", b.visited.Load(), b.copied.Load(), b.written.Load())
lastProgress = time.Now()
}
rel, err := relativeNative(from, p)
if err != nil {
return err
}
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{
Inode: n.Inode, Version: n.Version, Size: n.Size,
})); err != nil {
return err
}
// POSIX hardlinks can also refer to symlinks and special files. Track all
// non-directory inodes, then create their aliases after canonical entries.
if n.Kind() != storage.Directory {
first, err := b.pending.get("groups", nativeInodeKey(n.Inode))
if err != nil {
return err
}
if first != nil {
return b.pending.put("aliases", []byte(rel), first)
}
if err = b.pending.put("groups", nativeInodeKey(n.Inode), []byte(rel)); err != nil {
return err
}
}
switch n.Kind() {
case storage.Directory:
if err = ensureNativeDirectory(copyCtx, b.target, target); err != nil {
return err
}
return b.pending.put("dirs", nativeDirKey(rel, depth), []byte(rel))
case storage.Regular:
if n.Size > math.MaxInt64 {
return errors.New("file exceeds supported signed offset range")
}
select {
case jobs <- nativeJob{rel, n}:
return nil
case <-copyCtx.Done():
return copyCtx.Err()
}
case storage.Symlink, storage.FIFO, storage.Socket, storage.CharDevice, storage.BlockDevice:
return b.copySpecial(copyCtx, rel, n)
default:
return fmt.Errorf("unsupported native file type %o at %s", n.Mode, p)
}
})
close(jobs)
wg.Wait()
select {
case err := <-errorsOut:
return err
default:
}
if walkErr != nil {
return walkErr
}
if err = b.pending.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
return err
}
if err = ctx.Err(); err != nil {
return err
}
// Complete links only after every canonical file is durable.
if err = b.pending.each("aliases", false, func(k, v []byte) error {
if err := ctx.Err(); err != nil {
return err
}
dst, canonical := path.Join(to, string(k)), path.Join(to, string(v))
a, err := b.target.Stat(canonical)
if err != nil {
return err
}
old, err := b.target.Stat(dst)
if err == nil && old.Kind() == a.Kind() && old.Inode == a.Inode {
return nil
}
if err != nil && !errors.Is(err, syscall.ENOENT) {
return err
}
if err == nil {
if err = removeNative(ctx, b.target, dst); err != nil {
return err
}
}
if err := b.target.Link(canonical, dst); err != nil {
return fmt.Errorf("native hardlink %s -> %s: %w", string(k), string(v), err)
}
// Linking resets the ctime of the inode; set it again.
src := path.Join(from, string(k))
n, err := b.source.Stat(src)
if err != nil {
return err
}
return restoreNativeMetadata(b.source, b.target, src, dst, n)
}); err != nil {
return err
}
if err = b.prune(ctx, from, to); err != nil {
return err
}
// Child creation/deletion has finished; restore directory metadata last.
// Creating or removing a child sets the ctime of its directory on the
// MDS, while the cache of this client may keep the old value, so the
// cached stat cannot tell whether a directory is current.
if err = b.pending.each("dirs", true, func(_, v []byte) error {
if err := ctx.Err(); err != nil {
return err
}
rel := string(v)
src, dst := path.Join(from, rel), path.Join(to, rel)
n, err := b.source.Stat(src)
if err != nil {
return err
}
return restoreNativeMetadata(b.source, b.target, src, dst, n)
}); err != nil {
return err
}
return b.target.Sync()
}
func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage.Node) error {
src, dst := path.Join(b.round.SourcePath, rel), path.Join(b.round.TargetPath, rel)
_, err := b.target.Stat(dst)
if err != nil && !errors.Is(err, syscall.ENOENT) {
return err
}
exists := err == nil
var text string
if n.Kind() == storage.Symlink {
text, err = b.source.Readlink(src)
if err != nil {
return err
}
}
// Recreate canonical special inodes so previously linked, now independent
// source entries cannot remain accidentally linked at the target.
if exists {
if err = removeNative(ctx, b.target, dst); err != nil {
return err
}
}
if n.Kind() == storage.Symlink {
err = b.target.Symlink(text, dst)
} else {
err = b.target.Mknod(dst, n.Mode, n.Rdev)
}
if err != nil {
return err
}
return syncNativeMetadata(b.source, b.target, src, dst, n, false)
}
func (b *nativeTransport) prune(ctx context.Context, from, to string) error {
if from != b.round.SourcePath {
return errors.New("source inventory belongs to a different round")
}
if err := b.pending.requireInventory(); err != nil {
return err
}
// Store deletions on disk and apply after closing the directory streams.
err := walkNative(ctx, b.target, to, func(p string, n storage.Node, _ int) error {
rel, err := relativeNative(to, p)
if err != nil {
return err
}
if rel == "." {
return nil
}
present, err := b.pending.containsPath(rel)
if err != nil {
return err
}
if present {
return b.skipped(rel)
}
// Removing one name of a hardlinked inode resets its ctime; the
// remaining names are set again below.
if n.Kind() != storage.Directory && n.Nlink > 1 {
if err = b.pending.put("relinked", nativeInodeKey(n.Inode), []byte{1}); err != nil {
return err
}
}
return b.pending.put("delete", []byte(rel), []byte{1})
})
if err != nil {
return err
}
err = b.pending.each("delete", true, func(k, _ []byte) error {
return removeNative(ctx, b.target, path.Join(to, string(k)))
})
if err != nil {
return err
}
return b.restoreRelinked(from, to)
}
// restoreRelinked sets the metadata of regular files again whose target inode
// lost a name during pruning. The source inventory records the target inode
// of every regular file copied in this round.
func (b *nativeTransport) restoreRelinked(from, to string) error {
inodes := map[uint64]bool{}
if err := b.pending.each("relinked", false, func(k, _ []byte) error {
inodes[binary.BigEndian.Uint64(k)] = true
return nil
}); err != nil || len(inodes) == 0 {
return err
}
var rels []string
if err := b.pending.each("paths", false, func(k, v []byte) error {
if e, ok := decodeEntry(v); ok && e.TargetInode != 0 && inodes[e.TargetInode] {
rels = append(rels, string(k))
}
return nil
}); err != nil {
return err
}
for _, rel := range rels {
src := path.Join(from, rel)
n, err := b.source.Stat(src)
if err != nil {
return err
}
if err = restoreNativeMetadata(b.source, b.target, src, path.Join(to, rel), n); err != nil {
return err
}
}
return nil
}
func (b *nativeTransport) Published(p string) { b.verified[p] = true }
func (b *nativeTransport) Commit(ctx context.Context, name string) error {
if err := ctx.Err(); err != nil {
return err
}
if b.base != nil {
if err := b.base.close(); err != nil {
return err
}
b.base = nil
}
return b.pending.commit(b.workspace, name)
}
func (b *nativeTransport) Statistics() TransferStats {
mode := "full"
base := ""
if b.delta {
mode = "snapdiff"
base = b.round.BaseName
}
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(),
SkippedSubtrees: b.skippedSubtrees.Load(),
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 {
if b.config.BandwidthKiB == 0 {
return nil
}
total := b.rateBytes.Add(int64(n))
seconds := float64(total) / float64(b.config.BandwidthKiB*1024)
wait := time.Duration(seconds*float64(time.Second)) - time.Since(b.started)
if wait <= 0 {
return nil
}
timer := time.NewTimer(wait)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func nodeKey(ino uint64) [16]byte {
var b [16]byte
binary.BigEndian.PutUint64(b[:], ino)
return b
}