diff --git a/docs/migration.md b/docs/migration.md index d162f00..6a7a0b9 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -188,7 +188,7 @@ sequenceDiagram M->>T: hardlink aliases, prune surplus entries M->>T: restore directory metadata, deepest first M->>T: sync_fs - M->>V: connect a fresh client to the target + M->>V: connect a fresh client, close the writing client V->>T: compare metadata, links and copied ranges with R(n) M->>T: create snapshot R(n), copy snapshot metadata V->>T: compare snapshot R(n) with R(n) @@ -251,7 +251,11 @@ sequenceDiagram after linking and after removing surplus names. - The writing client sometimes caches a different ctime for directories. The verification before publication therefore reads the target through a - separate, freshly connected client. + freshly connected client. The writing client is closed first and the + fresh client writes from then on. Closing returns all caps of the writer + at once; otherwise the MDS recalls them entry by entry, which in the lab + cost about five seconds per lookup for the files written last. The claim + lock is held through a client of its own, so it survives the change. This behaviour was measured in the lab and is not guaranteed by Ceph; the verification reports every deviation. The atime at the target subsequently diff --git a/internal/migration/access.go b/internal/migration/access.go index ac1d82d..f6b6520 100644 --- a/internal/migration/access.go +++ b/internal/migration/access.go @@ -144,6 +144,9 @@ type TransferStats struct { BlockDiffFiles int64 `json:"blockdiff_files"` SnapDiffEntries int64 `json:"snapdiff_entries"` SkippedSubtrees int64 `json:"skipped_subtrees,omitempty"` + // Seconds is the duration of the round from its start to the commit, + // including verification and snapshot creation. + Seconds float64 `json:"seconds"` } // NewEngine returns an Engine for c.Backend and a Closer that releases its diff --git a/internal/migration/native_access.go b/internal/migration/native_access.go index cc058f6..3a32ae4 100644 --- a/internal/migration/native_access.go +++ b/internal/migration/native_access.go @@ -97,7 +97,38 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io. return nil, err } - fs := a.backend.target + if a.backend.openTarget == nil { + return claimNative(a.backend.target, c, fsid, id) + } + + // The lock lives as long as this client; Verify replaces target. + client, err := a.backend.openTarget() + if err != nil { + return nil, fmt.Errorf("native claim client: %w", err) + } + + f, err := claimNative(client, c, fsid, id) + if err != nil { + client.Close() + return nil, err + } + + return nativeClaim{file: f, client: client}, nil +} + +// nativeClaim is a claim lock held through a client of its own. +type nativeClaim struct { + file storage.File + client storage.FS +} + +func (c nativeClaim) Close() error { + return errors.Join(c.file.Close(), c.client.Close()) +} + +// claimNative creates the claim file for id if needed, locks it through fs +// and checks that it names id. The returned file holds the lock. +func claimNative(fs storage.FS, c Config, fsid, id string) (storage.File, error) { current := "/" for _, component := range []string{".cephmig", "claims"} { current = path.Join(current, component) diff --git a/internal/migration/native_data.go b/internal/migration/native_data.go index 7df0846..d28b694 100644 --- a/internal/migration/native_data.go +++ b/internal/migration/native_data.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "path" + "sync" "syscall" "time" @@ -332,19 +333,23 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { return err } - if b.openVerifier != nil { - v, err := b.openVerifier() + if b.openTarget != nil { + // Replace the writing client before reading the target. Its cache + // may hold a ctime that differs from the MDS, and the MDS would have + // to recall its caps on every entry it wrote last, which in the lab + // cost about five seconds per lookup. Closing it returns all caps at + // once. The engine calls transport methods one at a time, and the + // claim lock is held by a client of its own. + v, err := b.openTarget() if err != nil { return fmt.Errorf("native verification client: %w", err) } - // The engine calls transport methods one at a time. - writer := b.target + err = b.target.Close() b.target = v - defer func() { - b.target = writer - v.Close() - }() + if err != nil { + return fmt.Errorf("close native writing client: %w", err) + } } skipData := b.verified[to] @@ -354,7 +359,40 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { } defer scratch.cleanup() - 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 + // order. Every other entry is checked by one of the workers. + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + workers := b.config.Workers + if workers == 0 { + workers = 8 + } + + type entry struct { + p, rel string + n storage.Node + } + + jobs := make(chan entry, workers*4) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for job := range jobs { + if ctx.Err() != nil { + continue + } + + if err := v.entry(ctx, job.p, job.rel, job.n); err != nil { + cancel(err) + } + } + }() + } + lastProgress := time.Now() var verifiedPaths uint64 err = walkNative(ctx, b.source, from, func(p string, n storage.Node, _ int) error { @@ -369,101 +407,27 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { return err } - targetPath := path.Join(to, rel) - target, err := b.target.Stat(targetPath) - if err != nil { - return err - } - - if err = syncNativeMetadataKnown(b.source, b.target, p, targetPath, n, target, true); err != nil { - return err - } - if n.Kind() == storage.Directory { + if err = v.entry(ctx, p, rel, n); err != nil { + return err + } + return b.skipped(rel) } - if n.Kind() != storage.Directory { - if n.Nlink > 1 { - same, err := index.observe("source", nodeKey(n.Inode), nodeKey(target.Inode)) - if err != nil { - return err - } - - if !same { - return fmt.Errorf("native hardlink group was split at %s", rel) - } - } - - if target.Nlink > 1 { - same, err := index.observe("target", nodeKey(target.Inode), nodeKey(n.Inode)) - if err != nil { - return err - } - - if !same { - return fmt.Errorf("native unrelated files became hardlinked at %s", rel) - } - } + select { + case jobs <- entry{p: p, rel: rel, n: n}: + return nil + case <-ctx.Done(): + return context.Cause(ctx) } - - switch n.Kind() { - case storage.Directory: - case storage.Regular: - if n.Size != target.Size { - return fmt.Errorf("native size mismatch at %s", targetPath) - } - - canonical, err := b.pending.get("groups", nativeInodeKey(n.Inode)) - if err != nil { - return err - } - - if !skipData && string(canonical) == rel { - full, err := b.pending.get("full", []byte(rel)) - if err != nil { - return err - } - - if full != nil { - if err = b.compareRange(ctx, p, targetPath, 0, n.Size); err != nil { - return err - } - } else { - if err = b.pending.ranges(rel, func(off, length uint64) error { return b.compareRange(ctx, p, targetPath, off, length) }); err != nil { - return err - } - } - } - - // Only live target identities may be reused as the next blockdiff base. - if to == b.round.TargetPath && !skipData { - return b.pending.putEntryIfChanged(rel, baseEntry{Inode: n.Inode, Version: n.Version, Size: n.Size, TargetInode: target.Inode}) - } - - case storage.Symlink: - a, err := b.source.Readlink(p) - if err != nil { - return err - } - - v, err := b.target.Readlink(targetPath) - if err != nil { - return err - } - - if a != v { - return fmt.Errorf("native symlink mismatch at %s", rel) - } - - default: - if n.Rdev != target.Rdev { - return fmt.Errorf("native device mismatch at %s", rel) - } - } - - return nil }) + close(jobs) + wg.Wait() + if cause := context.Cause(ctx); cause != nil && (err == nil || errors.Is(err, context.Canceled)) { + err = cause + } + if err != nil { return err } @@ -475,6 +439,120 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error { return err } +// nativeVerification holds the state of one Verify call that its workers +// share. +type nativeVerification struct { + b *nativeTransport + to string + skipData bool + mu sync.Mutex // guards index, which holds one write transaction + index *linkIndex +} + +// observe records a hardlink relation in the scratch index. +func (v *nativeVerification) observe(bucket string, key, value [16]byte) (bool, error) { + v.mu.Lock() + defer v.mu.Unlock() + return v.index.observe(bucket, key, value) +} + +// entry checks one source entry p against its target copy. It is safe for +// concurrent use. +func (v *nativeVerification) entry(ctx context.Context, p, rel string, n storage.Node) error { + b := v.b + targetPath := path.Join(v.to, rel) + target, err := b.target.Stat(targetPath) + if err != nil { + return err + } + + if err = syncNativeMetadataKnown(b.source, b.target, p, targetPath, n, target, true); err != nil { + return err + } + + if n.Kind() == storage.Directory { + return nil + } + + if n.Nlink > 1 { + same, err := v.observe("source", nodeKey(n.Inode), nodeKey(target.Inode)) + if err != nil { + return err + } + + if !same { + return fmt.Errorf("native hardlink group was split at %s", rel) + } + } + + if target.Nlink > 1 { + same, err := v.observe("target", nodeKey(target.Inode), nodeKey(n.Inode)) + if err != nil { + return err + } + + if !same { + return fmt.Errorf("native unrelated files became hardlinked at %s", rel) + } + } + + switch n.Kind() { + case storage.Regular: + if n.Size != target.Size { + return fmt.Errorf("native size mismatch at %s", targetPath) + } + + canonical, err := b.pending.get("groups", nativeInodeKey(n.Inode)) + if err != nil { + return err + } + + if !v.skipData && string(canonical) == rel { + full, err := b.pending.get("full", []byte(rel)) + if err != nil { + return err + } + + if full != nil { + if err = b.compareRange(ctx, p, targetPath, 0, n.Size); err != nil { + return err + } + } else { + if err = b.pending.ranges(rel, func(off, length uint64) error { return b.compareRange(ctx, p, targetPath, off, length) }); err != nil { + return err + } + } + } + + // Only live target identities may be reused as the next blockdiff base. + if v.to == b.round.TargetPath && !v.skipData { + return b.pending.putEntryIfChanged(rel, baseEntry{Inode: n.Inode, Version: n.Version, Size: n.Size, TargetInode: target.Inode}) + } + + case storage.Symlink: + a, err := b.source.Readlink(p) + if err != nil { + return err + } + + t, err := b.target.Readlink(targetPath) + if err != nil { + return err + } + + if a != t { + return fmt.Errorf("native symlink mismatch at %s", rel) + } + + default: + if n.Rdev != target.Rdev { + return fmt.Errorf("native device mismatch at %s", rel) + } + } + + return nil +} + func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error { if err := b.pending.requireInventory(); err != nil { return err diff --git a/internal/migration/native_factory_ceph.go b/internal/migration/native_factory_ceph.go index 8254ee8..e23c536 100644 --- a/internal/migration/native_factory_ceph.go +++ b/internal/migration/native_factory_ceph.go @@ -26,7 +26,7 @@ func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer) return Engine{}, nil, err } - verifier := func() (storage.FS, error) { + openTarget := func() (storage.FS, error) { v, err := cephfsnative.Open(options(c.Target)) if err != nil { return nil, err @@ -35,6 +35,6 @@ func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer) return v, nil } - backend := &nativeTransport{source: source, target: target, config: c, log: log, openVerifier: verifier} + backend := &nativeTransport{source: source, target: target, config: c, log: log, openTarget: openTarget} return Engine{Exec: x, Log: log, Transport: backend, Access: nativeAccess{backend}}, backend, nil } diff --git a/internal/migration/native_transport.go b/internal/migration/native_transport.go index 3032d1e..05b4bd9 100644 --- a/internal/migration/native_transport.go +++ b/internal/migration/native_transport.go @@ -27,11 +27,11 @@ type nativeTransport struct { source, target storage.FS config Config - // openVerifier opens a separate client of the target for Verify. The - // writing client may cache a ctime that differs from the MDS, so only a - // client without caps of its own sees what other clients see. Nil means - // verify through target. - openVerifier func() (storage.FS, error) + // 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 @@ -629,7 +629,8 @@ 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(), - SkippedSubtrees: b.skippedSubtrees.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, diff --git a/internal/migration/native_verify_test.go b/internal/migration/native_verify_test.go new file mode 100644 index 0000000..0d55c0d --- /dev/null +++ b/internal/migration/native_verify_test.go @@ -0,0 +1,302 @@ +package migration + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "git.zb-server.de/Sebi/CephfsMig/internal/storage" +) + +// diskFS is a read-only storage.FS over the local file system. Stat reports +// the mtime as ctime and leaves the other times zero, so two copies with +// equal mtimes compare as equal metadata. Symlinks report no times. +type diskFS struct{ storage.FS } + +func (diskFS) Stat(p string) (storage.Node, error) { + var s syscall.Stat_t + if err := syscall.Lstat(p, &s); err != nil { + return storage.Node{}, err + } + + mtime := time.Unix(s.Mtim.Sec, s.Mtim.Nsec) + if s.Mode&syscall.S_IFMT == syscall.S_IFLNK { + mtime = time.Time{} // os.Chtimes cannot set symlink times. + } + + return storage.Node{Mode: s.Mode, Inode: s.Ino, Nlink: uint64(s.Nlink), Size: uint64(s.Size), + UID: s.Uid, GID: s.Gid, Mtime: mtime, Ctime: mtime}, nil +} + +func (diskFS) OpenDir(p string) (storage.DirectoryStream, error) { + d, err := os.Open(p) + if err != nil { + return nil, err + } + + return &diskDir{file: d, path: p}, nil +} + +func (diskFS) Open(p string, _ int, _ uint32) (storage.File, error) { + f, err := os.Open(p) + if err != nil { + return nil, err + } + + return diskFile{f}, nil +} + +func (diskFS) Readlink(p string) (string, error) { return os.Readlink(p) } +func (diskFS) ListXattr(string) ([]string, error) { return nil, nil } +func (diskFS) GetXattr(string, string) ([]byte, error) { return nil, syscall.ENODATA } + +type diskFile struct{ *os.File } + +func (diskFile) Lock(uint64) error { return nil } +func (diskFile) PunchHole(int64, int64) error { return syscall.ENOTSUP } + +type diskDir struct { + file *os.File + path string +} + +func (d *diskDir) Next() (*storage.Entry, error) { + es, err := d.file.ReadDir(1) + if len(es) == 0 { + if err == nil { + err = io.EOF + } + + return nil, err + } + + n, err := (diskFS{}).Stat(filepath.Join(d.path, es[0].Name())) + return &storage.Entry{Name: es[0].Name(), Node: n}, err +} + +func (d *diskDir) Close() error { return d.file.Close() } + +// verifyTree builds the same tree under src and dst: files spread over +// directories, one hardlink pair and one symlink. +func verifyTree(t *testing.T, src, dst string, files int) { + t.Helper() + stamp := time.Unix(1700000000, 0) + for _, root := range []string{src, dst} { + for i := 0; i < files; i++ { + rel := filepath.Join(fmt.Sprintf("d%02d", i%7), fmt.Sprintf("f%04d", i)) + if err := os.MkdirAll(filepath.Join(root, filepath.Dir(rel)), 0755); err != nil { + t.Fatal(err) + } + + p := filepath.Join(root, rel) + if err := os.WriteFile(p, []byte(fmt.Sprintf("payload %d", i)), 0644); err != nil { + t.Fatal(err) + } + + if err := os.Chtimes(p, stamp, stamp.Add(time.Duration(i)*time.Second)); err != nil { + t.Fatal(err) + } + } + + if err := os.Link(filepath.Join(root, "d00", "f0000"), filepath.Join(root, "hard")); err != nil { + t.Fatal(err) + } + + if err := os.Symlink("d00/f0000", filepath.Join(root, "soft")); err != nil { + t.Fatal(err) + } + } + + // Directory mtimes changed while their entries were created. + for _, root := range []string{src, dst} { + if err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { + if err != nil || !d.IsDir() { + return err + } + + return os.Chtimes(p, stamp, stamp) + }); err != nil { + t.Fatal(err) + } + } +} + +// verifyIndex records the inventory of src in a fresh index, as the copy +// phase does: every path, the canonical path of every inode and the files +// copied in full. +func verifyIndex(t *testing.T, src string) *nativeIndex { + t.Helper() + x, err := createNativeIndex(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { x.close() }) + err = filepath.WalkDir(src, func(p string, d os.DirEntry, err error) error { + if err != nil { + return err + } + + rel, err := filepath.Rel(src, p) + if err != nil { + return err + } + + n, err := (diskFS{}).Stat(p) + if err != nil { + return err + } + + if err = x.put("paths", []byte(rel), encodeEntry(baseEntry{Inode: n.Inode})); err != nil { + return err + } + + if n.Kind() != storage.Regular { + return nil + } + + if old, err := x.get("groups", nativeInodeKey(n.Inode)); err != nil || old != nil { + return err + } + + if err = x.put("groups", nativeInodeKey(n.Inode), []byte(rel)); err != nil { + return err + } + + return x.put("full", []byte(rel), []byte{1}) + }) + if err != nil { + t.Fatal(err) + } + + if err := x.put("meta", []byte("inventory_complete"), []byte{1}); err != nil { + t.Fatal(err) + } + + return x +} + +func TestNativeVerifyParallel(t *testing.T) { + for _, tc := range []struct { + name string + damage func(t *testing.T, dst string) + want string + }{ + {"identical", nil, ""}, + {"content", func(t *testing.T, dst string) { + p := filepath.Join(dst, "d03", "f0150") + info, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(p, []byte("payload 15X"), 0644); err != nil { + t.Fatal(err) + } + + if err := os.Chtimes(p, info.ModTime(), info.ModTime()); err != nil { + t.Fatal(err) + } + + if err := os.Chtimes(filepath.Dir(p), time.Unix(1700000000, 0), time.Unix(1700000000, 0)); err != nil { + t.Fatal(err) + } + }, "content mismatch"}, + {"split hardlink", func(t *testing.T, dst string) { + p := filepath.Join(dst, "hard") + info, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + + data, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + + if err := os.Remove(p); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(p, data, 0644); err != nil { + t.Fatal(err) + } + + for _, x := range []string{p, dst} { + mtime := info.ModTime() + if x == dst { + mtime = time.Unix(1700000000, 0) + } + + if err := os.Chtimes(x, mtime, mtime); err != nil { + t.Fatal(err) + } + } + }, "hardlink group was split"}, + } { + t.Run(tc.name, func(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + verifyTree(t, src, dst, 400) + if tc.damage != nil { + tc.damage(t, dst) + } + + b := nativeTransport{source: diskFS{}, target: diskFS{}, pending: verifyIndex(t, src), + workspace: t.TempDir(), config: Config{Workers: 16}, + round: Round{SourcePath: src, TargetPath: dst}, verified: map[string]bool{}} + err := b.Verify(context.Background(), src, dst) + if tc.want == "" { + if err != nil { + t.Fatal(err) + } + + if !b.verified[dst] || b.checked.Load() == 0 { + t.Fatalf("verified=%v checked=%d", b.verified[dst], b.checked.Load()) + } + + return + } + + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error %v; want %q", err, tc.want) + } + }) + } +} + +// closingFS records whether Close was called. +type closingFS struct { + diskFS + closed bool +} + +func (f *closingFS) Close() error { f.closed = true; return nil } + +func TestNativeVerifyReplacesWriter(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + verifyTree(t, src, dst, 20) + writer := &closingFS{} + var opened []*closingFS + b := nativeTransport{source: diskFS{}, target: writer, pending: verifyIndex(t, src), + workspace: t.TempDir(), round: Round{SourcePath: src, TargetPath: dst}, verified: map[string]bool{}, + openTarget: func() (storage.FS, error) { + f := &closingFS{} + opened = append(opened, f) + return f, nil + }} + + if err := b.Verify(context.Background(), src, dst); err != nil { + t.Fatal(err) + } + + if !writer.closed || len(opened) != 1 || b.target != storage.FS(opened[0]) || opened[0].closed { + t.Fatalf("writer closed=%v, opened=%d, target replaced=%v", writer.closed, len(opened), + len(opened) == 1 && b.target == storage.FS(opened[0])) + } +}