-
Notifications
You must be signed in to change notification settings - Fork 3
Enforce sparse-only guest directory copy #123
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sjmiller609
merged 2 commits into
main
from
codex/hypeman-fork-performance-via-sparse-copy
Mar 7, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| //go:build darwin || linux | ||
|
|
||
| package forkvm | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "io/fs" | ||
| "os" | ||
|
|
||
| "golang.org/x/sys/unix" | ||
| ) | ||
|
|
||
| var ( | ||
| seekDataFn = func(fd int, offset int64) (int64, error) { | ||
| return unix.Seek(fd, offset, unix.SEEK_DATA) | ||
| } | ||
| seekHoleFn = func(fd int, offset int64) (int64, error) { | ||
| return unix.Seek(fd, offset, unix.SEEK_HOLE) | ||
| } | ||
| ) | ||
|
|
||
| func copyRegularFileSparse(srcPath, dstPath string, perms fs.FileMode) (retErr error) { | ||
| src, err := os.Open(srcPath) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer src.Close() | ||
|
|
||
| info, err := src.Stat() | ||
| if err != nil { | ||
| return fmt.Errorf("stat source file: %w", err) | ||
| } | ||
|
|
||
| dst, err := os.OpenFile(dstPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, perms) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer func() { | ||
| if cerr := dst.Close(); retErr == nil && cerr != nil { | ||
| retErr = cerr | ||
| } | ||
| }() | ||
|
|
||
| size := info.Size() | ||
| if err := unix.Ftruncate(int(dst.Fd()), size); err != nil { | ||
| return fmt.Errorf("truncate destination file: %w", err) | ||
| } | ||
| if size == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| srcFD := int(src.Fd()) | ||
| dstFD := int(dst.Fd()) | ||
| offset := int64(0) | ||
|
|
||
| for offset < size { | ||
| dataStart, err := seekDataFn(srcFD, offset) | ||
| if err != nil { | ||
| if errors.Is(err, unix.ENXIO) { | ||
| break | ||
| } | ||
| if isSparseUnsupportedError(err) { | ||
| return fmt.Errorf("%w: SEEK_DATA unsupported for %s: %v", ErrSparseCopyUnsupported, srcPath, err) | ||
| } | ||
| return fmt.Errorf("seek data at offset %d: %w", offset, err) | ||
| } | ||
| if dataStart >= size { | ||
| break | ||
| } | ||
|
|
||
| dataEnd, err := seekHoleFn(srcFD, dataStart) | ||
| if err != nil { | ||
| if errors.Is(err, unix.ENXIO) { | ||
| dataEnd = size | ||
| } else if isSparseUnsupportedError(err) { | ||
| return fmt.Errorf("%w: SEEK_HOLE unsupported for %s: %v", ErrSparseCopyUnsupported, srcPath, err) | ||
| } else { | ||
| return fmt.Errorf("seek hole at offset %d: %w", dataStart, err) | ||
| } | ||
| } | ||
|
|
||
| if dataEnd > size { | ||
| dataEnd = size | ||
| } | ||
| if dataEnd < dataStart { | ||
| return fmt.Errorf("invalid sparse extent (%d..%d) for %s", dataStart, dataEnd, srcPath) | ||
| } | ||
|
|
||
| length := dataEnd - dataStart | ||
| if length > 0 { | ||
| if err := copyFileExtent(srcFD, dstFD, dataStart, length); err != nil { | ||
| return fmt.Errorf("copy sparse extent [%d,%d): %w", dataStart, dataEnd, err) | ||
| } | ||
| } | ||
| offset = dataEnd | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func copyFileExtent(srcFD, dstFD int, offset, length int64) error { | ||
| const chunkSize = 1 << 20 // 1 MiB | ||
| buf := make([]byte, chunkSize) | ||
|
|
||
| pos := offset | ||
| remaining := length | ||
| for remaining > 0 { | ||
| toRead := int64(len(buf)) | ||
| if remaining < toRead { | ||
| toRead = remaining | ||
| } | ||
|
|
||
| n, err := unix.Pread(srcFD, buf[:int(toRead)], pos) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if n == 0 { | ||
| return io.ErrUnexpectedEOF | ||
| } | ||
|
|
||
| written := 0 | ||
| for written < n { | ||
| wn, werr := unix.Pwrite(dstFD, buf[written:n], pos+int64(written)) | ||
| if werr != nil { | ||
| return werr | ||
| } | ||
| if wn == 0 { | ||
| return io.ErrShortWrite | ||
| } | ||
| written += wn | ||
| } | ||
|
|
||
| pos += int64(n) | ||
| remaining -= int64(n) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func isSparseUnsupportedError(err error) bool { | ||
| return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) || errors.Is(err, unix.EOPNOTSUPP) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| //go:build darwin || linux | ||
|
|
||
| package forkvm | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "net" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "golang.org/x/sys/unix" | ||
| ) | ||
|
|
||
| func TestCopyGuestDirectory_PreservesSparseFiles(t *testing.T) { | ||
| src := filepath.Join(t.TempDir(), "src") | ||
| dst := filepath.Join(t.TempDir(), "dst") | ||
| require.NoError(t, os.MkdirAll(src, 0755)) | ||
|
|
||
| srcOverlay := filepath.Join(src, "overlay.raw") | ||
| const logicalSize = 256 * 1024 * 1024 // 256 MiB logical, tiny physical | ||
| require.NoError(t, writeSparseFile(srcOverlay, logicalSize)) | ||
|
|
||
| require.NoError(t, CopyGuestDirectory(src, dst)) | ||
|
|
||
| dstOverlay := filepath.Join(dst, "overlay.raw") | ||
| srcInfo, err := os.Stat(srcOverlay) | ||
| require.NoError(t, err) | ||
| dstInfo, err := os.Stat(dstOverlay) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, srcInfo.Size(), dstInfo.Size(), "logical size must match") | ||
|
|
||
| srcAllocated, err := allocatedBytes(srcOverlay) | ||
| require.NoError(t, err) | ||
| dstAllocated, err := allocatedBytes(dstOverlay) | ||
| require.NoError(t, err) | ||
|
|
||
| // Guard against dense copy inflation. | ||
| assert.Less(t, dstAllocated, int64(logicalSize/10), "destination should remain sparse") | ||
| // Allow modest filesystem allocation variance while preserving sparsity. | ||
| assert.LessOrEqual(t, dstAllocated, srcAllocated+8*1024*1024) | ||
| } | ||
|
|
||
| func TestCopyGuestDirectory_FailsWhenSparseSeekingUnsupported(t *testing.T) { | ||
| src := filepath.Join(t.TempDir(), "src") | ||
| dst := filepath.Join(t.TempDir(), "dst") | ||
| require.NoError(t, os.MkdirAll(src, 0755)) | ||
| require.NoError(t, os.WriteFile(filepath.Join(src, "metadata.json"), []byte(`{"id":"abc"}`), 0644)) | ||
|
|
||
| origSeekData := seekDataFn | ||
| origSeekHole := seekHoleFn | ||
| seekDataFn = func(fd int, offset int64) (int64, error) { | ||
| return 0, unix.EINVAL | ||
| } | ||
| seekHoleFn = func(fd int, offset int64) (int64, error) { | ||
| return 0, unix.EINVAL | ||
| } | ||
| defer func() { | ||
| seekDataFn = origSeekData | ||
| seekHoleFn = origSeekHole | ||
| }() | ||
|
|
||
| err := CopyGuestDirectory(src, dst) | ||
| require.Error(t, err) | ||
| assert.True(t, errors.Is(err, ErrSparseCopyUnsupported), "error should indicate sparse support is required") | ||
| } | ||
|
|
||
| func TestCopyGuestDirectory_SkipsSocketRuntimeArtifacts(t *testing.T) { | ||
| base, err := os.MkdirTemp("/tmp", "forkvm-*") | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { _ = os.RemoveAll(base) }) | ||
|
|
||
| src := filepath.Join(base, "src") | ||
| dst := filepath.Join(base, "dst") | ||
| require.NoError(t, os.MkdirAll(src, 0755)) | ||
| require.NoError(t, os.WriteFile(filepath.Join(src, "metadata.json"), []byte(`{"id":"abc"}`), 0644)) | ||
|
|
||
| socketPath := filepath.Join(src, fmt.Sprintf("vz-%d.sock", time.Now().UnixNano())) | ||
| listener, err := net.Listen("unix", socketPath) | ||
| require.NoError(t, err) | ||
| defer func() { _ = listener.Close() }() | ||
|
|
||
| require.NoError(t, CopyGuestDirectory(src, dst)) | ||
|
|
||
| assert.NoFileExists(t, filepath.Join(dst, filepath.Base(socketPath))) | ||
| assert.FileExists(t, filepath.Join(dst, "metadata.json")) | ||
| } | ||
|
|
||
| func writeSparseFile(path string, logicalSize int64) error { | ||
| f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer f.Close() | ||
|
|
||
| if _, err := f.WriteAt([]byte("begin"), 0); err != nil { | ||
| return err | ||
| } | ||
| if _, err := f.WriteAt([]byte("middle"), logicalSize/2); err != nil { | ||
| return err | ||
| } | ||
| if _, err := f.WriteAt([]byte("end"), logicalSize-4); err != nil { | ||
| return err | ||
| } | ||
| return f.Truncate(logicalSize) | ||
| } | ||
|
|
||
| func allocatedBytes(path string) (int64, error) { | ||
| var st unix.Stat_t | ||
| if err := unix.Stat(path, &st); err != nil { | ||
| return 0, err | ||
| } | ||
| return st.Blocks * 512, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| //go:build !darwin && !linux | ||
|
|
||
| package forkvm | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "io/fs" | ||
| ) | ||
|
|
||
| func copyRegularFileSparse(srcPath, dstPath string, perms fs.FileMode) error { | ||
| _ = dstPath | ||
| _ = perms | ||
| return fmt.Errorf("%w: unsupported platform for sparse copy: %s", ErrSparseCopyUnsupported, srcPath) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.