diff --git a/cmd/cephmig/main.go b/cmd/cephmig/main.go index 820f174..0af2fc3 100644 --- a/cmd/cephmig/main.go +++ b/cmd/cephmig/main.go @@ -1,3 +1,18 @@ +// Command cephmig migrates a CephFS subvolume, including its snapshots, +// between two Ceph clusters while the application keeps running. +// +// Usage: +// +// cephmig doctor +// cephmig inspect --config FILE +// cephmig sync --config FILE --state FILE +// cephmig finalize --config FILE --state FILE --writers-stopped +// cephmig status --state FILE +// +// inspect checks both clusters without changing them. sync copies the +// current state and may be repeated. finalize performs the last round after +// all writers are stopped and marks the job ready for cutover. status prints +// the migration journal. All results are written to standard output as JSON. package main import ( diff --git a/internal/cephfsnative/client_ceph.go b/internal/cephfsnative/client_ceph.go index bd86a90..f6c521d 100644 --- a/internal/cephfsnative/client_ceph.go +++ b/internal/cephfsnative/client_ceph.go @@ -58,6 +58,7 @@ import ( "git.zb-server.de/Sebi/CephfsMig/internal/storage" ) +// Client is a libcephfs connection that implements storage.FS. type Client struct{ mount *C.struct_ceph_mount_info } func errno(ret C.int) error { @@ -70,6 +71,9 @@ func str(s string) (*C.char, func()) { p := C.CString(s) return p, func() { C.free(unsafe.Pointer(p)) } } + +// Open connects to the cluster described by o and mounts the root of the +// selected filesystem in userspace. func Open(o storage.Options) (*Client, error) { c := &Client{} user := strings.TrimPrefix(o.User, "client.") @@ -117,6 +121,8 @@ func Open(o storage.Options) (*Client, error) { failed = false return c, nil } + +// Close unmounts and releases the connection. It is safe to call twice. func (c *Client) Close() error { if c.mount != nil { C.ceph_shutdown(c.mount) @@ -130,6 +136,8 @@ func node(s C.struct_ceph_statx) storage.Node { Rdev: uint64(s.stx_rdev), UID: uint32(s.stx_uid), GID: uint32(s.stx_gid), Mtime: time.Unix(int64(s.stx_mtime.tv_sec), int64(s.stx_mtime.tv_nsec))} } + +// Stat returns the attributes of path without following a final symlink. func (c *Client) Stat(path string) (storage.Node, error) { p, f := str(path) defer f() @@ -148,6 +156,8 @@ func nativeStatFlags(path string) C.int { } return flags } + +// Open opens the file at path with open(2) flags and mode. func (c *Client) Open(path string, flags int, mode uint32) (storage.File, error) { p, f := str(path) defer f() @@ -215,6 +225,7 @@ type dir struct { flags C.int } +// OpenDir opens the directory at path for iteration. func (c *Client) OpenDir(path string) (storage.DirectoryStream, error) { p, f := str(path) defer f() @@ -244,21 +255,29 @@ func (d *dir) Next() (*storage.Entry, error) { } } func (d *dir) Close() error { return errno(C.ceph_closedir(d.client.mount, d.handle)) } + +// Mkdir creates a directory. func (c *Client) Mkdir(path string, mode uint32) error { p, f := str(path) defer f() return errno(C.ceph_mkdir(c.mount, p, C.mode_t(mode))) } + +// Unlink removes a non-directory entry. func (c *Client) Unlink(path string) error { p, f := str(path) defer f() return errno(C.ceph_unlink(c.mount, p)) } + +// Rmdir removes an empty directory. func (c *Client) Rmdir(path string) error { p, f := str(path) defer f() return errno(C.ceph_rmdir(c.mount, p)) } + +// Rename renames a to b. func (c *Client) Rename(a, b string) error { p, f := str(a) defer f() @@ -266,6 +285,8 @@ func (c *Client) Rename(a, b string) error { defer g() return errno(C.ceph_rename(c.mount, p, q)) } + +// Link creates the hard link b to a without following a symlink at a. func (c *Client) Link(a, b string) error { p, f := str(a) defer f() @@ -275,6 +296,8 @@ func (c *Client) Link(a, b string) error { defer h() return errno(C.cm_link_nofollow(c.mount, p, q, name)) } + +// Symlink creates the symbolic link b pointing to a. func (c *Client) Symlink(a, b string) error { p, f := str(a) defer f() @@ -282,11 +305,15 @@ func (c *Client) Symlink(a, b string) error { defer g() return errno(C.ceph_symlink(c.mount, p, q)) } + +// Mknod creates a special file. func (c *Client) Mknod(path string, mode uint32, dev uint64) error { p, f := str(path) defer f() return errno(C.ceph_mknod(c.mount, p, C.mode_t(mode), C.dev_t(dev))) } + +// Readlink returns the target of a symbolic link. func (c *Client) Readlink(path string) (string, error) { p, f := str(path) defer f() @@ -302,11 +329,15 @@ func (c *Client) Readlink(path string) (string, error) { } return "", errors.New("symlink target exceeds 1 MiB") } + +// SetAttr sets numeric owner, mode and mtime without following symlinks. func (c *Client) SetAttr(path string, n storage.Node) error { p, f := str(path) defer f() return errno(C.cm_attr(c.mount, p, C.uint(n.Mode), C.uint(n.UID), C.uint(n.GID), C.long(n.Mtime.Unix()), C.long(n.Mtime.Nanosecond()))) } + +// GetXattr returns the value of an extended attribute. func (c *Client) GetXattr(path, key string) ([]byte, error) { p, f := str(path) defer f() @@ -325,6 +356,8 @@ func (c *Client) GetXattr(path, key string) ([]byte, error) { } return nil, errors.New("xattr exceeds 1 MiB") } + +// ListXattr returns the names of all extended attributes of path. func (c *Client) ListXattr(path string) ([]string, error) { p, f := str(path) defer f() @@ -347,6 +380,8 @@ func (c *Client) ListXattr(path string) ([]string, error) { } return nil, errors.New("xattr list exceeds 1 MiB") } + +// SetXattr sets an extended attribute. func (c *Client) SetXattr(path, key string, b []byte) error { p, f := str(path) defer f() @@ -358,6 +393,8 @@ func (c *Client) SetXattr(path, key string, b []byte) error { } return errno(C.ceph_lsetxattr(c.mount, p, k, ptr, C.size_t(len(b)), 0)) } + +// RemoveXattr removes an extended attribute. func (c *Client) RemoveXattr(path, key string) error { p, f := str(path) defer f() @@ -365,10 +402,14 @@ func (c *Client) RemoveXattr(path, key string) error { defer g() return errno(C.ceph_lremovexattr(c.mount, p, k)) } + +// Sync flushes all dirty data and metadata of the filesystem. func (c *Client) Sync() error { return errno(C.ceph_sync_fs(c.mount)) } type snapDiff struct{ info C.struct_ceph_snapdiff_info } +// SnapDiff lists the entries below root/rel that differ between +// snapshots a and b. func (c *Client) SnapDiff(root, rel, a, b string) (storage.DiffStream, error) { p, f := str(root) defer f() @@ -408,6 +449,8 @@ type blockDiff struct { done bool } +// BlockDiff lists the changed extents of the file root/rel between +// snapshots a and b. func (c *Client) BlockDiff(root, rel, a, b string) (storage.BlockStream, error) { p, f := str(root) defer f() diff --git a/internal/migration/access.go b/internal/migration/access.go index 48ca5c2..b84e3dc 100644 --- a/internal/migration/access.go +++ b/internal/migration/access.go @@ -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) diff --git a/internal/migration/config.go b/internal/migration/config.go index 802e93b..21b1c1c 100644 --- a/internal/migration/config.go +++ b/internal/migration/config.go @@ -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) diff --git a/internal/migration/doc.go b/internal/migration/doc.go new file mode 100644 index 0000000..3d168f3 --- /dev/null +++ b/internal/migration/doc.go @@ -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 diff --git a/internal/migration/engine.go b/internal/migration/engine.go index eba94f0..c6a1a01 100644 --- a/internal/migration/engine.go +++ b/internal/migration/engine.go @@ -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 diff --git a/internal/migration/hardlinks.go b/internal/migration/hardlinks.go index 04ad584..6ad5251 100644 --- a/internal/migration/hardlinks.go +++ b/internal/migration/hardlinks.go @@ -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) { diff --git a/internal/migration/linux.go b/internal/migration/linux.go index c9094d2..8c97888 100644 --- a/internal/migration/linux.go +++ b/internal/migration/linux.go @@ -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 { diff --git a/internal/migration/process.go b/internal/migration/process.go index b1fdeec..4ced8a0 100644 --- a/internal/migration/process.go +++ b/internal/migration/process.go @@ -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 diff --git a/internal/migration/rsync.go b/internal/migration/rsync.go index e500a19..a531876 100644 --- a/internal/migration/rsync.go +++ b/internal/migration/rsync.go @@ -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 diff --git a/internal/migration/state.go b/internal/migration/state.go index a97e884..b257e50 100644 --- a/internal/migration/state.go +++ b/internal/migration/state.go @@ -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) } diff --git a/internal/storage/fs.go b/internal/storage/fs.go index f51cea1..f25af36 100644 --- a/internal/storage/fs.go +++ b/internal/storage/fs.go @@ -6,6 +6,7 @@ import ( "time" ) +// Node holds the inode attributes the copier needs. type Node struct { Mode uint32 Inode, Version, Nlink, Size, Rdev uint64 @@ -13,6 +14,7 @@ type Node struct { Mtime time.Time } +// File type bits of Node.Mode, as in stat(2). const ( TypeMask uint32 = 0170000 Regular uint32 = 0100000 @@ -24,16 +26,22 @@ const ( CharDevice uint32 = 0020000 ) +// Kind returns the file type bits of n.Mode. func (n Node) Kind() uint32 { return n.Mode & TypeMask } +// Entry is a single directory entry. type Entry struct { Name string Node Node } + +// DirectoryStream iterates over a directory. Next returns io.EOF at the end. type DirectoryStream interface { Next() (*Entry, error) Close() error } + +// File is an open regular file. type File interface { io.ReaderAt io.WriterAt @@ -43,16 +51,23 @@ type File interface { Lock(uint64) error PunchHole(int64, int64) error } + +// DiffStream yields the paths that differ between two snapshots. type DiffStream interface { Next() (string, error) Close() error } + +// Extent is a changed byte range of a file. type Extent struct{ Offset, Length uint64 } + +// BlockStream yields batches of changed extents between two snapshots. type BlockStream interface { Next() ([]Extent, error) Close() error } +// FS is the filesystem interface implemented by the native libcephfs client. type FS interface { Stat(string) (Node, error) // Never follows the final symlink. Open(string, int, uint32) (File, error) @@ -76,4 +91,5 @@ type FS interface { Close() error } +// Options identifies the cluster, credentials and filesystem to connect to. type Options struct{ Config, Keyring, User, Filesystem string }