package migration import ( "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 log io.Writer identity string round Round workspace string pending, base *nativeIndex delta bool snapRoot, snapRel string verified map[string]bool visited, copied, written, checked, blockFiles, diffEntries atomic.Int64 rateBytes atomic.Int64 started time.Time } 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.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 { 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) // 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) } return nil }); err != nil { return err } if err = b.prune(ctx, from, to); err != nil { return err } // Child creation/deletion has finished; restore directory metadata last. 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 syncNativeMetadata(b.source, b.target, src, dst, n, false) }); 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, _ 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.pending.put("delete", []byte(rel), []byte{1}) } return nil }) if err != nil { return err } return b.pending.each("delete", true, func(k, _ []byte) error { return removeNative(ctx, b.target, path.Join(to, string(k))) }) } 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()} } 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 }