chore: import CephMig prototype

Initial import of the existing CephFS subvolume migration prototype,
including the native libcephfs transport, rsync backend, local Ceph
lab environment and integration tests.

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:05:53 +01:00
commit 7705ed3eaf
58 files changed
+8769

No files matched your search

+447
View File
@@ -0,0 +1,447 @@
//go:build ceph && cgo
// Package cephfsnative provides a small binding to the installed libcephfs ABI.
// Client handles are userspace connections, not operating-system/FUSE mounts.
package cephfsnative
/*
#cgo CFLAGS: -D_FILE_OFFSET_BITS=64 -D_GNU_SOURCE
#cgo LDFLAGS: -lcephfs
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <cephfs/libcephfs.h>
static int cm_stat(struct ceph_mount_info *m, const char *p, struct ceph_statx *s,int flags) {
return ceph_statx(m,p,s,CEPH_STATX_BASIC_STATS|CEPH_STATX_VERSION,flags);
}
static int cm_attr(struct ceph_mount_info *m,const char *p,unsigned mode,unsigned uid,
unsigned gid,long sec,long nsec) {
struct ceph_statx s = {0};
s.stx_mode=mode; s.stx_uid=uid; s.stx_gid=gid;
s.stx_mtime.tv_sec=sec; s.stx_mtime.tv_nsec=nsec;
int mask=CEPH_SETATTR_UID|CEPH_SETATTR_GID|CEPH_SETATTR_MTIME;
if ((mode&S_IFMT)!=S_IFLNK) mask|=CEPH_SETATTR_MODE;
return ceph_setattrx(m,p,&s,mask,AT_SYMLINK_NOFOLLOW);
}
// ceph_link resolves a symbolic-link source. Use inode-based linking so the
// link itself, including a dangling symlink, is shared instead of its referent.
static int cm_link_nofollow(struct ceph_mount_info *m,const char *oldpath,
const char *newparent,const char *name) {
const UserPerm *perms=ceph_mount_perms(m);
Inode *in=NULL,*parent=NULL;
struct ceph_statx s={0};
int ret=ceph_ll_walk(m,oldpath,&in,&s,CEPH_STATX_BASIC_STATS,AT_SYMLINK_NOFOLLOW,perms);
if (ret<0) return ret;
ret=ceph_ll_walk(m,newparent,&parent,&s,CEPH_STATX_BASIC_STATS,0,perms);
if (ret==0) ret=ceph_ll_link(m,in,parent,name,perms);
if (parent) ceph_ll_put(m,parent);
ceph_ll_put(m,in);
return ret;
}
*/
import "C"
import (
"errors"
"fmt"
"io"
"path"
"strings"
"syscall"
"time"
"unsafe"
"CephMig/internal/storage"
)
type Client struct{ mount *C.struct_ceph_mount_info }
func errno(ret C.int) error {
if ret < 0 {
return syscall.Errno(-ret)
}
return nil
}
func str(s string) (*C.char, func()) {
p := C.CString(s)
return p, func() { C.free(unsafe.Pointer(p)) }
}
func Open(o storage.Options) (*Client, error) {
c := &Client{}
user := strings.TrimPrefix(o.User, "client.")
if user == "" {
user = "admin"
}
id, free := str(user)
defer free()
if err := errno(C.ceph_create(&c.mount, id)); err != nil {
return nil, err
}
failed := true
defer func() {
if failed {
c.Close()
}
}()
conf, release := str(o.Config)
defer release()
if err := errno(C.ceph_conf_read_file(c.mount, conf)); err != nil {
return nil, err
}
settings := map[string]string{"keyring": o.Keyring, "client_mount_timeout": "30",
"client_acl_type": "posix_acl", "client_oc": "false"}
for k, v := range settings {
key, fk := str(k)
value, fv := str(v)
ret := C.ceph_conf_set(c.mount, key, value)
fk()
fv()
if err := errno(ret); err != nil {
return nil, fmt.Errorf("Ceph option %s: %w", k, err)
}
}
fs, ff := str(o.Filesystem)
defer ff()
if err := errno(C.ceph_select_filesystem(c.mount, fs)); err != nil {
return nil, err
}
root, fr := str("/")
defer fr()
if err := errno(C.ceph_mount(c.mount, root)); err != nil {
return nil, err
}
failed = false
return c, nil
}
func (c *Client) Close() error {
if c.mount != nil {
C.ceph_shutdown(c.mount)
c.mount = nil
}
return nil
}
func node(s C.struct_ceph_statx) storage.Node {
return storage.Node{Mode: uint32(s.stx_mode), Inode: uint64(s.stx_ino),
Version: uint64(s.stx_version), Nlink: uint64(s.stx_nlink), Size: uint64(s.stx_size),
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))}
}
func (c *Client) Stat(path string) (storage.Node, error) {
p, f := str(path)
defer f()
var s C.struct_ceph_statx
err := errno(C.cm_stat(c.mount, p, &s, nativeStatFlags(path)))
return node(s), err
}
func nativeStatFlags(path string) C.int {
flags := C.int(C.AT_SYMLINK_NOFOLLOW)
// Snapshot inodes are immutable and separately cached by snapshot ID. As in
// cephfs-mirror, avoid acquiring all shared metadata locks again for them.
// Live target paths retain normal synchronization semantics.
if strings.Contains(path, "/.snap/") {
flags |= C.AT_STATX_DONT_SYNC
}
return flags
}
func (c *Client) Open(path string, flags int, mode uint32) (storage.File, error) {
p, f := str(path)
defer f()
ret := C.ceph_open(c.mount, p, C.int(flags), C.mode_t(mode))
if err := errno(ret); err != nil {
return nil, err
}
return &file{client: c, fd: ret}, nil
}
type file struct {
client *Client
fd C.int
closed bool
}
func (f *file) Close() error {
if f.closed {
return nil
}
f.closed = true
return errno(C.ceph_close(f.client.mount, f.fd))
}
func (f *file) ReadAt(b []byte, off int64) (int, error) {
if len(b) == 0 {
return 0, nil
}
n := C.ceph_read(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off))
if err := errno(n); err != nil {
return 0, err
}
if int(n) < len(b) {
return int(n), io.EOF
}
return int(n), nil
}
func (f *file) WriteAt(b []byte, off int64) (int, error) {
if len(b) == 0 {
return 0, nil
}
n := C.ceph_write(f.client.mount, f.fd, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(len(b)), C.int64_t(off))
if err := errno(n); err != nil {
return 0, err
}
if int(n) != len(b) {
return int(n), io.ErrShortWrite
}
return int(n), nil
}
func (f *file) Truncate(n int64) error {
return errno(C.ceph_ftruncate(f.client.mount, f.fd, C.int64_t(n)))
}
func (f *file) Sync() error { return errno(C.ceph_fsync(f.client.mount, f.fd, 0)) }
func (f *file) Lock(owner uint64) error {
return errno(C.ceph_flock(f.client.mount, f.fd, C.LOCK_EX|C.LOCK_NB, C.uint64_t(owner)))
}
func (f *file) PunchHole(off, length int64) error {
return errno(C.ceph_fallocate(f.client.mount, f.fd, 3, C.int64_t(off), C.int64_t(length)))
}
type dir struct {
client *Client
handle *C.struct_ceph_dir_result
path string
flags C.int
}
func (c *Client) OpenDir(path string) (storage.DirectoryStream, error) {
p, f := str(path)
defer f()
d := &dir{client: c, path: path, flags: nativeStatFlags(path)}
if err := errno(C.ceph_opendir(c.mount, p, &d.handle)); err != nil {
return nil, err
}
return d, nil
}
func (d *dir) Next() (*storage.Entry, error) {
for {
var entry C.struct_dirent
var s C.struct_ceph_statx
ret := C.ceph_readdirplus_r(d.client.mount, d.handle, &entry, &s,
C.CEPH_STATX_BASIC_STATS|C.CEPH_STATX_VERSION, C.uint(d.flags), nil)
if err := errno(ret); err != nil {
return nil, err
}
if ret == 0 {
return nil, io.EOF
}
name := C.GoString(&entry.d_name[0])
if name == "." || name == ".." || name == ".snap" {
continue
}
return &storage.Entry{Name: name, Node: node(s)}, nil
}
}
func (d *dir) Close() error { return errno(C.ceph_closedir(d.client.mount, d.handle)) }
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)))
}
func (c *Client) Unlink(path string) error {
p, f := str(path)
defer f()
return errno(C.ceph_unlink(c.mount, p))
}
func (c *Client) Rmdir(path string) error {
p, f := str(path)
defer f()
return errno(C.ceph_rmdir(c.mount, p))
}
func (c *Client) Rename(a, b string) error {
p, f := str(a)
defer f()
q, g := str(b)
defer g()
return errno(C.ceph_rename(c.mount, p, q))
}
func (c *Client) Link(a, b string) error {
p, f := str(a)
defer f()
q, g := str(path.Dir(b))
defer g()
name, h := str(path.Base(b))
defer h()
return errno(C.cm_link_nofollow(c.mount, p, q, name))
}
func (c *Client) Symlink(a, b string) error {
p, f := str(a)
defer f()
q, g := str(b)
defer g()
return errno(C.ceph_symlink(c.mount, p, q))
}
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)))
}
func (c *Client) Readlink(path string) (string, error) {
p, f := str(path)
defer f()
for size := 256; size <= 1<<20; size *= 2 {
b := make([]byte, size)
n := C.ceph_readlink(c.mount, p, (*C.char)(unsafe.Pointer(&b[0])), C.int64_t(size))
if err := errno(n); err != nil {
return "", err
}
if int(n) < size {
return string(b[:int(n)]), nil
}
}
return "", errors.New("symlink target exceeds 1 MiB")
}
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())))
}
func (c *Client) GetXattr(path, key string) ([]byte, error) {
p, f := str(path)
defer f()
k, g := str(key)
defer g()
for size := 256; size <= 1<<20; size *= 2 {
b := make([]byte, size)
ret := C.ceph_lgetxattr(c.mount, p, k, unsafe.Pointer(&b[0]), C.size_t(size))
if ret == -C.ERANGE {
continue
}
if err := errno(ret); err != nil {
return nil, err
}
return b[:int(ret)], nil
}
return nil, errors.New("xattr exceeds 1 MiB")
}
func (c *Client) ListXattr(path string) ([]string, error) {
p, f := str(path)
defer f()
for size := 4096; size <= 1<<20; size *= 2 {
b := make([]byte, size)
ret := C.ceph_llistxattr(c.mount, p, (*C.char)(unsafe.Pointer(&b[0])), C.size_t(size))
if ret == -C.ERANGE {
continue
}
if err := errno(ret); err != nil {
return nil, err
}
var names []string
for _, s := range strings.Split(string(b[:int(ret)]), "\x00") {
if s != "" {
names = append(names, s)
}
}
return names, nil
}
return nil, errors.New("xattr list exceeds 1 MiB")
}
func (c *Client) SetXattr(path, key string, b []byte) error {
p, f := str(path)
defer f()
k, g := str(key)
defer g()
var ptr unsafe.Pointer
if len(b) > 0 {
ptr = unsafe.Pointer(&b[0])
}
return errno(C.ceph_lsetxattr(c.mount, p, k, ptr, C.size_t(len(b)), 0))
}
func (c *Client) RemoveXattr(path, key string) error {
p, f := str(path)
defer f()
k, g := str(key)
defer g()
return errno(C.ceph_lremovexattr(c.mount, p, k))
}
func (c *Client) Sync() error { return errno(C.ceph_sync_fs(c.mount)) }
type snapDiff struct{ info C.struct_ceph_snapdiff_info }
func (c *Client) SnapDiff(root, rel, a, b string) (storage.DiffStream, error) {
p, f := str(root)
defer f()
q, g := str(rel)
defer g()
x, h := str(a)
defer h()
y, j := str(b)
defer j()
s := &snapDiff{}
if err := errno(C.ceph_open_snapdiff(c.mount, p, q, x, y, &s.info)); err != nil {
return nil, err
}
return s, nil
}
func (s *snapDiff) Next() (string, error) {
for {
var entry C.struct_ceph_snapdiff_entry_t
ret := C.ceph_readdir_snapdiff(&s.info, &entry)
if err := errno(ret); err != nil {
return "", err
}
if ret == 0 {
return "", io.EOF
}
name := C.GoString(&entry.dir_entry.d_name[0])
if name == "." || name == ".." || name == ".snap" {
continue
}
return name, nil
}
}
func (s *snapDiff) Close() error { return errno(C.ceph_close_snapdiff(&s.info)) }
type blockDiff struct {
info C.struct_ceph_file_blockdiff_info
done bool
}
func (c *Client) BlockDiff(root, rel, a, b string) (storage.BlockStream, error) {
p, f := str(root)
defer f()
q, g := str(rel)
defer g()
x, h := str(a)
defer h()
y, j := str(b)
defer j()
s := &blockDiff{}
if err := errno(C.ceph_file_blockdiff_init(c.mount, p, q, x, y, &s.info)); err != nil {
return nil, err
}
return s, nil
}
func (s *blockDiff) Next() ([]storage.Extent, error) {
if s.done {
return nil, io.EOF
}
var blocks C.struct_ceph_file_blockdiff_changedblocks
ret := C.ceph_file_blockdiff(&s.info, &blocks)
if err := errno(ret); err != nil {
return nil, err
}
defer C.ceph_free_file_blockdiff_buffer(&blocks)
s.done = ret == 0
if uint64(blocks.num_blocks) > 1<<20 {
return nil, errors.New("blockdiff batch exceeds supported bound")
}
cblocks := unsafe.Slice(blocks.b, int(blocks.num_blocks))
out := make([]storage.Extent, len(cblocks))
for i, b := range cblocks {
out[i] = storage.Extent{Offset: uint64(b.offset), Length: uint64(b.len)}
}
return out, nil
}
func (s *blockDiff) Close() error { return errno(C.ceph_file_blockdiff_finish(&s.info)) }
+94
View File
@@ -0,0 +1,94 @@
package migration
import (
"context"
"fmt"
"io"
"path"
"strings"
)
func nativePath(p string) (string, error) {
if !strings.HasPrefix(p, "/") || path.Clean(p) != p || p == "/" {
return "", fmt.Errorf("invalid Ceph data path %q", p)
}
return p, nil
}
// Access separates filesystem access from the shared snapshot/journal workflow.
type Access interface {
Inspect(context.Context, Config, Executor) (*Inspection, error)
Empty(context.Context, string) error
Claim(context.Context, Config, string, string) (io.Closer, error)
Prepare(context.Context, string, string, string) error
Apply(context.Context, string, string) error
Verify(context.Context, string, string, string) error
}
type mountedAccess struct{}
func (mountedAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspection, error) {
return inspectMounted(ctx, c, x)
}
func (mountedAccess) Empty(_ context.Context, p string) error { return emptyDirectory(p) }
func (mountedAccess) Claim(_ context.Context, c Config, fsid, id string) (io.Closer, error) {
return claimTarget(c.Target.Mount, fsid, c.Target, id)
}
func (mountedAccess) Prepare(ctx context.Context, src, dst, scratch string) error {
if err := clearQuotas(ctx, dst); err != nil {
return err
}
return hardlinkTopology(ctx, src, dst, scratch, true)
}
func (mountedAccess) Apply(ctx context.Context, src, dst string) error {
return quotas(ctx, src, dst, false)
}
func (mountedAccess) Verify(ctx context.Context, src, dst, scratch string) error {
if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
return err
}
return quotas(ctx, src, dst, true)
}
func (e Engine) access() Access {
if e.Access != nil {
return e.Access
}
return mountedAccess{}
}
func (e Engine) Inspect(ctx context.Context, c Config) (*Inspection, error) {
return e.access().Inspect(ctx, c, e.Exec)
}
type Round struct {
SourcePath, TargetPath string
BaseName, BaseSourcePath string
Name, StatePath string
}
type RoundTransport interface {
BeginRound(context.Context, Round) error
Published(string)
Commit(context.Context, string) error
Statistics() TransferStats
}
type TransferStats struct {
Mode string `json:"mode"`
BaseSnapshot string `json:"base_snapshot,omitempty"`
FilesVisited int64 `json:"files_visited"`
FilesCopied int64 `json:"files_copied"`
BytesCopied int64 `json:"bytes_copied"`
BytesVerified int64 `json:"bytes_verified"`
BlockDiffFiles int64 `json:"blockdiff_files"`
SnapDiffEntries int64 `json:"snapdiff_entries"`
}
// NewEngine 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)
}
return Engine{Exec: x, Log: log, Transport: Rsync{Exec: x, Log: log, BandwidthKiB: c.BandwidthKiB}}, nopCloser{}, nil
}
type nopCloser struct{}
func (nopCloser) Close() error { return nil }
+146
View File
@@ -0,0 +1,146 @@
package migration
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
)
type ceph struct {
endpoint Endpoint
exec Executor
native bool
}
func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) {
// A manager operation may wait for MDS capability/session recovery after a
// killed client. Keep a deadline, but allow the normal recovery grace period.
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
flags := []string{"--conf", c.endpoint.Config, "--keyring", c.endpoint.Keyring}
if c.endpoint.User != "" {
flags = append(flags, "--name", c.endpoint.User)
}
b, err := output(ctx, c.exec, "ceph", append(flags, args...)...)
if err != nil {
// The first three tokens identify the operation; omit names and metadata
// values, which can contain confidential application information.
return nil, fmt.Errorf("Ceph %s: %w", strings.Join(args[:min(3, len(args))], " "), err)
}
return b, nil
}
func (c ceph) sub(ctx context.Context, op string, extra ...string) ([]byte, error) {
args := []string{"fs", "subvolume", op, c.endpoint.Filesystem, c.endpoint.Subvolume}
args = append(args, extra...)
if c.endpoint.Group != "" {
args = append(args, "--group_name", c.endpoint.Group)
}
return c.call(ctx, args...)
}
func (c ceph) snap(ctx context.Context, op, name string, extra ...string) ([]byte, error) {
args := []string{"fs", "subvolume", "snapshot", op, c.endpoint.Filesystem, c.endpoint.Subvolume}
if name != "" {
args = append(args, name)
}
args = append(args, extra...)
if c.endpoint.Group != "" {
args = append(args, "--group_name", c.endpoint.Group)
}
return c.call(ctx, args...)
}
func (c ceph) snapshotPath(ctx context.Context, name string) (string, error) {
b, err := c.snap(ctx, "getpath", name)
if err != nil {
return "", err
}
p := strings.TrimSpace(string(b))
if c.native {
return nativePath(p)
}
return dataPath(c.endpoint.Mount, p)
}
func (c ceph) names(ctx context.Context) ([]string, error) {
b, err := c.snap(ctx, "ls", "")
if err != nil {
return nil, err
}
var list []struct {
Name string `json:"name"`
}
if err = json.Unmarshal(b, &list); err != nil {
return nil, err
}
names := make([]string, 0, len(list))
for _, s := range list {
if !validName(s.Name) {
return nil, fmt.Errorf("unsupported snapshot name %q", s.Name)
}
names = append(names, s.Name)
}
return names, nil
}
func (c ceph) metadata(ctx context.Context, snapshot string) (map[string]string, error) {
args := []string{"fs", "subvolume"}
if snapshot != "" {
args = append(args, "snapshot")
}
args = append(args, "metadata", "ls", c.endpoint.Filesystem, c.endpoint.Subvolume)
if snapshot != "" {
args = append(args, snapshot)
}
if c.endpoint.Group != "" {
args = append(args, "--group_name", c.endpoint.Group)
}
b, err := c.call(ctx, args...)
if err != nil {
return nil, err
}
var m map[string]string
err = json.Unmarshal(b, &m)
return m, err
}
func (c ceph) setMetadata(ctx context.Context, snapshot string, m map[string]string) error {
// Remove obsolete keys too, including keys removed during a catch-up round.
old, err := c.metadata(ctx, snapshot)
if err != nil {
return err
}
for k := range old {
if _, exists := m[k]; exists {
continue
}
if err := c.metadataCommand(ctx, snapshot, "rm", k, ""); err != nil {
return err
}
}
for k, v := range m {
if ov, ok := old[k]; ok && ov == v {
continue
}
if err := c.metadataCommand(ctx, snapshot, "set", k, v); err != nil {
return err
}
}
return nil
}
func (c ceph) metadataCommand(ctx context.Context, snapshot, op, key, value string) error {
args := []string{"fs", "subvolume"}
if snapshot != "" {
args = append(args, "snapshot")
}
args = append(args, "metadata", op, c.endpoint.Filesystem, c.endpoint.Subvolume)
if snapshot != "" {
args = append(args, snapshot)
}
args = append(args, "--key_name="+key)
if op == "set" {
args = append(args, "--value="+value)
}
if c.endpoint.Group != "" {
args = append(args, "--group_name", c.endpoint.Group)
}
_, err := c.call(ctx, args...)
return err
}
+130
View File
@@ -0,0 +1,130 @@
package migration
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
type Endpoint struct {
User string `json:"user,omitempty"`
Config string `json:"config"`
Keyring string `json:"keyring"`
Filesystem string `json:"filesystem"`
Group string `json:"group"`
Subvolume string `json:"subvolume"`
Mount string `json:"mount,omitempty"`
}
type Config struct {
Backend string `json:"backend,omitempty"`
Workers int `json:"workers,omitempty"`
Source Endpoint `json:"source"`
Target Endpoint `json:"target"`
BandwidthKiB int64 `json:"bandwidth_kib,omitempty"`
}
func ReadConfig(path string) (Config, error) {
var c Config
f, err := os.Open(path)
if err != nil {
return c, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return c, err
}
if !st.Mode().IsRegular() || st.Size() > 1<<20 {
return c, errors.New("config must be a regular file of at most 1 MiB")
}
dec := json.NewDecoder(io.LimitReader(f, 1<<20))
dec.DisallowUnknownFields()
if err = dec.Decode(&c); err != nil {
return c, fmt.Errorf("config: %w", err)
}
if err = dec.Decode(new(any)); !errors.Is(err, io.EOF) {
return c, errors.New("config must contain exactly one JSON object")
}
return c, c.Validate()
}
func validName(s string) bool {
return s != "" && s != "." && s != ".." && !strings.HasPrefix(s, "-") &&
!strings.ContainsAny(s, "/\x00\n\r")
}
func (c Config) Validate() error {
if c.Backend != "" && c.Backend != "rsync" && c.Backend != "native" {
return errors.New("backend must be native or rsync")
}
if c.Workers < 0 || c.Workers > 64 {
return errors.New("workers must be between 0 and 64 (0 selects the default)")
}
for _, p := range []struct {
name string
e Endpoint
}{{"source", c.Source}, {"target", c.Target}} {
if p.e.User != "" && (!strings.HasPrefix(p.e.User, "client.") || !validName(p.e.User)) {
return fmt.Errorf("%s: user must be a client identity", p.name)
}
for _, s := range []string{p.e.Filesystem, p.e.Subvolume} {
if !validName(s) {
return fmt.Errorf("%s: invalid filesystem or subvolume name", p.name)
}
}
if p.e.Group != "" && !validName(p.e.Group) {
return fmt.Errorf("%s: invalid group", p.name)
}
paths := []string{p.e.Config, p.e.Keyring}
if c.Backend != "native" || p.e.Mount != "" {
paths = append(paths, p.e.Mount)
}
for _, path := range paths {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return fmt.Errorf("%s: paths must be absolute and clean: %q", p.name, path)
}
}
}
if c.BandwidthKiB < 0 || c.BandwidthKiB > (1<<63-1)/1024 {
return errors.New("bandwidth_kib must be nonnegative and fit in bytes per second")
}
if c.Backend != "native" && overlaps(c.Source.Mount, c.Target.Mount) {
return errors.New("source and target mounts must not overlap")
}
return nil
}
func beneath(root, path string) bool {
rel, err := filepath.Rel(root, path)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
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.
func dataPath(root, cephPath string) (string, error) {
if !filepath.IsAbs(cephPath) || filepath.Clean(cephPath) != cephPath || cephPath == "/" {
return "", fmt.Errorf("invalid Ceph path %q", cephPath)
}
p := filepath.Join(root, strings.TrimPrefix(cephPath, "/"))
resolved, err := filepath.EvalSymlinks(p)
if err != nil {
return "", err
}
if resolved != p || !beneath(root, p) {
return "", fmt.Errorf("path escapes mount or contains symlinks: %q", p)
}
st, err := os.Stat(p)
if err != nil {
return "", err
}
if !st.IsDir() {
return "", fmt.Errorf("not a directory: %s", p)
}
return p, nil
}
+100
View File
@@ -0,0 +1,100 @@
package migration
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func testConfig() Config {
return Config{Source: Endpoint{Config: "/clusters/a/ceph.conf", Keyring: "/clusters/a/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "source", Mount: "/mnt/a"},
Target: Endpoint{Config: "/clusters/b/ceph.conf", Keyring: "/clusters/b/keyring", Filesystem: "cephfs", Group: "group", Subvolume: "target", Mount: "/mnt/b"}}
}
func TestConfigRejectsUnsafePathsAndNames(t *testing.T) {
for name, modify := range map[string]func(*Config){
"overlap": func(c *Config) { c.Target.Mount = "/mnt/a/nested" },
"relative": func(c *Config) { c.Source.Mount = "relative" },
"unclean": func(c *Config) { c.Source.Mount = "/mnt/a/../a" },
"flag-name": func(c *Config) { c.Target.Subvolume = "--force" },
"traversal": func(c *Config) { c.Source.Group = "../outside" },
"negative-rate": func(c *Config) { c.BandwidthKiB = -1 },
"overflow-rate": func(c *Config) { c.BandwidthKiB = 1 << 62 },
"bad-backend": func(c *Config) { c.Backend = "raw" },
"bad-workers": func(c *Config) { c.Workers = 65 },
"invalid-user": func(c *Config) { c.Source.User = "osd.0" },
} {
t.Run(name, func(t *testing.T) {
c := testConfig()
modify(&c)
if c.Validate() == nil {
t.Fatal("accepted invalid config")
}
})
}
if err := testConfig().Validate(); err != nil {
t.Fatal(err)
}
}
func TestNativeConfigAndResumeSettings(t *testing.T) {
c := testConfig()
c.Backend = "native"
c.Source.Mount, c.Target.Mount = "", ""
if err := c.Validate(); err != nil {
t.Fatal(err)
}
changed := c
changed.Workers, changed.BandwidthKiB = 32, 100000
if !sameMigrationIdentity(c, changed) {
t.Fatal("runtime settings invalidated resume identity")
}
changed.Target.Subvolume = "another"
if sameMigrationIdentity(c, changed) {
t.Fatal("accepted a different target")
}
}
func TestStrictJSONConfig(t *testing.T) {
b, _ := json.Marshal(testConfig())
for name, data := range map[string]string{"unknown": strings.TrimSuffix(string(b), "}") + ", \"typo\": true}", "trailing": string(b) + " {}", "truncated": string(b[:len(b)-2])} {
t.Run(name, func(t *testing.T) {
p := filepath.Join(t.TempDir(), "config.json")
if err := os.WriteFile(p, []byte(data), 0600); err != nil {
t.Fatal(err)
}
if _, err := ReadConfig(p); err == nil {
t.Fatal("accepted invalid JSON config")
}
})
}
}
func TestDataPathRejectsEscapeAndSymlink(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "real"), 0700); err != nil {
t.Fatal(err)
}
if err := os.Symlink(t.TempDir(), filepath.Join(root, "link")); err != nil {
t.Fatal(err)
}
for _, path := range []string{"/../escape", "/real/../real", "relative", "/link", "/"} {
if _, err := dataPath(root, path); err == nil {
t.Fatalf("accepted %q", path)
}
}
if got, err := dataPath(root, "/real"); err != nil || got != filepath.Join(root, "real") {
t.Fatalf("got %q, %v", got, err)
}
}
func TestPrivateDirectoriesNeverFollowsSymlink(t *testing.T) {
root, outside := t.TempDir(), t.TempDir()
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {
t.Fatal(err)
}
if err := privateDirectories(filepath.Join(root, "link", "new")); err == nil {
t.Fatal("followed symlink")
}
if _, err := os.Stat(filepath.Join(outside, "new")); !os.IsNotExist(err) {
t.Fatal("created directory through symlink")
}
}
+591
View File
@@ -0,0 +1,591 @@
package migration
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"syscall"
"time"
)
type Engine struct {
Exec Executor
Transport Transport
Log io.Writer
Access Access
}
type endpointInfo struct {
Path string `json:"path"`
State string `json:"state"`
BytesUsed uint64 `json:"bytes_used"`
CaseSensitive bool `json:"casesensitive"`
Normalization string `json:"normalization"`
Encryption string `json:"enctag"`
Earmark string `json:"earmark"`
}
type Inspection struct {
SourceFSID string `json:"source_fsid"`
TargetFSID string `json:"target_fsid"`
SourcePath string `json:"source_path"`
TargetPath string `json:"target_path"`
SourceBytes uint64 `json:"source_bytes"`
SourceSnapshots []string `json:"source_snapshots"`
NativeSnapshotIdentityPreserved bool `json:"native_snapshot_identity_preserved"`
Notes []string `json:"notes"`
}
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) {
if e.Log != nil {
fmt.Fprintf(e.Log, format+"\n", args...)
}
}
func queryEndpoint(ctx context.Context, c ceph) (string, endpointInfo, error) {
var info endpointInfo
b, err := c.call(ctx, "fsid")
if err != nil {
return "", info, err
}
fsid := strings.TrimSpace(string(b))
if len(fsid) != 36 {
return "", info, errors.New("invalid cluster FSID")
}
b, err = c.sub(ctx, "info")
if err != nil {
return "", info, err
}
if err = json.Unmarshal(b, &info); err != nil {
return "", info, err
}
if info.State != "complete" || !info.CaseSensitive || info.Normalization != "none" || info.Encryption != "" || info.Earmark != "" {
return "", info, errors.New("subvolume must be complete, case-sensitive, unencrypted, without normalization or earmark")
}
return fsid, info, nil
}
func endpoint(ctx context.Context, c ceph) (string, endpointInfo, string, error) {
fsid, info, err := queryEndpoint(ctx, c)
if err != nil {
return "", info, "", err
}
path, err := dataPath(c.endpoint.Mount, info.Path)
if err != nil {
return "", info, "", err
}
mountedFSID, err := xattr(path, "ceph.cluster_fsid")
if err != nil {
return "", info, "", fmt.Errorf("cannot verify mount FSID: %w", err)
}
if string(mountedFSID) != fsid {
return "", info, "", fmt.Errorf("mount belongs to a different cluster than the configured Ceph endpoint")
}
return fsid, info, path, err
}
func inspectMounted(ctx context.Context, c Config, x Executor) (*Inspection, error) {
if err := c.Validate(); err != nil {
return nil, err
}
if err := checkMount(c.Source.Mount, false); err != nil {
return nil, err
}
if err := checkMount(c.Target.Mount, true); err != nil {
return nil, err
}
src, dst := ceph{endpoint: c.Source, exec: x}, ceph{endpoint: c.Target, exec: x}
sf, si, sp, err := endpoint(ctx, src)
if err != nil {
return nil, fmt.Errorf("source: %w", err)
}
tf, _, tp, err := endpoint(ctx, dst)
if err != nil {
return nil, fmt.Errorf("target: %w", err)
}
if sf == tf {
return nil, errors.New("source and target must be different clusters")
}
var ss, ts syscall.Stat_t
if err = syscall.Stat(sp, &ss); err != nil {
return nil, err
}
if err = syscall.Stat(tp, &ts); err != nil {
return nil, err
}
if ss.Dev == ts.Dev {
return nil, errors.New("source and target are on the same mounted filesystem")
}
names, err := src.names(ctx)
if err != nil {
return nil, err
}
inspection := &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: sp, TargetPath: tp, SourceBytes: si.BytesUsed, SourceSnapshots: names}
inspection.Notes = []string{SnapshotIdentityNote}
return inspection, nil
}
func newID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return hex.EncodeToString(b[:]), nil
}
func emptyDirectory(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
entries, err := f.ReadDir(1)
if err != nil && !errors.Is(err, io.EOF) {
return err
}
if len(entries) != 0 {
return fmt.Errorf("new migration requires empty target subvolume: %s", path)
}
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.
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")
if err := privateDirectories(dir); err != nil {
return nil, err
}
resolved, err := filepath.EvalSymlinks(dir)
if err != nil || resolved != dir {
return nil, errors.New("claim directory contains symlinks")
}
path := filepath.Join(dir, hex.EncodeToString(key[:]))
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
if err == nil {
if _, err = f.WriteString(id + "\n"); err == nil {
err = f.Sync()
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err != nil {
return nil, err
}
} else if !errors.Is(err, os.ErrExist) {
return nil, err
}
st, err := os.Lstat(path)
if err != nil {
return nil, err
}
if !st.Mode().IsRegular() {
return nil, errors.New("target claim is not a regular file")
}
f, err = os.OpenFile(path, os.O_RDWR|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
f.Close()
return nil, fmt.Errorf("target is being migrated by another process: %w", err)
}
b, err := io.ReadAll(io.LimitReader(f, 256))
if err != nil || string(b) != id+"\n" {
f.Close()
return nil, errors.New("target is claimed by a different job or claim is incomplete; preserve the original state file")
}
return f, nil
}
func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, error) {
var s Snapshot
s.Name = name
b, err := src.snap(ctx, "info", name)
if err != nil {
return s, err
}
var info struct {
CreatedAt string `json:"created_at"`
}
if err = json.Unmarshal(b, &info); err != nil {
return s, err
}
if _, err = time.Parse("2006-01-02 15:04:05.999999999", info.CreatedAt); err != nil {
return s, fmt.Errorf("invalid creation time for %s: %w", name, err)
}
s.CreatedAt = info.CreatedAt
s.Metadata, err = src.metadata(ctx, name)
return s, err
}
func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool) error {
if err := c.Validate(); err != nil {
return err
}
e.log("note: %s", SnapshotIdentityNote)
if os.Geteuid() != 0 {
return errors.New("migration requires root for numeric ownership, ACLs and xattrs")
}
if e.Exec == nil || e.Transport == nil {
return errors.New("missing executor or transport")
}
abs, err := filepath.Abs(statePath)
if err != nil {
return err
}
if c.Backend != "native" && (overlaps(filepath.Dir(abs), c.Source.Mount) || overlaps(filepath.Dir(abs), c.Target.Mount)) {
return errors.New("state directory must be outside the CephFS mounts")
}
if err = privateDirectories(filepath.Dir(abs)); err != nil {
return err
}
resolved, err := filepath.EvalSymlinks(filepath.Dir(abs))
if err != nil || resolved != filepath.Dir(abs) {
return errors.New("state directory must not contain symlinks")
}
lock, err := lockFile(abs + ".lock")
if err != nil {
return err
}
defer lock.Close()
inspection, err := e.Inspect(ctx, c)
if err != nil {
return err
}
src, dst := ceph{endpoint: c.Source, exec: e.Exec, native: c.Backend == "native"}, ceph{endpoint: c.Target, exec: e.Exec, native: c.Backend == "native"}
s, err := LoadState(abs)
if errors.Is(err, os.ErrNotExist) {
if err = e.access().Empty(ctx, inspection.TargetPath); err != nil {
return err
}
names, err := dst.names(ctx)
if err != nil {
return err
}
if len(names) != 0 {
return errors.New("new migration requires a target without snapshots")
}
metadata, err := dst.metadata(ctx, "")
if err != nil {
return err
}
if len(metadata) != 0 {
return errors.New("new migration requires a target without custom metadata")
}
id, err := newID()
if err != nil {
return err
}
s = &State{
Version: stateVersion, ID: id, Config: c,
SourceFSID: inspection.SourceFSID, TargetFSID: inspection.TargetFSID,
SourcePath: inspection.SourcePath, TargetPath: inspection.TargetPath,
Phase: "syncing", Notes: []string{SnapshotIdentityNote},
}
if err = SaveState(abs, s); err != nil {
return err
}
} else if err != nil {
return err
}
if !sameMigrationIdentity(s.Config, c) || s.SourceFSID != inspection.SourceFSID || s.TargetFSID != inspection.TargetFSID || s.SourcePath != inspection.SourcePath || s.TargetPath != inspection.TargetPath {
return errors.New("config or cluster identity changed; refusing to reuse migration state")
}
claim, err := e.access().Claim(ctx, c, s.TargetFSID, s.ID)
if err != nil {
return err
}
defer claim.Close()
s.Config = c
if !contains(s.Notes, SnapshotIdentityNote) {
s.Notes = append(s.Notes, SnapshotIdentityNote)
if err = SaveState(abs, s); err != nil {
return err
}
}
if s.Phase == "ready-for-cutover" {
if !final {
return errors.New("job is ready for cutover; sync is no longer allowed")
}
e.log("already ready for cutover; no new source snapshot created")
return nil
}
if s.Phase != "syncing" {
return fmt.Errorf("unsupported job phase %q", s.Phase)
}
known := make(map[string]bool, len(s.Snapshots))
finalPending := false
for _, snap := range s.Snapshots {
known[snap.Name] = true
if snap.Final {
finalPending = true
}
}
if finalPending && !final {
return errors.New("a final round is pending; resume using finalize while writers remain stopped")
}
targetNames, err := dst.names(ctx)
if err != nil {
return err
}
for _, name := range targetNames {
if !known[name] {
return fmt.Errorf("unowned target snapshot %q; refusing to overwrite target", name)
}
}
// Discover newly created application snapshots on every invocation.
var discovered []Snapshot
for _, name := range inspection.SourceSnapshots {
if known[name] {
continue
}
snap, err := snapshotDetails(ctx, src, name)
if err != nil {
return err
}
discovered = append(discovered, snap)
}
sort.Slice(discovered, func(i, j int) bool {
if discovered[i].CreatedAt == discovered[j].CreatedAt {
return discovered[i].Name < discovered[j].Name
}
return discovered[i].CreatedAt < discovered[j].CreatedAt
})
s.Snapshots = append(s.Snapshots, discovered...)
if err = SaveState(abs, s); err != nil {
return err
}
// Resume all intent records before capturing another live snapshot.
for i := range s.Snapshots {
if s.Snapshots[i].Done {
snap := &s.Snapshots[i]
if !contains(targetNames, snap.Name) {
return fmt.Errorf("completed target snapshot %q disappeared", snap.Name)
}
info, err := snapshotDetails(ctx, dst, snap.Name)
if err != nil {
return err
}
if info.CreatedAt != snap.TargetCreatedAt {
return fmt.Errorf("completed target snapshot %q was replaced", snap.Name)
}
if contains(inspection.SourceSnapshots, snap.Name) {
info, err = snapshotDetails(ctx, src, snap.Name)
if err != nil {
return err
}
if info.CreatedAt != snap.CreatedAt {
return fmt.Errorf("completed source snapshot %q was replaced", snap.Name)
}
if err = dst.setMetadata(ctx, snap.Name, info.Metadata); err != nil {
return err
}
snap.Metadata = info.Metadata
}
continue
}
if err := e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, i); err != nil {
return err
}
}
id, err := newID()
if err != nil {
return err
}
s.Snapshots = append(s.Snapshots, Snapshot{Name: "cephmig-" + s.ID[:12] + "-" + id[:12], Owned: true, Final: final})
if err = SaveState(abs, s); err != nil {
return err
}
if err = e.transfer(ctx, src, dst, inspection.TargetPath, abs, s, len(s.Snapshots)-1); err != nil {
return err
}
metadata, err := src.metadata(ctx, "")
if err != nil {
return err
}
if err = dst.setMetadata(ctx, "", metadata); err != nil {
return err
}
if final {
// Every source snapshot visible at finalization must have a completed record.
names, err := src.names(ctx)
if err != nil {
return err
}
completed := map[string]bool{}
for _, snap := range s.Snapshots {
if snap.Done {
completed[snap.Name] = true
}
}
for _, name := range names {
if !completed[name] {
return fmt.Errorf("source snapshot inventory changed during finalization (%s); retry finalize", name)
}
}
last := s.Snapshots[len(s.Snapshots)-1]
if !last.Final {
return errors.New("final snapshot is not the last transferred snapshot; retry requires operator review")
}
path, err := src.snapshotPath(ctx, last.Name)
if err != nil {
return err
}
if err = e.Transport.Verify(ctx, path, inspection.TargetPath); err != nil {
return err
}
if err = e.access().Verify(ctx, path, inspection.TargetPath, filepath.Dir(abs)); err != nil {
return err
}
s.Phase = "ready-for-cutover"
}
if err = SaveState(abs, s); err != nil {
return err
}
e.log("phase=%s snapshots=%d state=%s", s.Phase, len(s.Snapshots), abs)
return nil
}
func sameMigrationIdentity(a, b Config) bool {
a.Workers, b.Workers = 0, 0
a.BandwidthKiB, b.BandwidthKiB = 0, 0
return reflect.DeepEqual(a, b)
}
func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath string, s *State, index int) error {
snap := &s.Snapshots[index]
e.log("snapshot=%s: resolving immutable source", snap.Name)
names, err := src.names(ctx)
if err != nil {
return err
}
if !contains(names, snap.Name) {
if !snap.Owned || snap.CreatedAt != "" {
return fmt.Errorf("source snapshot %q disappeared before transfer", snap.Name)
}
if _, err = src.snap(ctx, "create", snap.Name); err != nil {
return err
}
}
details, err := snapshotDetails(ctx, src, snap.Name)
if err != nil {
return err
}
if snap.CreatedAt != "" && snap.CreatedAt != details.CreatedAt {
return fmt.Errorf("source snapshot %q was replaced", snap.Name)
}
snap.CreatedAt, snap.Metadata = details.CreatedAt, details.Metadata
if err = SaveState(statePath, s); err != nil {
return err
}
from, err := src.snapshotPath(ctx, snap.Name)
if err != nil {
return err
}
targetNames, err := dst.names(ctx)
if err != nil {
return err
}
aware, isNative := e.Transport.(RoundTransport)
existed := contains(targetNames, snap.Name)
if isNative {
round := Round{SourcePath: from, TargetPath: target, Name: snap.Name, StatePath: statePath, BaseName: s.LiveSnapshot}
if s.LiveSnapshot != "" {
round.BaseSourcePath, err = src.snapshotPath(ctx, s.LiveSnapshot)
if err != nil {
return err
}
}
if err = aware.BeginRound(ctx, round); err != nil {
return err
}
}
created := false
if !existed || isNative {
// Clearing this durable marker before any target mutation makes interrupted
// rounds fall back to full reconstruction rather than trusting a partial base.
s.LiveSnapshot = ""
if err = SaveState(statePath, s); err != nil {
return err
}
e.log("snapshot=%s: copying", snap.Name)
if err = e.access().Prepare(ctx, from, target, filepath.Dir(statePath)); err != nil {
return err
}
if err = e.Transport.Copy(ctx, from, target); err != nil {
return err
}
if err = e.access().Apply(ctx, from, target); err != nil {
return err
}
e.log("snapshot=%s: verifying before publication", snap.Name)
if err = e.Transport.Verify(ctx, from, target); err != nil {
return err
}
if err = e.access().Verify(ctx, from, target, filepath.Dir(statePath)); err != nil {
return err
}
if !existed {
if _, err = dst.snap(ctx, "create", snap.Name); err != nil {
return err
}
created = true
}
}
// A crash may have occurred between snapshot creation and the state commit.
// Never trust an existing snapshot solely because its name matches.
to, err := dst.snapshotPath(ctx, snap.Name)
if err != nil {
return err
}
if isNative && created {
aware.Published(to)
}
if err = e.Transport.Verify(ctx, from, to); err != nil {
return err
}
if err = e.access().Verify(ctx, from, to, filepath.Dir(statePath)); err != nil {
return err
}
if err = dst.setMetadata(ctx, snap.Name, snap.Metadata); err != nil {
return err
}
targetInfo, err := snapshotDetails(ctx, dst, snap.Name)
if err != nil {
return err
}
snap.TargetCreatedAt = targetInfo.CreatedAt
if isNative {
if err = aware.Commit(ctx, snap.Name); err != nil {
return err
}
stats := aware.Statistics()
snap.Stats = &stats
}
snap.Done = true
s.LiveSnapshot = snap.Name
if err = SaveState(statePath, s); err != nil {
return err
}
e.log("snapshot=%s: verified and committed", snap.Name)
return nil
}
func contains(names []string, name string) bool {
for _, n := range names {
if n == name {
return true
}
}
return false
}
+185
View File
@@ -0,0 +1,185 @@
package migration
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"syscall"
"time"
bolt "go.etcd.io/bbolt"
)
type linkIndex struct {
db *bolt.DB
tx *bolt.Tx
observations int
}
func openLinkIndex(path string) (*linkIndex, error) {
// Rebuildable scratch data only: never used as a durable migration checkpoint.
db, err := bolt.Open(path, 0600, &bolt.Options{Timeout: time.Second, NoSync: true})
if err != nil {
return nil, err
}
tx, err := db.Begin(true)
if err != nil {
db.Close()
return nil, err
}
for _, name := range []string{"source", "target"} {
if _, err = tx.CreateBucket([]byte(name)); err != nil {
tx.Rollback()
db.Close()
return nil, err
}
}
return &linkIndex{db: db, tx: tx}, nil
}
func (x *linkIndex) close() error {
if x.tx != nil {
_ = x.tx.Rollback()
}
return x.db.Close()
}
func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
b := x.tx.Bucket([]byte(bucket))
old := b.Get(key[:])
same := true
if old == nil {
if err := b.Put(key[:], value[:]); err != nil {
return false, err
}
} else {
same = bytes.Equal(old, value[:])
}
x.observations++
// Limit dirty transaction state; the complete relation stays on disk.
if x.observations%4096 == 0 {
err := x.tx.Commit()
x.tx = nil
if err != nil {
return false, err
}
x.tx, err = x.db.Begin(true)
if err != nil {
return false, err
}
}
return same, nil
}
func inodeIdentity(info os.FileInfo) ([16]byte, uint64, error) {
var key [16]byte
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return key, 0, errors.New("missing Linux inode information")
}
binary.BigEndian.PutUint64(key[:8], uint64(st.Dev))
binary.BigEndian.PutUint64(key[8:], st.Ino)
return key, uint64(st.Nlink), nil
}
// In repair mode remove 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) {
scratch, err := os.MkdirTemp(scratchParent, ".cephmig-links-")
if err != nil {
return err
}
defer os.RemoveAll(scratch)
index, err := openLinkIndex(filepath.Join(scratch, "index.bolt"))
if err != nil {
return err
}
defer func() {
if err := index.close(); result == nil {
result = err
}
}()
targetPath := func(path string) (string, error) {
rel, err := filepath.Rel(src, path)
if err != nil || !beneath(src, path) {
return "", fmt.Errorf("hardlink path outside source: %s", path)
}
return filepath.Join(dst, rel), nil
}
visitDir := func(path string) error {
target, err := targetPath(path)
if err != nil {
return err
}
st, err := os.Lstat(target)
if repair && (errors.Is(err, os.ErrNotExist) || (err == nil && !st.IsDir())) {
// Never follow a target symlink directory, even when its referent exists.
return fs.SkipDir
}
if err != nil {
return err
}
if !st.IsDir() {
return fmt.Errorf("target directory changed type: %s", target)
}
return nil
}
visitFile := func(path string, sourceInfo os.FileInfo) error {
if !sourceInfo.Mode().IsRegular() {
return nil
}
target, err := targetPath(path)
if err != nil {
return err
}
targetInfo, err := os.Lstat(target)
if repair && errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !targetInfo.Mode().IsRegular() {
if repair {
return nil
}
return fmt.Errorf("hardlink target is not a regular file: %s", target)
}
sourceKey, sourceLinks, err := inodeIdentity(sourceInfo)
if err != nil {
return err
}
targetKey, targetLinks, err := inodeIdentity(targetInfo)
if err != nil {
return err
}
if !repair && sourceLinks > 1 {
same, err := index.observe("source", sourceKey, targetKey)
if err != nil {
return err
}
if !same {
return fmt.Errorf("source hardlink group was split at %s", target)
}
}
if targetLinks > 1 {
same, err := index.observe("target", targetKey, sourceKey)
if err != nil {
return err
}
if !same {
if !repair {
return fmt.Errorf("unrelated source files became hardlinked at %s", target)
}
if err := os.Remove(target); err != nil {
return fmt.Errorf("break obsolete target hardlink: %w", err)
}
}
}
return nil
}
return walkTree(ctx, src, visitDir, visitFile)
}
+143
View File
@@ -0,0 +1,143 @@
package migration
import (
"context"
"encoding/binary"
"io"
"os"
"os/exec"
"path/filepath"
"testing"
)
func mustWrite(t *testing.T, path string) {
t.Helper()
if err := os.WriteFile(path, []byte("identical contents"), 0640); err != nil {
t.Fatal(err)
}
}
func TestHardlinkTopologyHandlesSplitAndRejoin(t *testing.T) {
if _, err := exec.LookPath("rsync"); err != nil {
t.Skip("rsync is not installed")
}
ctx := context.Background()
src, dst, scratch := t.TempDir(), t.TempDir(), t.TempDir()
if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil {
t.Fatal(err)
}
a, b := filepath.Join(src, "a"), filepath.Join(src, "d", "b")
mustWrite(t, a)
if err := os.Link(a, b); err != nil {
t.Fatal(err)
}
r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard}
if err := r.Copy(ctx, src, dst); err != nil {
t.Fatal(err)
}
if err := hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
t.Fatal(err)
}
// Break one source link without changing bytes, mode or mtime. Rsync -H
// alone can leave an extra target link in this exact case.
old, err := os.Stat(b)
if err != nil {
t.Fatal(err)
}
if err = os.Remove(b); err != nil {
t.Fatal(err)
}
mustWrite(t, b)
if err = os.Chtimes(b, old.ModTime(), old.ModTime()); err != nil {
t.Fatal(err)
}
if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil {
t.Fatal("extra destination hardlink was missed")
}
if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil {
t.Fatal(err)
}
if err = r.Copy(ctx, src, dst); err != nil {
t.Fatal(err)
}
if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
t.Fatal(err)
}
x, _ := os.Stat(filepath.Join(dst, "a"))
y, _ := os.Stat(filepath.Join(dst, "d", "b"))
if os.SameFile(x, y) {
t.Fatal("split source files remained linked")
}
if err = os.Remove(b); err != nil {
t.Fatal(err)
}
if err = os.Link(a, b); err != nil {
t.Fatal(err)
}
if err = hardlinkTopology(ctx, src, dst, scratch, false); err == nil {
t.Fatal("missing target hardlink was missed")
}
if err = hardlinkTopology(ctx, src, dst, scratch, true); err != nil {
t.Fatal(err)
}
if err = r.Copy(ctx, src, dst); err != nil {
t.Fatal(err)
}
if err = hardlinkTopology(ctx, src, dst, scratch, false); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(scratch)
if err != nil || len(entries) != 0 {
t.Fatal("scratch indexes were not removed")
}
}
func TestHardlinkRepairDoesNotFollowTargetSymlinkDirectories(t *testing.T) {
src, dst, outside, scratch := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir()
if err := os.Mkdir(filepath.Join(src, "d"), 0700); err != nil {
t.Fatal(err)
}
mustWrite(t, filepath.Join(src, "d", "a"))
mustWrite(t, filepath.Join(src, "d", "b"))
mustWrite(t, filepath.Join(outside, "a"))
if err := os.Link(filepath.Join(outside, "a"), filepath.Join(outside, "b")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(dst, "d")); err != nil {
t.Fatal(err)
}
if err := hardlinkTopology(context.Background(), src, dst, scratch, true); err != nil {
t.Fatal(err)
}
a, err := os.Stat(filepath.Join(outside, "a"))
if err != nil {
t.Fatal(err)
}
b, err := os.Stat(filepath.Join(outside, "b"))
if err != nil || !os.SameFile(a, b) {
t.Fatal("repair touched files outside the target tree")
}
}
func TestHardlinkDiskIndexSurvivesBatchBoundaries(t *testing.T) {
x, err := openLinkIndex(filepath.Join(t.TempDir(), "index"))
if err != nil {
t.Fatal(err)
}
defer x.close()
for i := uint64(0); i < 5000; i++ {
var key, value [16]byte
binary.BigEndian.PutUint64(key[:8], i)
binary.BigEndian.PutUint64(value[:8], i+1)
same, err := x.observe("target", key, value)
if err != nil || !same {
t.Fatalf("insert %d: %v", i, err)
}
}
var key, value [16]byte
binary.BigEndian.PutUint64(value[:8], 1)
if same, err := x.observe("target", key, value); err != nil || !same {
t.Fatalf("committed entry lost: %v", err)
}
value[15] = 1
if same, err := x.observe("target", key, value); err != nil || same {
t.Fatalf("conflict missed: %v", err)
}
}
+232
View File
@@ -0,0 +1,232 @@
//go:build linux
package migration
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"
)
func unescapeMount(s string) string {
return strings.NewReplacer("\\040", " ", "\\011", "\t", "\\012", "\n", "\\134", "\\").Replace(s)
}
func privateDirectories(path string) error {
if !filepath.IsAbs(path) {
return errors.New("directory path must be absolute")
}
current := "/"
for _, component := range strings.Split(strings.TrimPrefix(filepath.Clean(path), "/"), "/") {
if component == "" {
continue
}
current = filepath.Join(current, component)
if err := os.Mkdir(current, 0700); err != nil && !errors.Is(err, os.ErrExist) {
return err
}
st, err := os.Lstat(current)
if err != nil {
return err
}
if !st.IsDir() {
return fmt.Errorf("directory contains a symlink or non-directory: %s", current)
}
}
return nil
}
func checkMount(root string, writable bool) error {
f, err := os.Open("/proc/self/mountinfo")
if err != nil {
return err
}
defer f.Close()
scan := bufio.NewScanner(f)
found := false
for scan.Scan() {
parts := strings.SplitN(scan.Text(), " - ", 2)
if len(parts) != 2 {
continue
}
fields, after := strings.Fields(parts[0]), strings.Fields(parts[1])
if len(fields) < 6 || len(after) < 2 {
continue
}
mount := unescapeMount(fields[4])
if mount == root {
if after[0] != "ceph" && after[0] != "fuse.ceph-fuse" {
return fmt.Errorf("%s is not a CephFS mount", root)
}
if writable && !strings.Contains(","+fields[5]+",", ",rw,") {
return fmt.Errorf("target %s must be mounted read-write", root)
}
found = true
} else if beneath(root, mount) {
return fmt.Errorf("nested mount %s below %s is unsupported", mount, root)
}
}
if err := scan.Err(); err != nil {
return err
}
if !found {
return fmt.Errorf("%s must be a dedicated CephFS filesystem-root mount", root)
}
resolved, err := filepath.EvalSymlinks(root)
if err != nil {
return err
}
if resolved != root {
return errors.New("mount path must not contain symlinks")
}
return nil
}
func xattr(path, key string) ([]byte, error) {
for attempt := 0; attempt < 3; attempt++ {
n, err := syscall.Getxattr(path, key, nil)
if errors.Is(err, syscall.ENODATA) {
return []byte("0"), nil
}
if err != nil {
return nil, err
}
if n > 1<<20 {
return nil, fmt.Errorf("xattr too large: %s", key)
}
b := make([]byte, n)
n, err = syscall.Getxattr(path, key, b)
if errors.Is(err, syscall.ERANGE) {
continue
}
if err != nil {
return nil, err
}
return b[:n], nil
}
return nil, errors.New("xattr changed repeatedly")
}
var quotaKeys = []string{"ceph.quota.max_bytes", "ceph.quota.max_files"}
// ReadDir batches keep a single very large directory from exhausting memory.
func walkDirectories(ctx context.Context, root string, visit func(string) error) error {
return walkTree(ctx, root, visit, nil)
}
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 {
if err := ctx.Err(); err != nil {
return err
}
if depth > 128 {
return errors.New("directory depth exceeds supported limit (128)")
}
if visitDir != nil {
if err := visitDir(path); errors.Is(err, fs.SkipDir) {
return nil
} else if err != nil {
return err
}
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
for {
batch, readErr := f.ReadDir(128)
for _, e := range batch {
if err := ctx.Err(); err != nil {
return err
}
if e.Name() == ".snap" {
continue
}
child := filepath.Join(path, e.Name())
if e.IsDir() {
if err := walk(child, depth+1); err != nil {
return err
}
} else if visitFile != nil {
info, err := e.Info()
if err != nil {
return err
}
if err = visitFile(child, info); err != nil {
return err
}
}
}
if errors.Is(readErr, io.EOF) {
return nil
}
if readErr != nil {
return readErr
}
}
}
return walk(root, 0)
}
func clearQuotas(ctx context.Context, root string) error {
return walkDirectories(ctx, root, func(path string) error {
for _, key := range quotaKeys {
old, err := xattr(path, key)
if err != nil {
return fmt.Errorf("read quota %s: %w", path, err)
}
if string(old) == "0" {
continue
}
if err := syscall.Setxattr(path, key, []byte("0"), 0); err != nil {
return fmt.Errorf("clear quota %s: %w", path, err)
}
}
return nil
})
}
func quotas(ctx context.Context, src, dst string, verify bool) error {
return walkDirectories(ctx, src, func(path string) error {
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
target := filepath.Join(dst, rel)
st, err := os.Lstat(target)
if err != nil {
return err
}
if !st.IsDir() {
return fmt.Errorf("quota target is not a real directory: %s", target)
}
for _, key := range quotaKeys {
value, err := xattr(path, key)
if err != nil {
return fmt.Errorf("source quota %s %s: %w", path, key, err)
}
actual, err := xattr(target, key)
if err != nil {
return fmt.Errorf("target quota %s %s: %w", target, key, err)
}
if string(value) == string(actual) {
continue
}
if verify {
return fmt.Errorf("quota mismatch: %s %s", rel, key)
}
if err := syscall.Setxattr(target, key, value, 0); err != nil {
return fmt.Errorf("set quota %s %s: %w", target, key, err)
}
}
return nil
})
}
+173
View File
@@ -0,0 +1,173 @@
package migration
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"syscall"
"CephMig/internal/storage"
)
type nativeAccess struct{ backend *nativeTransport }
func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspection, error) {
if err := c.Validate(); err != nil {
return nil, err
}
sf, si, err := queryEndpoint(ctx, ceph{endpoint: c.Source, exec: x, native: true})
if err != nil {
return nil, err
}
tf, ti, err := queryEndpoint(ctx, ceph{endpoint: c.Target, exec: x, native: true})
if err != nil {
return nil, err
}
if sf == tf {
return nil, errors.New("native source and target must be different clusters")
}
for _, p := range []struct {
fs storage.FS
path, fsid string
}{{a.backend.source, si.Path, sf}, {a.backend.target, ti.Path, tf}} {
if _, err := nativePath(p.path); err != nil {
return nil, err
}
if err := validateNativeDirectory(p.fs, p.path); err != nil {
return nil, err
}
id, err := p.fs.GetXattr(p.path, "ceph.cluster_fsid")
if err != nil {
return nil, err
}
if string(id) != p.fsid {
return nil, errors.New("native connection belongs to the wrong cluster")
}
}
names, err := (ceph{endpoint: c.Source, exec: x, native: true}).names(ctx)
if err != nil {
return nil, err
}
fingerprint := sha256.Sum256([]byte(sf + "\x00" + tf + "\x00" + si.Path + "\x00" + ti.Path))
a.backend.identity = hex.EncodeToString(fingerprint[:])
return &Inspection{SourceFSID: sf, TargetFSID: tf, SourcePath: si.Path, TargetPath: ti.Path,
SourceBytes: si.BytesUsed, SourceSnapshots: names, Notes: []string{SnapshotIdentityNote}}, nil
}
func (a nativeAccess) Empty(ctx context.Context, p string) error {
if err := ctx.Err(); err != nil {
return err
}
d, err := a.backend.target.OpenDir(p)
if err != nil {
return err
}
defer d.Close()
_, err = d.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
return errors.New("new native migration requires an empty target subvolume")
}
func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.Closer, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
fs := a.backend.target
current := "/"
for _, component := range []string{".cephmig", "claims"} {
current = path.Join(current, component)
n, err := fs.Stat(current)
if errors.Is(err, syscall.ENOENT) {
if err = fs.Mkdir(current, 0700); err != nil && !errors.Is(err, syscall.EEXIST) {
return nil, err
}
n, err = fs.Stat(current)
}
if err != nil {
return nil, err
}
if n.Kind() != storage.Directory {
return nil, errors.New("native claim directory contains a symlink or non-directory")
}
}
sum := sha256.Sum256([]byte(fsid + "\x00" + c.Target.Filesystem + "\x00" + c.Target.Group + "\x00" + c.Target.Subvolume))
p := path.Join(current, hex.EncodeToString(sum[:]))
f, err := fs.Open(p, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600)
if err == nil {
if err = writeNativeAt(f, []byte(id+"\n"), 0); err == nil {
err = f.Sync()
}
closeErr := f.Close()
if err == nil {
err = closeErr
}
if err != nil {
return nil, err
}
} else if !errors.Is(err, syscall.EEXIST) {
return nil, err
}
n, err := fs.Stat(p)
if err != nil {
return nil, err
}
if n.Kind() != storage.Regular {
return nil, errors.New("native target claim is not a regular file")
}
f, err = fs.Open(p, syscall.O_RDWR|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
if err = f.Lock(1); err != nil {
f.Close()
return nil, fmt.Errorf("native target is locked: %w", err)
}
b := make([]byte, 256)
count, readErr := f.ReadAt(b, 0)
if readErr != nil && !errors.Is(readErr, io.EOF) {
f.Close()
return nil, readErr
}
if string(b[:count]) != id+"\n" {
f.Close()
return nil, errors.New("native target belongs to a different job")
}
return f, nil
}
func (a nativeAccess) Prepare(ctx context.Context, _, target, _ string) error {
return clearNativeQuotas(ctx, a.backend.target, target)
}
func (a nativeAccess) Apply(context.Context, string, string) error { return a.backend.target.Sync() }
func (a nativeAccess) Verify(context.Context, string, string, string) error { return nil } // Transport verifies all native metadata and links.
type nativeVerifyIndex struct {
index *linkIndex
dir string
}
func osNativeVerifyIndex(parent string) (*nativeVerifyIndex, error) {
dir, err := os.MkdirTemp(parent, "verify-")
if err != nil {
return nil, err
}
index, err := openLinkIndex(filepath.Join(dir, "links.bolt"))
if err != nil {
os.RemoveAll(dir)
return nil, err
}
return &nativeVerifyIndex{index: index, dir: dir}, nil
}
func (i *nativeVerifyIndex) cleanup() { _ = i.index.close(); _ = os.RemoveAll(i.dir) }
func options(ep Endpoint) storage.Options {
return storage.Options{Config: ep.Config, Keyring: ep.Keyring, User: strings.TrimPrefix(ep.User, "client."), Filesystem: ep.Filesystem}
}
+432
View File
@@ -0,0 +1,432 @@
package migration
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"path"
"syscall"
"time"
"CephMig/internal/storage"
)
func readNativeAt(f storage.File, b []byte, offset int64) error {
n, err := f.ReadAt(b, offset)
if n != len(b) {
if err == nil {
err = io.ErrUnexpectedEOF
}
return err
}
if err != nil && !errors.Is(err, io.EOF) {
return err
}
return nil
}
func writeNativeAt(f storage.File, b []byte, offset int64) error {
n, err := f.WriteAt(b, offset)
if err != nil {
return err
}
if n != len(b) {
return io.ErrShortWrite
}
return nil
}
func allZero(b []byte) bool {
for _, v := range b {
if v != 0 {
return false
}
}
return true
}
func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error {
if err := ctx.Err(); err != nil {
return err
}
from, to := path.Join(b.round.SourcePath, job.rel), path.Join(b.round.TargetPath, job.rel)
target, statErr := b.target.Stat(to)
if statErr != nil && !errors.Is(statErr, syscall.ENOENT) {
return statErr
}
exists := statErr == nil && target.Kind() == storage.Regular
var previous baseEntry
trusted := false
if b.delta && exists {
var ok bool
var err error
previous, ok, err = b.base.entry(job.rel)
if err != nil {
return err
}
trusted = ok && previous.Inode == job.node.Inode && previous.TargetInode == target.Inode && previous.Size == target.Size
}
changed := true
if trusted && job.node.Version != 0 && job.node.Version == previous.Version && job.node.Size == previous.Size {
changedBytes, err := b.pending.get("changed", nativeInodeKey(job.node.Inode))
if err != nil {
return err
}
changed = changedBytes != nil
}
if changed {
usedBlockDiff := false
if trusted && job.node.Size >= nativeBlockThreshold {
old, err := b.source.Stat(path.Join(b.round.BaseSourcePath, job.rel))
if err == nil && old.Kind() == storage.Regular && old.Inode == job.node.Inode {
stream, err := b.source.BlockDiff(b.snapRoot, path.Join(b.snapRel, job.rel), b.round.BaseName, b.round.Name)
if err == nil {
usedBlockDiff = true
if err = b.copyBlocks(ctx, job, stream); err != nil {
return fmt.Errorf("native blockdiff %s: %w", job.rel, err)
}
b.blockFiles.Add(1)
} else if !errors.Is(err, syscall.ENOSYS) && !errors.Is(err, syscall.EOPNOTSUPP) && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.EINVAL) {
return err
}
} else if err != nil && !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.ENOTDIR) {
return err
}
}
if !usedBlockDiff {
if err := b.copyFull(ctx, job); err != nil {
return fmt.Errorf("native full copy %s: %w", job.rel, err)
}
if err := b.pending.put("full", []byte(job.rel), []byte{1}); err != nil {
return err
}
}
b.copied.Add(1)
}
if err := syncNativeMetadata(b.source, b.target, from, to, job.node, false); err != nil {
return err
}
current, err := b.target.Stat(to)
if err != nil {
return err
}
return b.pending.put("paths", []byte(job.rel), encodeEntry(baseEntry{Inode: job.node.Inode, Version: job.node.Version, Size: job.node.Size, TargetInode: current.Inode}))
}
func (b *nativeTransport) copyFull(ctx context.Context, job nativeJob) (result error) {
from, to := path.Join(b.round.SourcePath, job.rel), path.Join(b.round.TargetPath, job.rel)
source, err := b.source.Open(from, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer source.Close()
old, err := b.target.Stat(to)
if err != nil && !errors.Is(err, syscall.ENOENT) {
return err
}
if err == nil && old.Kind() == storage.Directory {
if err = removeNative(ctx, b.target, to); err != nil {
return err
}
}
id, err := newID()
if err != nil {
return err
}
temporary := path.Join(path.Dir(to), ".cephmig-file-"+id)
target, err := b.target.Open(temporary, syscall.O_CREAT|syscall.O_EXCL|syscall.O_RDWR|syscall.O_NOFOLLOW, 0600)
if err != nil {
return err
}
defer func() {
if target != nil {
if err := target.Close(); result == nil {
result = err
}
}
if result != nil {
_ = b.target.Unlink(temporary)
}
}()
buffer := make([]byte, min(job.node.Size, uint64(nativeChunk)))
for off := uint64(0); off < job.node.Size; {
if err = ctx.Err(); err != nil {
return err
}
length := min(uint64(len(buffer)), job.node.Size-off)
chunk := buffer[:int(length)]
if err = readNativeAt(source, chunk, int64(off)); err != nil {
return err
}
if !allZero(chunk) {
if err = b.rate(ctx, len(chunk)); err != nil {
return err
}
if err = writeNativeAt(target, chunk, int64(off)); err != nil {
return err
}
b.written.Add(int64(length))
}
off += length
}
if err = target.Truncate(int64(job.node.Size)); err != nil {
return err
}
if err = target.Sync(); err != nil {
return err
}
if err = target.Close(); err != nil {
return err
}
target = nil
return b.target.Rename(temporary, to)
}
func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks storage.BlockStream) (result error) {
defer func() {
if err := blocks.Close(); result == nil {
result = err
}
}()
source, err := b.source.Open(path.Join(b.round.SourcePath, job.rel), syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer source.Close()
target, err := b.target.Open(path.Join(b.round.TargetPath, job.rel), syscall.O_RDWR|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer func() {
if err := target.Close(); result == nil {
result = err
}
}()
buffer := make([]byte, nativeChunk)
for {
if err = ctx.Err(); err != nil {
return err
}
ranges, err := blocks.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
for _, extent := range ranges {
if extent.Offset > job.node.Size {
continue
}
length := min(extent.Length, job.node.Size-extent.Offset)
if extent.Length > ^uint64(0)-extent.Offset {
return errors.New("blockdiff extent overflows")
}
for copied := uint64(0); copied < length; {
if err = ctx.Err(); err != nil {
return err
}
count := min(uint64(len(buffer)), length-copied)
chunk := buffer[:int(count)]
off := extent.Offset + copied
if err = readNativeAt(source, chunk, int64(off)); err != nil {
return err
}
punched := false
if allZero(chunk) {
err = target.PunchHole(int64(off), int64(count))
if err == nil {
punched = true
} else if !errors.Is(err, syscall.EOPNOTSUPP) && !errors.Is(err, syscall.ENOSYS) && !errors.Is(err, syscall.EINVAL) {
return err
}
}
if !punched {
if err = b.rate(ctx, len(chunk)); err != nil {
return err
}
if err = writeNativeAt(target, chunk, int64(off)); err != nil {
return err
}
b.written.Add(int64(count))
}
if err = b.pending.extent(job.rel, off, count); err != nil {
return err
}
copied += count
}
}
}
if err = target.Truncate(int64(job.node.Size)); err != nil {
return err
}
return target.Sync()
}
func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
if b.pending == nil || from != b.round.SourcePath {
return errors.New("native verification round is not initialized")
}
if err := b.pending.requireInventory(); err != nil {
return err
}
skipData := b.verified[to]
scratch, err := osNativeVerifyIndex(b.workspace)
if err != nil {
return err
}
defer scratch.cleanup()
index := scratch.index
lastProgress := time.Now()
var verifiedPaths uint64
err = walkNative(ctx, b.source, from, func(p string, n storage.Node, _ int) error {
verifiedPaths++
if b.log != nil && time.Since(lastProgress) >= 30*time.Second {
fmt.Fprintf(b.log, "native verifying paths=%d target=%s\n", verifiedPaths, to)
lastProgress = time.Now()
}
rel, err := relativeNative(from, p)
if err != nil {
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 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)
}
}
}
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
})
if err != nil {
return err
}
if err = b.verifyInventory(ctx, to); err == nil {
b.verified[to] = true
}
return err
}
func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error {
if err := b.pending.requireInventory(); err != nil {
return err
}
// The source snapshot is immutable. Check the complete local inventory,
// including aliases/directories/special files, rather than stat every source
// path again. Target traversal still detects every unexpected entry.
return walkNative(ctx, b.target, to, func(p string, _ storage.Node, _ int) error {
rel, err := relativeNative(to, p)
if err != nil {
return err
}
present, err := b.pending.containsPath(rel)
if err != nil {
return err
}
if !present {
return fmt.Errorf("unexpected native target entry %s", rel)
}
return nil
})
}
func (b *nativeTransport) compareRange(ctx context.Context, from, to string, offset, length uint64) error {
if length == 0 {
return nil
}
source, err := b.source.Open(from, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer source.Close()
target, err := b.target.Open(to, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return err
}
defer target.Close()
bufferSize := min(length, uint64(nativeChunk))
a, v := make([]byte, bufferSize), make([]byte, bufferSize)
for done := uint64(0); done < length; {
if err = ctx.Err(); err != nil {
return err
}
count := min(uint64(len(a)), length-done)
if err = readNativeAt(source, a[:int(count)], int64(offset+done)); err != nil {
return err
}
if err = readNativeAt(target, v[:int(count)], int64(offset+done)); err != nil {
return err
}
if !bytes.Equal(a[:int(count)], v[:int(count)]) {
return fmt.Errorf("native content mismatch at %s offset %d", to, offset+done)
}
b.checked.Add(int64(count))
done += count
}
return nil
}
+27
View File
@@ -0,0 +1,27 @@
//go:build ceph && cgo
package migration
import (
"context"
"io"
"CephMig/internal/cephfsnative"
)
func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine, io.Closer, error) {
if err := ctx.Err(); err != nil {
return Engine{}, nil, err
}
source, err := cephfsnative.Open(options(c.Source))
if err != nil {
return Engine{}, nil, err
}
target, err := cephfsnative.Open(options(c.Target))
if err != nil {
source.Close()
return Engine{}, nil, err
}
backend := &nativeTransport{source: source, target: target, config: c, log: log}
return Engine{Exec: x, Log: log, Transport: backend, Access: nativeAccess{backend}}, backend, nil
}
+13
View File
@@ -0,0 +1,13 @@
//go:build !ceph || !cgo
package migration
import (
"context"
"errors"
"io"
)
func openNativeEngine(context.Context, Config, Executor, io.Writer) (Engine, io.Closer, error) {
return Engine{}, nil, errors.New("native backend is not compiled in; use the ceph-tagged build with libcephfs (make dev-native-build)")
}
+264
View File
@@ -0,0 +1,264 @@
package migration
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"path"
"strings"
"syscall"
"CephMig/internal/storage"
)
func walkNative(ctx context.Context, fs storage.FS, root string, visit func(string, storage.Node, int) error) error {
var walk func(string, storage.Node, int) error
walk = func(p string, n storage.Node, depth int) error {
if err := ctx.Err(); err != nil {
return err
}
if depth > 128 {
return errors.New("native directory depth exceeds 128")
}
if err := visit(p, n, depth); err != nil {
return err
}
if n.Kind() != storage.Directory {
return nil
}
dir, err := fs.OpenDir(p)
if err != nil {
return err
}
defer dir.Close()
for {
e, err := dir.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if e == nil || e.Name == "" || strings.ContainsAny(e.Name, "/\x00") || e.Name == "." || e.Name == ".." || e.Name == ".snap" {
return errors.New("invalid native directory entry")
}
if err = walk(path.Join(p, e.Name), e.Node, depth+1); err != nil {
return err
}
}
}
n, err := fs.Stat(root)
if err != nil {
return err
}
return walk(root, n, 0)
}
func removeNative(ctx context.Context, fs storage.FS, p string) error {
if err := ctx.Err(); err != nil {
return err
}
n, err := fs.Stat(p)
if errors.Is(err, syscall.ENOENT) {
return nil
}
if err != nil {
return err
}
if n.Kind() != storage.Directory {
return fs.Unlink(p)
}
d, err := fs.OpenDir(p)
if err != nil {
return err
}
// Re-open after each bounded batch, so deleting while iterating does not skip
// entries on directory streams whose offsets change after removal.
for {
var names []string
for len(names) < 128 {
e, err := d.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
d.Close()
return err
}
names = append(names, e.Name)
}
if err = d.Close(); err != nil {
return err
}
if len(names) == 0 {
break
}
for _, s := range names {
if err = removeNative(ctx, fs, path.Join(p, s)); err != nil {
return err
}
}
d, err = fs.OpenDir(p)
if err != nil {
return err
}
}
return fs.Rmdir(p)
}
func nativeQuota(fs storage.FS, p, key string) ([]byte, error) {
b, err := fs.GetXattr(p, key)
if errors.Is(err, syscall.ENODATA) {
return []byte("0"), nil
}
return b, err
}
func clearNativeQuotas(ctx context.Context, fs storage.FS, root string) error {
return walkNative(ctx, fs, root, func(p string, n storage.Node, _ int) error {
if n.Kind() != storage.Directory {
return nil
}
for _, key := range quotaKeys {
b, err := nativeQuota(fs, p, key)
if err != nil {
return err
}
if string(b) != "0" {
if err = fs.SetXattr(p, key, []byte("0")); err != nil {
return err
}
}
}
return nil
})
}
func portableXattr(s string) bool {
return !strings.HasPrefix(s, "ceph.") && (!strings.HasPrefix(s, "system.") || s == "system.posix_acl_access" || s == "system.posix_acl_default")
}
func nativeAttrs(fs storage.FS, p string) (map[string][]byte, error) {
names, err := fs.ListXattr(p)
if err != nil {
return nil, err
}
attrs := make(map[string][]byte, len(names))
for _, key := range names {
if !portableXattr(key) {
continue
}
value, err := fs.GetXattr(p, key)
if err != nil {
return nil, err
}
attrs[key] = value
}
return attrs, nil
}
func syncNativeMetadata(src, dst storage.FS, from, to string, n storage.Node, verify bool) error {
target, err := dst.Stat(to)
if err != nil {
return err
}
return syncNativeMetadataKnown(src, dst, from, to, n, target, verify)
}
// Reuse a no-follow stat just read by the caller. No other writer is permitted
// in the target while a migration owns it.
func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target storage.Node, verify bool) error {
if n.Kind() != target.Kind() {
return fmt.Errorf("native type mismatch at %s", to)
}
different := n.Mode != target.Mode || n.UID != target.UID || n.GID != target.GID || !n.Mtime.Equal(target.Mtime)
if different {
if verify {
return fmt.Errorf("native metadata mismatch at %s", to)
}
if err := dst.SetAttr(to, n); err != nil {
return fmt.Errorf("native setattr %s: %w", to, err)
}
}
attrs, err := nativeAttrs(src, from)
if err != nil {
return err
}
old, err := nativeAttrs(dst, to)
if err != nil {
return err
}
for k, v := range old {
value, exists := attrs[k]
if verify {
if !exists || !bytes.Equal(value, v) {
return fmt.Errorf("native xattr mismatch at %s: %s", to, k)
}
} else if !exists {
if err = dst.RemoveXattr(to, k); err != nil {
return err
}
}
}
for k, v := range attrs {
if verify {
if actual, ok := old[k]; !ok || !bytes.Equal(v, actual) {
return fmt.Errorf("native xattr mismatch at %s: %s", to, k)
}
} else if actual, exists := old[k]; !exists || !bytes.Equal(actual, v) {
if err = dst.SetXattr(to, k, v); err != nil {
return fmt.Errorf("native setxattr %s: %w", k, err)
}
}
}
if n.Kind() == storage.Directory {
for _, key := range quotaKeys {
value, err := nativeQuota(src, from, key)
if err != nil {
return err
}
actual, err := nativeQuota(dst, to, key)
if err != nil {
return err
}
if bytes.Equal(value, actual) {
continue
}
if verify {
return fmt.Errorf("native quota mismatch at %s: %s", to, key)
}
if err = dst.SetXattr(to, key, value); err != nil {
return err
}
}
}
return nil
}
func ensureNativeDirectory(ctx context.Context, fs storage.FS, p string) error {
st, err := fs.Stat(p)
if err == nil && st.Kind() == storage.Directory {
return nil
}
if err != nil && !errors.Is(err, syscall.ENOENT) {
return err
}
if err == nil {
if err = removeNative(ctx, fs, p); err != nil {
return err
}
}
return fs.Mkdir(p, 0700)
}
func validateNativeDirectory(fs storage.FS, p string) error {
current := "/"
for _, part := range strings.Split(strings.TrimPrefix(p, "/"), "/") {
if part == "" || part == "." || part == ".." {
return fmt.Errorf("invalid native path %q", p)
}
current = path.Join(current, part)
n, err := fs.Stat(current)
if err != nil {
return err
}
if n.Kind() != storage.Directory {
return fmt.Errorf("native path contains non-directory %s", current)
}
}
return nil
}
+229
View File
@@ -0,0 +1,229 @@
package migration
import (
"bytes"
"encoding/binary"
"errors"
"os"
"path/filepath"
"time"
bolt "go.etcd.io/bbolt"
)
var nativeBuckets = []string{"meta", "paths", "groups", "aliases", "dirs", "full", "ranges", "changed", "delete"}
type nativeIndex struct {
db *bolt.DB
path string
}
type baseEntry struct{ Inode, Version, Size, TargetInode uint64 }
func encodeEntry(e baseEntry) []byte {
b := make([]byte, 32)
binary.BigEndian.PutUint64(b, e.Inode)
binary.BigEndian.PutUint64(b[8:], e.Version)
binary.BigEndian.PutUint64(b[16:], e.Size)
binary.BigEndian.PutUint64(b[24:], e.TargetInode)
return b
}
func decodeEntry(b []byte) (baseEntry, bool) {
if len(b) != 32 {
return baseEntry{}, false
}
return baseEntry{binary.BigEndian.Uint64(b), binary.BigEndian.Uint64(b[8:]), binary.BigEndian.Uint64(b[16:]), binary.BigEndian.Uint64(b[24:])}, true
}
func createNativeIndex(parent string) (*nativeIndex, error) {
f, err := os.CreateTemp(parent, "pending-*.bolt")
if err != nil {
return nil, err
}
p := f.Name()
if err = f.Close(); err != nil {
return nil, err
}
db, err := bolt.Open(p, 0600, &bolt.Options{Timeout: time.Second, NoSync: true})
if err != nil {
os.Remove(p)
return nil, err
}
err = db.Update(func(tx *bolt.Tx) error {
for _, s := range nativeBuckets {
if _, err := tx.CreateBucketIfNotExists([]byte(s)); err != nil {
return err
}
}
return nil
})
if err != nil {
db.Close()
os.Remove(p)
return nil, err
}
return &nativeIndex{db: db, path: p}, nil
}
func openNativeIndex(path string) (*nativeIndex, error) {
db, err := bolt.Open(path, 0600, &bolt.Options{ReadOnly: true, Timeout: time.Second})
if err != nil {
return nil, err
}
return &nativeIndex{db: db, path: path}, nil
}
func (x *nativeIndex) close() error {
if x == nil || x.db == nil {
return nil
}
err := x.db.Close()
x.db = nil
return err
}
func (x *nativeIndex) get(bucket string, key []byte) ([]byte, error) {
var b []byte
err := x.db.View(func(tx *bolt.Tx) error {
k := tx.Bucket([]byte(bucket))
if k == nil {
return errors.New("invalid native index")
}
b = bytes.Clone(k.Get(key))
return nil
})
return b, err
}
func (x *nativeIndex) put(bucket string, key, value []byte) error {
return x.db.Update(func(tx *bolt.Tx) error { return tx.Bucket([]byte(bucket)).Put(key, value) })
}
func (x *nativeIndex) entry(rel string) (baseEntry, bool, error) {
b, err := x.get("paths", []byte(rel))
if err != nil {
return baseEntry{}, false, err
}
e, ok := decodeEntry(b)
return e, ok, nil
}
// Source inventory entries also cover directories and special files. A zero
// target inode marks entries that cannot yet serve as a verified data base.
func (x *nativeIndex) containsPath(rel string) (bool, error) {
b, err := x.get("paths", []byte(rel))
if err != nil || b == nil {
return false, err
}
if _, ok := decodeEntry(b); !ok {
return false, errors.New("invalid source inventory entry")
}
return true, nil
}
func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error {
previous, ok, err := x.entry(rel)
if err != nil {
return err
}
if ok && previous == entry {
return nil
}
return x.put("paths", []byte(rel), encodeEntry(entry))
}
func (x *nativeIndex) requireInventory() error {
complete, err := x.get("meta", []byte("inventory_complete"))
if err != nil {
return err
}
if !bytes.Equal(complete, []byte{1}) {
return errors.New("source inventory is not complete")
}
return nil
}
func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byte) error) error {
// The read transaction deliberately spans the iteration. Callbacks must not
// write to this same DB (which could deadlock a mmap resize).
return x.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
if b == nil {
return errors.New("missing native index bucket")
}
c := b.Cursor()
var k, v []byte
if reverse {
k, v = c.Last()
} else {
k, v = c.First()
}
for k != nil {
if err := visit(k, v); err != nil {
return err
}
if reverse {
k, v = c.Prev()
} else {
k, v = c.Next()
}
}
return nil
})
}
func (x *nativeIndex) ranges(rel string, visit func(uint64, uint64) error) error {
prefix := append([]byte(rel), 0)
return x.db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("ranges")).Cursor()
for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
if len(k) != len(prefix)+8 || len(v) != 8 {
return errors.New("invalid native extent record")
}
if err := visit(binary.BigEndian.Uint64(k[len(prefix):]), binary.BigEndian.Uint64(v)); err != nil {
return err
}
}
return nil
})
}
func (x *nativeIndex) extent(rel string, off, length uint64) error {
key := make([]byte, len(rel)+1+8)
copy(key, rel)
binary.BigEndian.PutUint64(key[len(rel)+1:], off)
value := make([]byte, 8)
binary.BigEndian.PutUint64(value, length)
return x.put("ranges", key, value)
}
func nativeInodeKey(ino uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, ino)
return b
}
func nativeDirKey(rel string, depth int) []byte {
b := make([]byte, 2+len(rel))
binary.BigEndian.PutUint16(b, uint16(depth))
copy(b[2:], rel)
return b
}
func (x *nativeIndex) commit(parent, name string) error {
if err := x.put("meta", []byte("snapshot"), []byte(name)); err != nil {
return err
}
if err := x.db.Sync(); err != nil {
return err
}
if err := x.close(); err != nil {
return err
}
final := filepath.Join(parent, "base.bolt")
if err := os.Rename(x.path, final); err != nil {
return err
}
d, err := os.Open(parent)
if err != nil {
return err
}
err = d.Sync()
d.Close()
if err != nil {
return err
}
read, err := openNativeIndex(final)
if err != nil {
return err
}
x.path, x.db = read.path, read.db
return nil
}
+159
View File
@@ -0,0 +1,159 @@
package migration
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"syscall"
"testing"
"time"
"CephMig/internal/storage"
)
type inventorySourceFS struct {
storage.FS
calls int
}
func (f *inventorySourceFS) Stat(string) (storage.Node, error) {
f.calls++
return storage.Node{}, errors.New("source path lookup must use immutable inventory")
}
type inventoryTargetFS struct{ storage.FS }
func (f inventoryTargetFS) Stat(p string) (storage.Node, error) {
var s syscall.Stat_t
err := syscall.Lstat(p, &s)
return storage.Node{Mode: s.Mode, Inode: s.Ino, Nlink: s.Nlink, Size: uint64(s.Size), UID: s.Uid, GID: s.Gid,
Mtime: time.Unix(s.Mtim.Sec, s.Mtim.Nsec)}, err
}
func (f inventoryTargetFS) OpenDir(p string) (storage.DirectoryStream, error) {
d, err := os.Open(p)
if err != nil {
return nil, err
}
return &inventoryDir{file: d, path: p}, nil
}
func (inventoryTargetFS) Unlink(p string) error { return syscall.Unlink(p) }
func (inventoryTargetFS) Rmdir(p string) error { return syscall.Rmdir(p) }
type inventoryDir struct {
file *os.File
path string
}
func (d *inventoryDir) 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 := (inventoryTargetFS{}).Stat(filepath.Join(d.path, es[0].Name()))
return &storage.Entry{Name: es[0].Name(), Node: n}, err
}
func (d *inventoryDir) Close() error { return d.file.Close() }
func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
x, err := createNativeIndex(t.TempDir())
if err != nil {
t.Fatal(err)
}
defer x.close()
root, outside := t.TempDir(), t.TempDir()
for _, dir := range []string{"dir", "obsolete"} {
if err := os.Mkdir(filepath.Join(root, dir), 0700); err != nil {
t.Fatal(err)
}
}
for _, rel := range []string{"keep", "dir/file", "obsolete/nested"} {
if err := os.WriteFile(filepath.Join(root, rel), []byte("data"), 0600); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(outside, "sentinel"), []byte("untouched"), 0600); err != nil {
t.Fatal(err)
}
for _, rel := range []string{"link", "obsolete-link"} {
if err := os.Symlink(outside, filepath.Join(root, rel)); err != nil {
t.Fatal(err)
}
}
for _, rel := range []string{".", "keep", "dir", "dir/file", "link"} {
if err := x.put("paths", []byte(rel), encodeEntry(baseEntry{Inode: 1})); err != nil {
t.Fatal(err)
}
}
source := &inventorySourceFS{}
b := nativeTransport{source: source, target: inventoryTargetFS{}, pending: x, round: Round{SourcePath: "/immutable"}}
if err := b.prune(context.Background(), "/immutable", root); err == nil {
t.Fatal("pruned without complete inventory")
}
if _, err := os.Stat(filepath.Join(root, "obsolete/nested")); err != nil {
t.Fatal("incomplete inventory deleted target data")
}
if err := x.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
t.Fatal(err)
}
if err := b.verifyInventory(context.Background(), root); err == nil {
t.Fatal("unexpected entries were not detected")
}
if err := b.prune(context.Background(), "/immutable", root); err != nil {
t.Fatal(err)
}
if err := b.verifyInventory(context.Background(), root); err != nil {
t.Fatal(err)
}
if _, err := os.Lstat(filepath.Join(root, "obsolete")); !os.IsNotExist(err) {
t.Fatal("obsolete directory survived", err)
}
if _, err := os.Lstat(filepath.Join(root, "obsolete-link")); !os.IsNotExist(err) {
t.Fatal("obsolete symlink survived", err)
}
if data, err := os.ReadFile(filepath.Join(outside, "sentinel")); err != nil || string(data) != "untouched" {
t.Fatal("followed symlink outside target")
}
if source.calls != 0 {
t.Fatalf("performed %d redundant source stats", source.calls)
}
if err := os.WriteFile(filepath.Join(root, "dir/foreign"), nil, 0600); err != nil {
t.Fatal(err)
}
if err := b.verifyInventory(context.Background(), root); err == nil {
t.Fatal("extra target path was ignored")
}
}
func TestNativeInventoryRejectsCorruptionAndUnchangedIndexIsReadOnly(t *testing.T) {
dir := t.TempDir()
x, err := createNativeIndex(dir)
if err != nil {
t.Fatal(err)
}
defer x.close()
if err := x.put("paths", []byte("broken"), []byte{1}); err != nil {
t.Fatal(err)
}
if _, err := x.containsPath("broken"); err == nil {
t.Fatal("corrupt source inventory accepted")
}
entry := baseEntry{Inode: 1, Version: 2, Size: 128, TargetInode: 3}
if err := x.putEntryIfChanged("file", entry); err != nil {
t.Fatal(err)
}
if err := x.commit(dir, "snapshot"); err != nil {
t.Fatal(err)
}
if err := x.putEntryIfChanged("file", entry); err != nil {
t.Fatal("unchanged entry attempted a write", err)
}
entry.TargetInode++
if err := x.putEntryIfChanged("file", entry); err == nil {
t.Fatal("changed entry silently ignored on read-only index")
}
}
+234
View File
@@ -0,0 +1,234 @@
package migration
import (
"bytes"
"context"
"errors"
"io"
"path/filepath"
"reflect"
"syscall"
"testing"
"time"
"CephMig/internal/storage"
)
type emptyNativeDiff struct{}
func (emptyNativeDiff) Next() (string, error) { return "", io.EOF }
func (emptyNativeDiff) Close() error { return nil }
type diffTestFS struct {
storage.FS
err error
}
func (f diffTestFS) SnapDiff(_, _, _, _ string) (storage.DiffStream, error) {
return emptyNativeDiff{}, f.err
}
// A durable base is useful only if BOTH the journal and the filesystem identity
// match. An interrupted in-place block copy must never become the next base.
func TestNativeBaseTrust(t *testing.T) {
for _, tc := range []struct {
name, journal, identity string
apiError error
wantDelta bool
}{
{"committed", "previous", "cluster-paths", nil, true},
{"interrupted-target", "", "cluster-paths", nil, false},
{"wrong-round", "other", "cluster-paths", nil, false},
{"recreated-subvolume", "previous", "new-path", nil, false},
{"unsupported-api", "previous", "cluster-paths", syscall.ENOSYS, false},
} {
t.Run(tc.name, func(t *testing.T) {
state := filepath.Join(t.TempDir(), "job.json")
b := &nativeTransport{source: diffTestFS{err: tc.apiError}, identity: "cluster-paths"}
r := Round{SourcePath: "/sub/.snap/previous/uuid", Name: "previous", StatePath: state}
if err := b.BeginRound(context.Background(), r); err != nil {
t.Fatal(err)
}
entry := baseEntry{Inode: 42, Version: 7, Size: 1 << 30, TargetInode: 77}
if err := b.pending.put("paths", []byte("file\nname"), encodeEntry(entry)); err != nil {
t.Fatal(err)
}
if err := b.Commit(context.Background(), "previous"); err != nil {
t.Fatal(err)
}
b.identity = tc.identity
r.Name, r.SourcePath, r.BaseName = "current", "/sub/.snap/current/uuid", tc.journal
if err := b.BeginRound(context.Background(), r); err != nil {
t.Fatal(err)
}
defer b.pending.close()
if b.base != nil {
defer b.base.close()
}
if b.delta != tc.wantDelta {
t.Fatalf("delta=%v; want %v", b.delta, tc.wantDelta)
}
if b.delta {
got, ok, err := b.base.entry("file\nname")
if err != nil || !ok || got != entry {
t.Fatalf("entry=%+v ok=%v err=%v", got, ok, err)
}
}
})
}
}
func TestNativeExtentIsolation(t *testing.T) {
x, err := createNativeIndex(t.TempDir())
if err != nil {
t.Fatal(err)
}
defer x.close()
for _, e := range []struct {
name string
offset, size uint64
}{
{"a", 9000, 100}, {"a", 0, 4096}, {"ab", 12, 900}, {"a\n", 11, 1},
} {
if err := x.extent(e.name, e.offset, e.size); err != nil {
t.Fatal(err)
}
}
var got []storage.Extent
if err := x.ranges("a", func(off, length uint64) error {
got = append(got, storage.Extent{Offset: off, Length: length})
return nil
}); err != nil {
t.Fatal(err)
}
want := []storage.Extent{{Offset: 0, Length: 4096}, {Offset: 9000, Length: 100}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
type attrsTestFS struct {
storage.FS
n storage.Node
attrs map[string][]byte
setCalls int
}
func (f *attrsTestFS) Stat(string) (storage.Node, error) { return f.n, nil }
func (f *attrsTestFS) SetAttr(_ string, n storage.Node) error { f.setCalls++; f.n = n; return nil }
func (f *attrsTestFS) ListXattr(string) ([]string, error) {
var keys []string
for k := range f.attrs {
keys = append(keys, k)
}
return keys, nil
}
func (f *attrsTestFS) GetXattr(_, key string) ([]byte, error) {
if v, ok := f.attrs[key]; ok {
return v, nil
}
return nil, syscall.ENODATA
}
func (f *attrsTestFS) SetXattr(_, key string, value []byte) error {
f.attrs[key] = bytes.Clone(value)
return nil
}
func (f *attrsTestFS) RemoveXattr(_, key string) error { delete(f.attrs, key); return nil }
func TestNativeMetadataEmptyXattrAndDeletion(t *testing.T) {
n := storage.Node{Mode: storage.Regular | 0640, UID: 123, GID: 456, Mtime: time.Unix(123, 45)}
src := &attrsTestFS{n: n, attrs: map[string][]byte{"user.empty": {}, "user.data": []byte("content"), "ceph.layout": []byte("source-pool")}}
dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.old": []byte("delete"), "ceph.layout": []byte("target-pool")}}
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, false); err != nil {
t.Fatal(err)
}
if _, ok := dst.attrs["user.empty"]; !ok {
t.Fatal("empty xattr was not created")
}
if _, ok := dst.attrs["user.old"]; ok {
t.Fatal("obsolete xattr survived")
}
if string(dst.attrs["ceph.layout"]) != "target-pool" {
t.Fatal("source internal Ceph layout leaked into target")
}
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err != nil {
t.Fatal(err)
}
dst.n.UID++
if err := syncNativeMetadata(src, dst, "/src", "/dst", n, true); err == nil {
t.Fatal("owner mismatch not detected")
}
}
func TestNativeCancellationAndPaths(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
b := nativeTransport{config: Config{BandwidthKiB: 1}, started: time.Now()}
if err := b.rate(ctx, 4096); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
for _, bad := range []string{"", ".", "..", ".snap", "a/b", "a\x00b"} {
if validNativeEntry(bad) {
t.Fatalf("accepted %q", bad)
}
}
if !validNativeEntry("with spaces\nand newline") {
t.Fatal("valid filename rejected")
}
if _, err := relativeNative("/volume", "/volume-other/file"); err == nil {
t.Fatal("path escaped subvolume")
}
}
func TestNativeMetadataOnlyWritesChangedAttributes(t *testing.T) {
n := storage.Node{Mode: storage.Regular | 0640, UID: 12, GID: 34, Mtime: time.Unix(123, 0)}
src := &attrsTestFS{n: n, attrs: map[string][]byte{"user.new": []byte("value")}}
dst := &attrsTestFS{n: n, attrs: map[string][]byte{"user.old": []byte("remove")}}
if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil {
t.Fatal(err)
}
if dst.setCalls != 0 {
t.Fatal("unchanged ownership, mode and mtime were rewritten")
}
if !reflect.DeepEqual(src.attrs, dst.attrs) {
t.Fatal("xattrs must still be synchronized")
}
dst.n.UID++
if err := syncNativeMetadata(src, dst, "/source", "/target", n, false); err != nil {
t.Fatal(err)
}
if dst.setCalls != 1 || dst.n.UID != n.UID {
t.Fatal("changed ownership was not restored")
}
}
func TestNativeVerifyCommittedRound(t *testing.T) {
workspace := t.TempDir()
index, err := createNativeIndex(workspace)
if err != nil {
t.Fatal(err)
}
defer index.close()
n := storage.Node{Mode: storage.Regular | 0640, Inode: 7, Version: 1, Nlink: 1, Mtime: time.Unix(123, 0)}
src := &attrsTestFS{n: n, attrs: map[string][]byte{}}
dst := &attrsTestFS{n: n, attrs: map[string][]byte{}}
if err := index.put("groups", nativeInodeKey(n.Inode), []byte(".")); err != nil {
t.Fatal(err)
}
if err := index.put("paths", []byte("."), encodeEntry(baseEntry{Inode: n.Inode, Version: n.Version})); err != nil {
t.Fatal(err)
}
if err := index.put("meta", []byte("inventory_complete"), []byte{1}); err != nil {
t.Fatal(err)
}
if err := index.commit(workspace, "final"); err != nil {
t.Fatal(err)
}
b := nativeTransport{source: src, target: dst, pending: index, workspace: workspace,
round: Round{SourcePath: "/snapshot", TargetPath: "/live"}, verified: map[string]bool{"/live": true}}
// Finalization repeats metadata/topology verification after the durable base
// index has become read-only. It must not rewrite inode records at this stage.
if err := b.Verify(context.Background(), "/snapshot", "/live"); err != nil {
t.Fatal(err)
}
}
+461
View File
@@ -0,0 +1,461 @@
package migration
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"CephMig/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 }
+92
View File
@@ -0,0 +1,92 @@
package migration
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"syscall"
"time"
)
type Executor interface {
Exec(context.Context, io.Writer, string, ...string) error
}
type Process struct{ Stderr io.Writer }
type ProcessError struct {
Name string
Err error
Diagnostic string
}
func (e *ProcessError) Error() string { return fmt.Sprintf("%s failed: %v", e.Name, e.Err) }
func (e *ProcessError) Unwrap() error { return e.Err }
type tailBuffer struct{ data []byte }
func (b *tailBuffer) Write(p []byte) (int, error) {
const limit = 4096
n := len(p)
if n >= limit {
b.data = append(b.data[:0], p[n-limit:]...)
return n, nil
}
if len(b.data)+n > limit {
b.data = append(b.data[:0], b.data[len(b.data)+n-limit:]...)
}
b.data = append(b.data, p...)
return n, nil
}
func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdout = out
var diagnostic tailBuffer
cmd.Stderr = &diagnostic
if p.Stderr != nil {
cmd.Stderr = io.MultiWriter(p.Stderr, &diagnostic)
}
cmd.Env = append(os.Environ(), "LC_ALL=C")
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
cmd.WaitDelay = 5 * time.Second
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
// Do not print arguments: Ceph metadata values may be confidential.
return &ProcessError{Name: name, Err: err, Diagnostic: strings.TrimSpace(string(diagnostic.data))}
}
return nil
}
type limitedBuffer struct {
bytes.Buffer
limit int
}
func (b *limitedBuffer) Write(p []byte) (int, error) {
if len(p) > b.limit-b.Len() {
return 0, errors.New("command output exceeds configured limit")
}
return b.Buffer.Write(p)
}
func output(ctx context.Context, x Executor, name string, args ...string) ([]byte, error) {
b := &limitedBuffer{limit: 16 << 20}
if err := x.Exec(ctx, b, name, args...); err != nil {
return nil, err
}
return b.Bytes(), nil
}
+66
View File
@@ -0,0 +1,66 @@
package migration
import (
"context"
"errors"
"fmt"
"io"
"os/exec"
"strconv"
"strings"
)
type Transport interface {
Copy(context.Context, string, string) error
Verify(context.Context, string, string) error
}
type Rsync struct {
Exec Executor
Log io.Writer
BandwidthKiB int64
}
func (r Rsync) args(src, dst string) []string {
a := []string{"-aHAXS", "--numeric-ids", "--checksum", "--no-whole-file",
"--delete-during", "--partial", "--fsync", "--one-file-system",
"--filter=- .snap/", "--filter=-x ceph.*", "--filter=-x system.*"}
if r.BandwidthKiB > 0 {
a = append(a, "--bwlimit="+strconv.FormatInt(r.BandwidthKiB, 10))
}
return append(a, "--", src+"/", dst+"/")
}
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)...)
var processError *ProcessError
var exitError *exec.ExitError
// EEXIST was observed on Ceph-FUSE while rsync rebuilt a hardlink group.
// One idempotent retry repairs the partial group. All other errors
// are returned immediately; publication still requires full verification.
if attempt == 0 && errors.As(err, &processError) && errors.As(err, &exitError) && exitError.ExitCode() == 23 && strings.Contains(processError.Diagnostic, "link ") && strings.Contains(processError.Diagnostic, "File exists (17)") {
if r.Log != nil {
fmt.Fprintln(r.Log, "rsync hardlink EEXIST: retrying once before snapshot verification")
}
continue
}
return err
}
return errors.New("rsync retry limit reached")
}
type differences struct{ n int64 }
func (d *differences) Write(p []byte) (int, error) { d.n += int64(len(p)); return len(p), nil }
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
if err := r.Exec.Exec(ctx, &d, "rsync", args...); err != nil {
return err
}
if d.n != 0 {
return fmt.Errorf("verification found differences between %s and %s", src, dst)
}
return nil
}
+147
View File
@@ -0,0 +1,147 @@
package migration
import (
"context"
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
type executorFunc func(context.Context, io.Writer, string, ...string) error
func (f executorFunc) Exec(ctx context.Context, out io.Writer, name string, args ...string) error {
return f(ctx, out, name, args...)
}
func TestRsyncRetriesOnlyObservedHardlinkEEXIST(t *testing.T) {
exitErr := exec.Command("sh", "-c", "exit 23").Run()
for name, tc := range map[string]struct {
diagnostic string
attempts int
}{
"hardlink": {"link target failed: File exists (17)", 2},
"permission": {"Permission denied (13)", 1},
"other-eexist": {"mkdir failed: File exists (17)", 1},
} {
t.Run(name, func(t *testing.T) {
calls := 0
x := executorFunc(func(context.Context, io.Writer, string, ...string) error {
calls++
if calls == 1 {
return &ProcessError{Name: "rsync", Err: exitErr, Diagnostic: tc.diagnostic}
}
return nil
})
err := (Rsync{Exec: x, Log: io.Discard}).Copy(context.Background(), "/a", "/b")
if calls != tc.attempts {
t.Fatalf("attempts: %d", calls)
}
if (err == nil) != (tc.attempts == 2) {
t.Fatalf("unexpected result: %v", err)
}
})
}
calls := 0
x := executorFunc(func(context.Context, io.Writer, string, ...string) error { calls++; return context.Canceled })
err := (Rsync{Exec: x}).Copy(context.Background(), "/a", "/b")
if !errors.Is(err, context.Canceled) || calls != 1 {
t.Fatalf("retried cancellation: %v, %d", err, calls)
}
}
func TestRsyncDetectsSameSizeSameMtimeAndPreservesLinks(t *testing.T) {
if _, err := exec.LookPath("rsync"); err != nil {
t.Skip("rsync is not installed")
}
src, dst := t.TempDir(), t.TempDir()
path := filepath.Join(src, "file with spaces\nand newline")
if err := os.WriteFile(path, []byte("AAAA"), 0640); err != nil {
t.Fatal(err)
}
if err := os.Link(path, filepath.Join(src, "hardlink")); err != nil {
t.Fatal(err)
}
if err := os.Symlink("nonexistent", filepath.Join(src, "dangling")); err != nil {
t.Fatal(err)
}
if err := syscall.Setxattr(path, "user.cephmig", []byte("test"), 0); err != nil {
t.Fatal(err)
}
r := Rsync{Exec: Process{Stderr: io.Discard}, Log: io.Discard}
ctx := context.Background()
if err := r.Copy(ctx, src, dst); err != nil {
t.Fatal(err)
}
if err := r.Verify(ctx, src, dst); err != nil {
t.Fatal(err)
}
a, _ := os.Stat(filepath.Join(dst, "hardlink"))
b, _ := os.Stat(filepath.Join(dst, filepath.Base(path)))
if !os.SameFile(a, b) {
t.Fatal("hardlinks were split")
}
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(path, []byte("BBBB"), 0640); err != nil {
t.Fatal(err)
}
if err = os.Chtimes(path, st.ModTime(), st.ModTime()); err != nil {
t.Fatal(err)
}
if err = r.Verify(ctx, src, dst); err == nil {
t.Fatal("checksum verification missed changed bytes")
}
if err = os.WriteFile(filepath.Join(dst, "obsolete"), []byte("extra"), 0600); err != nil {
t.Fatal(err)
}
if err = r.Copy(ctx, src, dst); err != nil {
t.Fatal(err)
}
if err = r.Verify(ctx, src, dst); err != nil {
t.Fatal(err)
}
if _, err = os.Stat(filepath.Join(dst, "obsolete")); !os.IsNotExist(err) {
t.Fatal("obsolete target file survived")
}
got, err := xattr(filepath.Join(dst, "hardlink"), "user.cephmig")
if err != nil || string(got) != "test" {
t.Fatalf("xattr: %q, %v", got, err)
}
}
func TestProcessCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.Canceled {
t.Fatalf("got %v", err)
}
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
if err := (Process{Stderr: io.Discard}).Exec(ctx, io.Discard, "sleep", "60"); err != context.DeadlineExceeded {
t.Fatalf("got %v", err)
}
if time.Since(start) > 2*time.Second {
t.Fatal("cancellation was too slow")
}
}
func TestRsyncUsesIncrementalSafeOptions(t *testing.T) {
joined := strings.Join((Rsync{BandwidthKiB: 1024}).args("/source", "/target"), " ")
for _, required := range []string{"-aHAXS", "--checksum", "--delete-during", "--no-whole-file", "--fsync", "--bwlimit=1024", "--filter=-x ceph.*"} {
if !strings.Contains(joined, required) {
t.Fatalf("missing %s", required)
}
}
for _, bad := range []string{"--inplace", "--delete-before", "--delete-after", "--delay-updates"} {
if strings.Contains(joined, bad) {
t.Fatalf("unsafe option %s", bad)
}
}
}
+146
View File
@@ -0,0 +1,146 @@
package migration
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"syscall"
)
const stateVersion = 1
type Snapshot struct {
Name string `json:"name"`
CreatedAt string `json:"source_created_at"`
TargetCreatedAt string `json:"target_created_at,omitempty"`
Owned bool `json:"owned"`
Final bool `json:"final,omitempty"`
Done bool `json:"done"`
Metadata map[string]string `json:"metadata,omitempty"`
Stats *TransferStats `json:"transfer,omitempty"`
}
type State struct {
Version int `json:"version"`
ID string `json:"id"`
Config Config `json:"config"`
SourceFSID string `json:"source_fsid"`
TargetFSID string `json:"target_fsid"`
SourcePath string `json:"source_path"`
TargetPath string `json:"target_path"`
Phase string `json:"phase"`
Snapshots []Snapshot `json:"snapshots"`
Notes []string `json:"notes,omitempty"`
LiveSnapshot string `json:"live_snapshot,omitempty"`
}
func LoadState(path string) (*State, error) {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
defer f.Close()
var s State
d := json.NewDecoder(f)
d.DisallowUnknownFields()
if err := d.Decode(&s); err != nil {
return nil, fmt.Errorf("state: %w", err)
}
if err := d.Decode(new(any)); !errors.Is(err, io.EOF) {
return nil, errors.New("state must contain exactly one JSON object")
}
id, err := hex.DecodeString(s.ID)
if s.Version != stateVersion || err != nil || len(id) != 16 {
return nil, errors.New("unsupported or invalid state")
}
if s.Phase != "syncing" && s.Phase != "ready-for-cutover" {
return nil, errors.New("invalid state phase")
}
names := map[string]bool{}
for _, snap := range s.Snapshots {
if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) {
return nil, errors.New("invalid snapshot state")
}
names[snap.Name] = true
}
if s.LiveSnapshot != "" {
confirmed := false
for _, snap := range s.Snapshots {
if snap.Name == s.LiveSnapshot && snap.Done {
confirmed = true
break
}
}
if !confirmed {
return nil, errors.New("live base must reference a completed snapshot")
}
}
if s.Phase == "ready-for-cutover" {
if len(s.Snapshots) == 0 {
return nil, errors.New("ready state has no snapshots")
}
for _, snap := range s.Snapshots {
if !snap.Done {
return nil, errors.New("ready state has incomplete snapshots")
}
}
if !s.Snapshots[len(s.Snapshots)-1].Final {
return nil, errors.New("ready state has no final snapshot")
}
}
if err := s.Config.Validate(); err != nil {
return nil, fmt.Errorf("state config: %w", err)
}
return &s, nil
}
func SaveState(path string, s *State) error {
return atomicJSON(path, s)
}
func atomicJSON(path string, v any) error {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, ".cephmig-state-*")
if err != nil {
return err
}
name := f.Name()
defer os.Remove(name)
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err = enc.Encode(v); err != nil {
return err
}
if err = f.Sync(); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
if err = os.Rename(name, path); err != nil {
return err
}
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
return d.Sync()
}
func lockFile(path string) (*os.File, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
if err != nil {
return nil, err
}
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
f.Close()
return nil, fmt.Errorf("another process holds lock %s: %w", path, err)
}
return f, nil
}
+141
View File
@@ -0,0 +1,141 @@
package migration
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"testing"
)
func testState() *State {
return &State{Version: stateVersion, ID: "1234567890abcdef1234567890abcdef", Config: testConfig(), Phase: "syncing"}
}
func TestStateAtomicAndPrivate(t *testing.T) {
p := filepath.Join(t.TempDir(), "state.json")
s := testState()
s.Notes = []string{SnapshotIdentityNote}
if err := SaveState(p, s); err != nil {
t.Fatal(err)
}
st, err := os.Stat(p)
if err != nil || st.Mode().Perm() != 0600 {
t.Fatalf("state permissions: %v, %v", st, err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 40; i++ {
if err := SaveState(p, s); err != nil {
t.Error(err)
return
}
}
}()
for i := 0; i < 100; i++ {
got, err := LoadState(p)
if err != nil {
t.Fatalf("reader observed partial state: %v", err)
}
if got.ID != s.ID {
t.Fatal("state identity changed")
}
if len(got.Notes) != 1 || got.Notes[0] != SnapshotIdentityNote {
t.Fatal("snapshot identity note was lost")
}
}
wg.Wait()
}
func TestStateRejectsCorruption(t *testing.T) {
for name, modify := range map[string]func(*State){
"version": func(s *State) { s.Version++ },
"short-id": func(s *State) { s.ID = "bad" },
"phase": func(s *State) { s.Phase = "finished" },
"ready-without-final": func(s *State) { s.Phase = "ready-for-cutover" },
"duplicate": func(s *State) { s.Snapshots = []Snapshot{{Name: "a"}, {Name: "a"}} },
"invalid-done": func(s *State) { s.Snapshots = []Snapshot{{Name: "a", Done: true}} },
"missing-live-base": func(s *State) { s.LiveSnapshot = "missing" },
"pending-live-base": func(s *State) {
s.Snapshots = []Snapshot{{Name: "pending"}}
s.LiveSnapshot = "pending"
},
} {
t.Run(name, func(t *testing.T) {
p := filepath.Join(t.TempDir(), "state.json")
s := testState()
modify(s)
if err := SaveState(p, s); err != nil {
t.Fatal(err)
}
if _, err := LoadState(p); err == nil {
t.Fatal("accepted corrupt state")
}
})
}
p := filepath.Join(t.TempDir(), "state.json")
b, _ := json.Marshal(testState())
if err := os.WriteFile(p, append(b, []byte(" {}")...), 0600); err != nil {
t.Fatal(err)
}
if _, err := LoadState(p); err == nil {
t.Fatal("accepted trailing data")
}
}
func TestLockExclusionAndRelease(t *testing.T) {
p := filepath.Join(t.TempDir(), "lock")
first, err := lockFile(p)
if err != nil {
t.Fatal(err)
}
if second, err := lockFile(p); err == nil {
second.Close()
t.Fatal("second process acquired lock")
}
first.Close()
third, err := lockFile(p)
if err != nil {
t.Fatal(err)
}
third.Close()
}
func TestTargetClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) {
root := t.TempDir()
c := testConfig()
first, err := claimTarget(root, "fsid", c.Target, "job-one")
if err != nil {
t.Fatal(err)
}
if second, err := claimTarget(root, "fsid", c.Target, "job-one"); err == nil {
second.Close()
t.Fatal("concurrent use allowed")
}
first.Close()
if other, err := claimTarget(root, "fsid", c.Target, "job-two"); err == nil {
other.Close()
t.Fatal("different job stole target")
}
resumed, err := claimTarget(root, "fsid", c.Target, "job-one")
if err != nil {
t.Fatal(err)
}
resumed.Close()
}
func TestStateAndLockRejectSymlinks(t *testing.T) {
root := t.TempDir()
real := filepath.Join(root, "real")
if err := SaveState(real, testState()); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "link")
if err := os.Symlink(real, link); err != nil {
t.Fatal(err)
}
if _, err := LoadState(link); err == nil {
t.Fatal("followed state symlink")
}
if f, err := lockFile(link); err == nil {
f.Close()
t.Fatal("followed lock symlink")
}
}
+79
View File
@@ -0,0 +1,79 @@
// Package storage defines the native filesystem operations used by the copier.
package storage
import (
"io"
"time"
)
type Node struct {
Mode uint32
Inode, Version, Nlink, Size, Rdev uint64
UID, GID uint32
Mtime time.Time
}
const (
TypeMask uint32 = 0170000
Regular uint32 = 0100000
Directory uint32 = 0040000
Symlink uint32 = 0120000
FIFO uint32 = 0010000
Socket uint32 = 0140000
BlockDevice uint32 = 0060000
CharDevice uint32 = 0020000
)
func (n Node) Kind() uint32 { return n.Mode & TypeMask }
type Entry struct {
Name string
Node Node
}
type DirectoryStream interface {
Next() (*Entry, error)
Close() error
}
type File interface {
io.ReaderAt
io.WriterAt
io.Closer
Truncate(int64) error
Sync() error
Lock(uint64) error
PunchHole(int64, int64) error
}
type DiffStream interface {
Next() (string, error)
Close() error
}
type Extent struct{ Offset, Length uint64 }
type BlockStream interface {
Next() ([]Extent, error)
Close() error
}
type FS interface {
Stat(string) (Node, error) // Never follows the final symlink.
Open(string, int, uint32) (File, error)
OpenDir(string) (DirectoryStream, error)
Mkdir(string, uint32) error
Unlink(string) error
Rmdir(string) error
Rename(string, string) error
Link(string, string) error
Symlink(string, string) error
Readlink(string) (string, error)
Mknod(string, uint32, uint64) error
SetAttr(string, Node) error // Numeric owner, mode and mtime; no symlink following.
ListXattr(string) ([]string, error)
GetXattr(string, string) ([]byte, error)
SetXattr(string, string, []byte) error
RemoveXattr(string, string) error
SnapDiff(string, string, string, string) (DiffStream, error)
BlockDiff(string, string, string, string) (BlockStream, error)
Sync() error
Close() error
}
type Options struct{ Config, Keyring, User, Filesystem string }