docs: add package and doc comments for exported identifiers

Document every exported type, function and method in the migration,
storage and cephfsnative packages and add package comments for
migration and the cephmig command, following the commentary rules of
Effective Go. Comments on unexported helpers now start with the name
they describe.

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 18:07:48 +01:00
1 parent 7413b9a43a
commit c2ef7a6c3b
12 files changed
+150 -7

No files matched your search

+13 -1
View File
@@ -55,21 +55,32 @@ func (e Engine) access() Access {
}
return mountedAccess{}
}
// Inspect checks both endpoints without changing them and reports what a
// migration would transfer.
func (e Engine) Inspect(ctx context.Context, c Config) (*Inspection, error) {
return e.access().Inspect(ctx, c, e.Exec)
}
// Round describes one snapshot transfer handed to a RoundTransport.
// BaseName and BaseSourcePath name the last completed snapshot, if any,
// which allows an incremental transfer.
type Round struct {
SourcePath, TargetPath string
BaseName, BaseSourcePath string
Name, StatePath string
}
// RoundTransport is a Transport that keeps state across a snapshot round,
// such as the native backend's on-disk index.
type RoundTransport interface {
BeginRound(context.Context, Round) error
Published(string)
Commit(context.Context, string) error
Statistics() TransferStats
}
// TransferStats summarizes the work done for one snapshot round.
type TransferStats struct {
Mode string `json:"mode"`
BaseSnapshot string `json:"base_snapshot,omitempty"`
@@ -81,7 +92,8 @@ type TransferStats struct {
SnapDiffEntries int64 `json:"snapdiff_entries"`
}
// NewEngine never silently falls back from native I/O to mounted/rsync I/O.
// NewEngine returns an Engine for c.Backend and a Closer that releases its
// connections. It never silently falls back from native I/O to mounted/rsync I/O.
func NewEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) {
if c.Backend == "native" {
return openNativeEngine(ctx, c, x, log)
+11 -2
View File
@@ -10,6 +10,9 @@ import (
"strings"
)
// Endpoint describes how to reach one side of a migration: the Ceph
// client identity and configuration, the subvolume and, for the rsync
// backend, the local mount of the CephFS filesystem root.
type Endpoint struct {
User string `json:"user,omitempty"`
Config string `json:"config"`
@@ -20,6 +23,8 @@ type Endpoint struct {
Mount string `json:"mount,omitempty"`
}
// Config is the JSON migration configuration read by ReadConfig.
// Backend selects "native" (libcephfs) or "rsync" (the default).
type Config struct {
Backend string `json:"backend,omitempty"`
Workers int `json:"workers,omitempty"`
@@ -28,6 +33,8 @@ type Config struct {
BandwidthKiB int64 `json:"bandwidth_kib,omitempty"`
}
// ReadConfig reads exactly one JSON object from the regular file at path,
// rejects unknown fields and returns the validated configuration.
func ReadConfig(path string) (Config, error) {
var c Config
f, err := os.Open(path)
@@ -58,6 +65,8 @@ func validName(s string) bool {
!strings.ContainsAny(s, "/\x00\n\r")
}
// Validate checks names, paths, worker and bandwidth limits and reports
// the first problem found.
func (c Config) Validate() error {
if c.Backend != "" && c.Backend != "rsync" && c.Backend != "native" {
return errors.New("backend must be native or rsync")
@@ -105,8 +114,8 @@ func beneath(root, path string) bool {
}
func overlaps(a, b string) bool { return beneath(a, b) || beneath(b, a) }
// Resolve only real directories below the configured filesystem mount. No symlink
// component is permitted, including in the mount path.
// dataPath resolves cephPath to a real directory below the filesystem mount
// root. No symlink component is permitted, including in the mount path.
func dataPath(root, cephPath string) (string, error) {
if !filepath.IsAbs(cephPath) || filepath.Clean(cephPath) != cephPath || cephPath == "/" {
return "", fmt.Errorf("invalid Ceph path %q", cephPath)
+9
View File
@@ -0,0 +1,9 @@
// Package migration implements the snapshot-based migration of a CephFS
// subvolume between two clusters.
//
// A migration is a sequence of rounds. Each round creates or picks a source
// snapshot, copies it with a Transport, verifies the target and publishes a
// target snapshot of the same name. Progress is recorded in a State journal so
// that every step can be resumed. Two backends exist: rsync over mounted
// filesystems and a native libcephfs transport (build tag ceph).
package migration
+12 -2
View File
@@ -18,6 +18,8 @@ import (
"time"
)
// Engine runs the snapshot-based migration workflow. Transport moves the
// data; Access, if nil, defaults to mounted filesystem access.
type Engine struct {
Exec Executor
Transport Transport
@@ -34,6 +36,8 @@ type endpointInfo struct {
Encryption string `json:"enctag"`
Earmark string `json:"earmark"`
}
// Inspection is the result of Engine.Inspect.
type Inspection struct {
SourceFSID string `json:"source_fsid"`
TargetFSID string `json:"target_fsid"`
@@ -45,6 +49,8 @@ type Inspection struct {
Notes []string `json:"notes"`
}
// SnapshotIdentityNote documents the accepted deviation that native
// snapshot identities are not preserved at the target.
const SnapshotIdentityNote = "Native snapshot IDs and Ceph birthtimes are recreated at the target; original creation timestamps are recorded in the migration journal."
func (e Engine) log(format string, args ...any) {
@@ -159,8 +165,8 @@ func emptyDirectory(path string) error {
return nil
}
// The claim is outside the migrated tree and survives deletion of the local
// journal. O_EXCL prevents two different jobs from adopting the same target.
// claimTarget locks the target subvolume for the job id. The claim is outside
// the migrated tree and survives deletion of the local journal. O_EXCL prevents two different jobs from adopting the same target.
func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) {
key := sha256.Sum256([]byte(fsid + "\x00" + ep.Filesystem + "\x00" + ep.Group + "\x00" + ep.Subvolume))
dir := filepath.Join(root, ".cephmig", "claims")
@@ -230,6 +236,10 @@ func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, erro
return s, err
}
// Sync performs one migration round: it resumes unfinished snapshots,
// transfers newly discovered ones and then a fresh snapshot of the live
// subvolume. With final set, writers must be stopped; Sync then verifies
// the complete inventory and marks the job ready for cutover.
func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool) error {
if err := c.Validate(); err != nil {
return err
+2 -1
View File
@@ -84,7 +84,8 @@ func inodeIdentity(info os.FileInfo) ([16]byte, uint64, error) {
return key, uint64(st.Nlink), nil
}
// In repair mode remove only excess target hardlinks. Missing paths are then
// hardlinkTopology compares the hard-link groups of src and dst.
// In repair mode it removes only excess target hardlinks. Missing paths are then
// recreated by the copy backend. In verification mode check both directions:
// source groups must stay joined, and unrelated source files must stay separate.
func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repair bool) (result error) {
+3 -1
View File
@@ -115,11 +115,13 @@ func xattr(path, key string) ([]byte, error) {
var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"}
// ReadDir batches keep a single very large directory from exhausting memory.
// walkDirectories calls visit for every directory below root.
func walkDirectories(ctx context.Context, root string, visit func(string) error) error {
return walkTree(ctx, root, visit, nil)
}
// walkTree walks root depth-first, skipping .snap. ReadDir batches keep a
// single very large directory from exhausting memory.
func walkTree(ctx context.Context, root string, visitDir func(string) error, visitFile func(string, os.FileInfo) error) error {
var walk func(string, int) error
walk = func(path string, depth int) error {
+12
View File
@@ -13,18 +13,28 @@ import (
"time"
)
// Executor runs an external command, writing its standard output to the
// given writer.
type Executor interface {
Exec(context.Context, io.Writer, string, ...string) error
}
// Process is the Executor used in production. It runs commands in their own
// process group and mirrors their standard error to Stderr, if set.
type Process struct{ Stderr io.Writer }
// ProcessError reports a failed external command. Diagnostic holds the tail
// of its standard error; the arguments are deliberately omitted.
type ProcessError struct {
Name string
Err error
Diagnostic string
}
// Error implements the error interface.
func (e *ProcessError) Error() string { return fmt.Sprintf("%s failed: %v", e.Name, e.Err) }
// Unwrap returns the underlying error.
func (e *ProcessError) Unwrap() error { return e.Err }
type tailBuffer struct{ data []byte }
@@ -43,6 +53,8 @@ func (b *tailBuffer) Write(p []byte) (int, error) {
return n, nil
}
// Exec runs name with args under ctx. On cancellation the whole process
// group receives SIGTERM.
func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdout = out
+6
View File
@@ -10,11 +10,14 @@ import (
"strings"
)
// Transport copies a snapshot tree to the target and verifies the result.
type Transport interface {
Copy(context.Context, string, string) error
Verify(context.Context, string, string) error
}
// Rsync is the Transport that copies between mounted CephFS trees with
// rsync. BandwidthKiB limits the transfer rate when positive.
type Rsync struct {
Exec Executor
Log io.Writer
@@ -30,6 +33,8 @@ func (r Rsync) args(src, dst string) []string {
}
return append(a, "--", src+"/", dst+"/")
}
// Copy mirrors src into dst, including hard links, ACLs and xattrs.
func (r Rsync) Copy(ctx context.Context, src, dst string) error {
for attempt := 0; attempt < 2; attempt++ {
err := r.Exec.Exec(ctx, r.Log, "rsync", r.args(src, dst)...)
@@ -53,6 +58,7 @@ type differences struct{ n int64 }
func (d *differences) Write(p []byte) (int, error) { d.n += int64(len(p)); return len(p), nil }
// Verify runs rsync as a dry run and fails if any difference remains.
func (r Rsync) Verify(ctx context.Context, src, dst string) error {
args := append([]string{"--dry-run", "--itemize-changes", "--out-format=%i"}, r.args(src, dst)...)
var d differences
+8
View File
@@ -13,6 +13,8 @@ import (
const stateVersion = 1
// Snapshot is the journal record of one source snapshot and its transfer
// to the target.
type Snapshot struct {
Name string `json:"name"`
CreatedAt string `json:"source_created_at"`
@@ -24,6 +26,8 @@ type Snapshot struct {
Stats *TransferStats `json:"transfer,omitempty"`
}
// State is the persistent migration journal. It is written atomically
// after every step so that an interrupted run can be resumed.
type State struct {
Version int `json:"version"`
ID string `json:"id"`
@@ -38,6 +42,8 @@ type State struct {
LiveSnapshot string `json:"live_snapshot,omitempty"`
}
// LoadState reads and validates the migration journal at path. Symbolic
// links are not followed.
func LoadState(path string) (*State, error) {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
@@ -98,6 +104,8 @@ func LoadState(path string) (*State, error) {
return &s, nil
}
// SaveState atomically replaces the journal at path with s and syncs the
// containing directory.
func SaveState(path string, s *State) error {
return atomicJSON(path, s)
}