style: add blank lines between declarations and statement blocks
Separate top-level declarations and multi-line statements with blank lines, keeping an "if err != nil" check next to the statement it belongs to. Expand semicolon one-liners, group the nativeTransport fields by purpose, and format the cgo preamble as readable C. Apart from the expanded one-liners and the C preamble, the change is whitespace only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec0297fd23
commit
a6fda8f8d3
25 files changed
+929
-41
No files matched your search
@@ -12,6 +12,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -30,29 +31,38 @@ 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{}
|
||||
}
|
||||
|
||||
@@ -98,6 +108,7 @@ func NewEngine(ctx context.Context, c Config, x Executor, log io.Writer) (Engine
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -23,124 +23,156 @@ func (c ceph) call(ctx context.Context, args ...string) ([]byte, error) {
|
||||
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
|
||||
}
|
||||
@@ -41,22 +41,27 @@ func ReadConfig(path string) (Config, error) {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -71,9 +76,11 @@ 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
|
||||
@@ -81,30 +88,37 @@ func (c Config) Validate() error {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -112,6 +126,7 @@ 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) }
|
||||
|
||||
// dataPath resolves cephPath to a real directory below the filesystem mount
|
||||
@@ -120,20 +135,25 @@ 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
|
||||
}
|
||||
@@ -12,6 +12,7 @@ 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" },
|
||||
@@ -33,6 +34,7 @@ func TestConfigRejectsUnsafePathsAndNames(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if err := testConfig().Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -45,16 +47,19 @@ func TestNativeConfigAndResumeSettings(t *testing.T) {
|
||||
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])} {
|
||||
@@ -63,37 +68,45 @@ func TestStrictJSONConfig(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -66,38 +66,48 @@ func queryEndpoint(ctx context.Context, c ceph) (string, endpointInfo, error) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -105,38 +115,48 @@ func inspectMounted(ctx context.Context, c Config, x Executor) (*Inspection, err
|
||||
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
|
||||
@@ -147,6 +167,7 @@ func newID() (string, error) {
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
@@ -155,14 +176,17 @@ func emptyDirectory(path string) error {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -174,16 +198,19 @@ func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) {
|
||||
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
|
||||
}
|
||||
@@ -193,26 +220,32 @@ func claimTarget(root, fsid string, ep Endpoint, id string) (*os.File, error) {
|
||||
} 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
|
||||
}
|
||||
|
||||
@@ -223,15 +256,19 @@ func snapshotDetails(ctx context.Context, src ceph, name string) (Snapshot, erro
|
||||
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
|
||||
@@ -245,79 +282,98 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
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 !slices.Contains(s.Notes, SnapshotIdentityNote) {
|
||||
@@ -326,16 +382,20 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
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 {
|
||||
@@ -344,40 +404,50 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
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 {
|
||||
@@ -385,89 +455,113 @@ func (e Engine) Sync(ctx context.Context, c Config, statePath string, final bool
|
||||
if !slices.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 slices.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
|
||||
@@ -481,33 +575,41 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !slices.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 := slices.Contains(targetNames, snap.Name)
|
||||
if isNative {
|
||||
@@ -518,10 +620,12 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
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
|
||||
@@ -530,65 +634,82 @@ func (e Engine) transfer(ctx context.Context, src, dst ceph, target, statePath s
|
||||
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
|
||||
}
|
||||
@@ -27,11 +27,13 @@ func openLinkIndex(path string) (*linkIndex, error) {
|
||||
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()
|
||||
@@ -39,14 +41,18 @@ func openLinkIndex(path string) (*linkIndex, error) {
|
||||
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[:])
|
||||
@@ -58,6 +64,7 @@ func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
} else {
|
||||
same = bytes.Equal(old, value[:])
|
||||
}
|
||||
|
||||
x.observations++
|
||||
// Limit dirty transaction state; the complete relation stays on disk.
|
||||
if x.observations%4096 == 0 {
|
||||
@@ -66,19 +73,23 @@ func (x *linkIndex) observe(bucket string, key, value [16]byte) (bool, error) {
|
||||
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
|
||||
@@ -93,28 +104,34 @@ func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repai
|
||||
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.
|
||||
@@ -123,19 +140,24 @@ func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repai
|
||||
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
|
||||
@@ -143,44 +165,55 @@ func hardlinkTopology(ctx context.Context, src, dst, scratchParent string, repai
|
||||
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)
|
||||
}
|
||||
@@ -16,111 +16,139 @@ func mustWrite(t *testing.T, path string) {
|
||||
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
|
||||
@@ -131,11 +159,13 @@ func TestHardlinkDiskIndexSurvivesBatchBoundaries(t *testing.T) {
|
||||
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)
|
||||
|
||||
@@ -23,30 +23,37 @@ 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
|
||||
@@ -55,36 +62,45 @@ func checkMount(root string, writable bool) error {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -97,9 +113,11 @@ func xattr(path, key string) ([]byte, error) {
|
||||
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) {
|
||||
@@ -108,8 +126,10 @@ func xattr(path, key string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b[:n], nil
|
||||
}
|
||||
|
||||
return nil, errors.New("xattr changed repeatedly")
|
||||
}
|
||||
|
||||
@@ -128,9 +148,11 @@ func walkTree(ctx context.Context, root string, visitDir func(string) error, vis
|
||||
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
|
||||
@@ -138,10 +160,12 @@ func walkTree(ctx context.Context, root string, visitDir func(string) error, vis
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
for {
|
||||
batch, readErr := f.ReadDir(128)
|
||||
@@ -149,9 +173,11 @@ func walkTree(ctx context.Context, root string, visitDir func(string) error, vis
|
||||
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 {
|
||||
@@ -162,19 +188,23 @@ func walkTree(ctx context.Context, root string, visitDir func(string) error, vis
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -185,13 +215,16 @@ func clearQuotas(ctx context.Context, root string) error {
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -202,33 +235,41 @@ func quotas(ctx context.Context, src, dst string, verify bool) error {
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -22,17 +22,21 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe
|
||||
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
|
||||
@@ -40,34 +44,42 @@ func (a nativeAccess) Inspect(ctx context.Context, c Config, x Executor) (*Inspe
|
||||
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) {
|
||||
@@ -76,12 +88,15 @@ func (a nativeAccess) Empty(ctx context.Context, p string) error {
|
||||
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"} {
|
||||
@@ -91,15 +106,18 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.
|
||||
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)
|
||||
@@ -107,6 +125,7 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.
|
||||
if err = writeNativeAt(f, []byte(id+"\n"), 0); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
|
||||
closeErr := f.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
@@ -117,36 +136,45 @@ func (a nativeAccess) Claim(ctx context.Context, c Config, fsid, id string) (io.
|
||||
} 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.
|
||||
|
||||
@@ -160,14 +188,21 @@ func osNativeVerifyIndex(parent string) (*nativeVerifyIndex, error) {
|
||||
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 (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}
|
||||
}
|
||||
@@ -19,29 +19,37 @@ func readNativeAt(f storage.File, b []byte, offset int64) error {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -49,11 +57,13 @@ 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
|
||||
@@ -64,16 +74,20 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
|
||||
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 {
|
||||
@@ -85,6 +99,7 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
|
||||
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
|
||||
@@ -93,23 +108,29 @@ func (b *nativeTransport) copyRegular(ctx context.Context, job nativeJob) error
|
||||
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}))
|
||||
}
|
||||
|
||||
@@ -119,93 +140,115 @@ func (b *nativeTransport) copyFull(ctx context.Context, job nativeJob) (result e
|
||||
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
|
||||
@@ -213,24 +256,29 @@ func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks
|
||||
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))
|
||||
@@ -240,25 +288,32 @@ func (b *nativeTransport) copyBlocks(ctx context.Context, job nativeJob, blocks
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -266,14 +321,17 @@ 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()
|
||||
@@ -284,53 +342,64 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
|
||||
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
|
||||
@@ -341,35 +410,43 @@ func (b *nativeTransport) Verify(ctx context.Context, from, to string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -377,6 +454,7 @@ 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.
|
||||
@@ -385,29 +463,36 @@ func (b *nativeTransport) verifyInventory(ctx context.Context, to string) error
|
||||
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)
|
||||
@@ -415,18 +500,23 @@ func (b *nativeTransport) compareRange(ctx context.Context, from, to string, off
|
||||
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
|
||||
}
|
||||
@@ -13,15 +13,18 @@ func openNativeEngine(ctx context.Context, c Config, x Executor, log io.Writer)
|
||||
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
|
||||
}
|
||||
@@ -19,19 +19,24 @@ func walkNative(ctx context.Context, fs storage.FS, root string, visit func(stri
|
||||
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()
|
||||
@@ -41,24 +46,30 @@ func walkNative(ctx context.Context, fs storage.FS, root string, visit func(stri
|
||||
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
|
||||
@@ -66,13 +77,16 @@ func removeNative(ctx context.Context, fs storage.FS, p string) error {
|
||||
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 {
|
||||
@@ -86,78 +100,98 @@ func removeNative(ctx context.Context, fs storage.FS, p string) error {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -167,23 +201,28 @@ func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target sto
|
||||
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 {
|
||||
@@ -196,6 +235,7 @@ func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target sto
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for k, v := range attrs {
|
||||
if verify {
|
||||
if actual, ok := old[k]; !ok || !bytes.Equal(v, actual) {
|
||||
@@ -207,58 +247,72 @@ func syncNativeMetadataKnown(src, dst storage.FS, from, to string, n, target sto
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type nativeIndex struct {
|
||||
db *bolt.DB
|
||||
path string
|
||||
}
|
||||
|
||||
type baseEntry struct{ Inode, Version, Size, TargetInode uint64 }
|
||||
|
||||
func encodeEntry(e baseEntry) []byte {
|
||||
@@ -27,32 +28,39 @@ func encodeEntry(e baseEntry) []byte {
|
||||
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 {
|
||||
@@ -60,23 +68,29 @@ func createNativeIndex(parent string) (*nativeIndex, error) {
|
||||
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 {
|
||||
@@ -84,19 +98,24 @@ func (x *nativeIndex) get(bucket string, key []byte) ([]byte, error) {
|
||||
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
|
||||
}
|
||||
@@ -108,9 +127,11 @@ func (x *nativeIndex) containsPath(rel string) (bool, error) {
|
||||
if err != nil || b == nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if _, ok := decodeEntry(b); !ok {
|
||||
return false, errors.New("invalid source inventory entry")
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -119,9 +140,11 @@ func (x *nativeIndex) putEntryIfChanged(rel string, entry baseEntry) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ok && previous == entry {
|
||||
return nil
|
||||
}
|
||||
|
||||
return x.put("paths", []byte(rel), encodeEntry(entry))
|
||||
}
|
||||
|
||||
@@ -130,11 +153,14 @@ func (x *nativeIndex) requireInventory() error {
|
||||
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).
|
||||
@@ -143,6 +169,7 @@ func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byt
|
||||
if b == nil {
|
||||
return errors.New("missing native index bucket")
|
||||
}
|
||||
|
||||
c := b.Cursor()
|
||||
var k, v []byte
|
||||
if reverse {
|
||||
@@ -150,19 +177,23 @@ func (x *nativeIndex) each(bucket string, reverse bool, visit func([]byte, []byt
|
||||
} 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 {
|
||||
@@ -171,13 +202,16 @@ func (x *nativeIndex) ranges(rel string, visit func(uint64, uint64) error) error
|
||||
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)
|
||||
@@ -186,44 +220,54 @@ func (x *nativeIndex) extent(rel string, off, length uint64) error {
|
||||
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
|
||||
}
|
||||
@@ -31,13 +31,16 @@ func (f inventoryTargetFS) Stat(p string) (storage.Node, error) {
|
||||
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) }
|
||||
|
||||
@@ -52,11 +55,14 @@ func (d *inventoryDir) Next() (*storage.Entry, error) {
|
||||
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) {
|
||||
@@ -64,6 +70,7 @@ func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
root, outside := t.TempDir(), t.TempDir()
|
||||
for _, dir := range []string{"dir", "obsolete"} {
|
||||
@@ -71,59 +78,75 @@ func TestNativeInventoryPruneAndVerifyWithoutSourceLookups(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
@@ -135,23 +158,29 @@ func TestNativeInventoryRejectsCorruptionAndUnchangedIndexIsReadOnly(t *testing.
|
||||
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")
|
||||
|
||||
@@ -49,25 +49,31 @@ func TestNativeBaseTrust(t *testing.T) {
|
||||
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 {
|
||||
@@ -83,6 +89,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer x.close()
|
||||
for _, e := range []struct {
|
||||
name string
|
||||
@@ -94,6 +101,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
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})
|
||||
@@ -101,6 +109,7 @@ func TestNativeExtentIsolation(t *testing.T) {
|
||||
}); 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)
|
||||
@@ -114,26 +123,40 @@ type attrsTestFS struct {
|
||||
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) 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 (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)}
|
||||
@@ -142,18 +165,23 @@ func TestNativeMetadataEmptyXattrAndDeletion(t *testing.T) {
|
||||
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")
|
||||
@@ -167,14 +195,17 @@ func TestNativeCancellationAndPaths(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
@@ -187,16 +218,20 @@ func TestNativeMetadataOnlyWritesChangedAttributes(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
@@ -208,6 +243,7 @@ func TestNativeVerifyCommittedRound(t *testing.T) {
|
||||
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{}}
|
||||
@@ -215,17 +251,22 @@ func TestNativeVerifyCommittedRound(t *testing.T) {
|
||||
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 {
|
||||
|
||||
@@ -23,19 +23,24 @@ 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
|
||||
source, target storage.FS
|
||||
config Config
|
||||
log io.Writer
|
||||
identity string
|
||||
|
||||
// State of the current round.
|
||||
round Round
|
||||
workspace string
|
||||
pending, base *nativeIndex
|
||||
delta bool
|
||||
snapRoot, snapRel string
|
||||
verified map[string]bool
|
||||
started time.Time
|
||||
|
||||
// Counters reported by Statistics and used for rate limiting.
|
||||
visited, copied, written atomic.Int64
|
||||
checked, blockFiles atomic.Int64
|
||||
diffEntries, rateBytes atomic.Int64
|
||||
}
|
||||
|
||||
func (b *nativeTransport) Close() error {
|
||||
@@ -43,50 +48,62 @@ func (b *nativeTransport) Close() 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)
|
||||
@@ -102,11 +119,13 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
|
||||
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 {
|
||||
@@ -122,29 +141,36 @@ func (b *nativeTransport) BeginRound(ctx context.Context, r Round) error {
|
||||
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
|
||||
@@ -152,11 +178,13 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
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
|
||||
@@ -164,9 +192,11 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
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)
|
||||
@@ -176,6 +206,7 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
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
|
||||
@@ -187,16 +218,20 @@ func (b *nativeTransport) collectChanges(ctx context.Context, rel, current strin
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -210,12 +245,14 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) 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
|
||||
@@ -229,11 +266,13 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
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)
|
||||
@@ -241,10 +280,12 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
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.
|
||||
@@ -253,6 +294,7 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
})); 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 {
|
||||
@@ -260,106 +302,134 @@ func (b *nativeTransport) Copy(ctx context.Context, from, to string) error {
|
||||
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 {
|
||||
@@ -368,6 +438,7 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate canonical special inodes so previously linked, now independent
|
||||
// source entries cannot remain accidentally linked at the target.
|
||||
if exists {
|
||||
@@ -375,6 +446,7 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if n.Kind() == storage.Symlink {
|
||||
err = b.target.Symlink(text, dst)
|
||||
} else {
|
||||
@@ -383,51 +455,66 @@ func (b *nativeTransport) copySpecial(ctx context.Context, rel string, n storage
|
||||
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 := ""
|
||||
@@ -435,27 +522,37 @@ func (b *nativeTransport) Statistics() TransferStats {
|
||||
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 }
|
||||
|
||||
func nodeKey(ino uint64) [16]byte {
|
||||
var b [16]byte
|
||||
binary.BigEndian.PutUint64(b[:], ino)
|
||||
return b
|
||||
}
|
||||
@@ -46,9 +46,11 @@ func (b *tailBuffer) Write(p []byte) (int, error) {
|
||||
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
|
||||
}
|
||||
@@ -63,6 +65,7 @@ func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...s
|
||||
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 {
|
||||
@@ -70,16 +73,20 @@ func (p Process) Exec(ctx context.Context, out io.Writer, name string, args ...s
|
||||
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
|
||||
}
|
||||
|
||||
@@ -92,6 +99,7 @@ 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)
|
||||
}
|
||||
|
||||
@@ -100,5 +108,6 @@ func output(ctx context.Context, x Executor, name string, args ...string) ([]byt
|
||||
if err := x.Exec(ctx, b, name, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
@@ -28,9 +28,11 @@ 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+"/")
|
||||
}
|
||||
|
||||
@@ -47,16 +49,22 @@ func (r Rsync) Copy(ctx context.Context, src, dst string) error {
|
||||
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 (d *differences) Write(p []byte) (int, error) {
|
||||
d.n += int64(len(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Verify runs rsync as a dry run and fails if any difference remains.
|
||||
func (r Rsync) Verify(ctx context.Context, src, dst string) error {
|
||||
@@ -65,8 +73,10 @@ func (r Rsync) Verify(ctx context.Context, src, dst string) error {
|
||||
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
|
||||
}
|
||||
@@ -36,17 +36,21 @@ func TestRsyncRetriesOnlyObservedHardlinkEEXIST(t *testing.T) {
|
||||
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")
|
||||
@@ -59,79 +63,99 @@ 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.*"} {
|
||||
@@ -139,6 +163,7 @@ func TestRsyncUsesIncrementalSafeOptions(t *testing.T) {
|
||||
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)
|
||||
|
||||
@@ -49,6 +49,7 @@ func LoadState(path string) (*State, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
var s State
|
||||
d := json.NewDecoder(f)
|
||||
@@ -56,23 +57,29 @@ func LoadState(path string) (*State, error) {
|
||||
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 {
|
||||
@@ -81,26 +88,32 @@ func LoadState(path string) (*State, error) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -116,6 +129,7 @@ func atomicJSON(path string, v any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
name := f.Name()
|
||||
defer os.Remove(name)
|
||||
defer f.Close()
|
||||
@@ -124,19 +138,24 @@ func atomicJSON(path string, v any) error {
|
||||
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()
|
||||
}
|
||||
@@ -146,9 +165,11 @@ func lockFile(path string) (*os.File, error) {
|
||||
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
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
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()
|
||||
@@ -18,10 +19,12 @@ func TestStateAtomicAndPrivate(t *testing.T) {
|
||||
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() {
|
||||
@@ -33,20 +36,25 @@ func TestStateAtomicAndPrivate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
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++ },
|
||||
@@ -68,37 +76,45 @@ func TestStateRejectsCorruption(t *testing.T) {
|
||||
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()
|
||||
@@ -106,34 +122,42 @@ func TestTargetClaimExcludesOtherJobsAndSurvivesStateLoss(t *testing.T) {
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user