-
Notifications
You must be signed in to change notification settings - Fork 203
Write to cache when building a template #1133
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
Open
djeebus
wants to merge
8
commits into
main
Choose a base branch
from
bring-back-cache-writes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9492123
progress
djeebus 1a615fd
more progress
djeebus 3b7c715
add tests around the atomic file
djeebus 77192cf
enable caching in the template builder
djeebus 5b7e84c
Merge branch 'main' into bring-back-cache-writes
djeebus 1a2b56c
Merge branch 'main' into bring-back-cache-writes
djeebus f9ca649
Merge remote-tracking branch 'origin/main' into bring-back-cache-writes
djeebus 83bcfe4
remove race condition
djeebus 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,98 @@ | ||
| package lock | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "sync" | ||
|
|
||
| "github.com/google/uuid" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| type AtomicFile struct { | ||
| lockFile *os.File | ||
| tempFile *os.File | ||
| filename string | ||
|
|
||
| closeOnce sync.Once | ||
| } | ||
|
|
||
| func (f *AtomicFile) Write(p []byte) (n int, err error) { | ||
| return f.tempFile.Write(p) | ||
| } | ||
|
|
||
| var _ io.Writer = (*AtomicFile)(nil) | ||
|
|
||
| func OpenFile(filename string) (*AtomicFile, error) { | ||
| lockFile, err := TryAcquireLock(filename) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| tempFilename := fmt.Sprintf("%s.temp.%s", filename, uuid.NewString()) | ||
| tempFile, err := os.OpenFile(tempFilename, os.O_WRONLY|os.O_CREATE, 0o600) | ||
| if err != nil { | ||
| cleanup("failed to close lock file", lockFile.Close) | ||
|
|
||
| return nil, fmt.Errorf("failed to open temp file: %w", err) | ||
| } | ||
|
|
||
| return &AtomicFile{ | ||
| lockFile: lockFile, | ||
| tempFile: tempFile, | ||
| filename: filename, | ||
| }, nil | ||
| } | ||
|
|
||
| func (f *AtomicFile) Close() error { | ||
| var err error | ||
|
|
||
| f.closeOnce.Do(func() { | ||
| defer cleanup("failed to unlock file", func() error { | ||
| return ReleaseLock(f.lockFile) | ||
| }) | ||
|
|
||
| if err = f.tempFile.Close(); err != nil { | ||
| err = fmt.Errorf("failed to close temp file: %w", err) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| if err = moveWithoutReplace(f.tempFile.Name(), f.filename); err != nil { | ||
| err = fmt.Errorf("failed to commit file: %w", err) | ||
|
|
||
| return | ||
| } | ||
| }) | ||
|
|
||
| return err | ||
| } | ||
|
|
||
| func cleanup(msg string, fn func() error) { | ||
| if err := fn(); err != nil { | ||
| zap.L().Warn(msg, zap.Error(err)) | ||
| } | ||
| } | ||
|
|
||
| // moveWithoutReplace tries to rename a file but will not replace the target if it already exists. | ||
| // If the file already exists, the file will be deleted. | ||
| func moveWithoutReplace(oldPath, newPath string) error { | ||
| defer func() { | ||
| if err := os.Remove(oldPath); err != nil { | ||
| zap.L().Warn("failed to remove existing file", zap.Error(err)) | ||
| } | ||
| }() | ||
|
|
||
| if err := os.Link(oldPath, newPath); err != nil { | ||
| if errors.Is(err, os.ErrExist) { | ||
| // Someone else created newPath first. Treat as success. | ||
| return nil | ||
| } | ||
|
|
||
| return err | ||
| } | ||
|
|
||
| return 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,74 @@ | ||
| package lock | ||
|
|
||
| import ( | ||
| "io/fs" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestOpenFile(t *testing.T) { | ||
| t.Run("happy path", func(t *testing.T) { | ||
| expected := []byte("hello") | ||
|
|
||
| tempDir := t.TempDir() | ||
| filename := filepath.Join(tempDir, "test.bin") | ||
|
|
||
| f, err := OpenFile(filename) | ||
| require.NoError(t, err) | ||
| require.NotNil(t, f) | ||
|
|
||
| count, err := f.Write(expected) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, len(expected), count) | ||
|
|
||
| _, err = os.Stat("test.bin") | ||
| require.Error(t, err) | ||
| assert.True(t, os.IsNotExist(err)) | ||
|
|
||
| err = f.Close() | ||
| require.NoError(t, err) | ||
|
|
||
| data, err := os.ReadFile(filename) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, expected, data) | ||
| }) | ||
|
|
||
| t.Run("two files cannot be opened at the same time", func(t *testing.T) { | ||
| tempDir := t.TempDir() | ||
| filename := filepath.Join(tempDir, "test.bin") | ||
|
|
||
| f1, err := OpenFile(filename) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { | ||
| err := f1.Close() | ||
| assert.NoError(t, err) | ||
| }) | ||
|
|
||
| f2, err := OpenFile(filename) | ||
| require.ErrorIs(t, err, ErrLockAlreadyHeld) | ||
| assert.Nil(t, f2) | ||
|
|
||
| err = f1.Close() | ||
| require.NoError(t, err) | ||
|
|
||
| f2, err = OpenFile(filename) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { | ||
| err := f2.Close() | ||
| assert.NoError(t, err) | ||
| }) | ||
| }) | ||
|
|
||
| t.Run("missing directory returns error", func(t *testing.T) { | ||
| tempDir := t.TempDir() | ||
| filename := filepath.Join(tempDir, "a", "b", "test.bin") | ||
|
|
||
| _, err := OpenFile(filename) | ||
| require.Error(t, err) | ||
| assert.ErrorIs(t, err, fs.ErrNotExist) | ||
| }) | ||
| } |
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,58 @@ | ||
| package storage | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "go.opentelemetry.io/otel/attribute" | ||
| "go.opentelemetry.io/otel/metric" | ||
|
|
||
| "github.com/e2b-dev/infra/packages/shared/pkg/utils" | ||
| ) | ||
|
|
||
| var ( | ||
| cacheOpCounter = utils.Must(meter.Int64Counter("orchestrator.storage.cache.ops", | ||
| metric.WithDescription("total cache operations"))) | ||
| cacheBytesCounter = utils.Must(meter.Int64Counter("orchestrator.storage.cache.bytes", | ||
| metric.WithDescription("total cache bytes processed"), | ||
| metric.WithUnit("byte"))) | ||
| ) | ||
|
|
||
| type cacheOp string | ||
|
|
||
| const ( | ||
| cacheOpWriteTo cacheOp = "write_to" | ||
| cacheOpReadAt cacheOp = "read_at" | ||
| cacheOpSize cacheOp = "size" | ||
|
|
||
| cacheOpWrite cacheOp = "write" | ||
| cacheOpWriteFromFileSystem cacheOp = "write_from_filesystem" | ||
| ) | ||
|
|
||
| func recordCacheRead(ctx context.Context, isHit bool, bytesRead int64, op cacheOp) { | ||
| cacheOpCounter.Add(ctx, 1, metric.WithAttributes( | ||
| attribute.Bool("cache_hit", isHit), | ||
| attribute.String("operation", string(op)), | ||
| )) | ||
|
|
||
| cacheBytesCounter.Add(ctx, bytesRead, metric.WithAttributes( | ||
| attribute.Bool("cache_hit", isHit), | ||
| attribute.String("operation", string(op)), | ||
| )) | ||
| } | ||
|
|
||
| func recordCacheWrite(ctx context.Context, bytesWritten int64, op cacheOp) { | ||
| cacheOpCounter.Add(ctx, 1, metric.WithAttributes( | ||
| attribute.String("operation", string(op)), | ||
| )) | ||
|
|
||
| cacheBytesCounter.Add(ctx, bytesWritten, metric.WithAttributes( | ||
| attribute.String("operation", string(op)), | ||
| )) | ||
| } | ||
|
|
||
| func recordCacheError[T ~string](ctx context.Context, op T, err error) { | ||
| cacheOpCounter.Add(ctx, 1, metric.WithAttributes( | ||
| attribute.String("error", err.Error()), | ||
| attribute.String("operation", string(op)), | ||
| )) | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: NFS cache wrapping not applied to storage operations
The
templateStoragevariable is wrapped withNewCachedProviderat lines 229-231 to enable NFS caching, but the unwrappedbuilder.templateStorageis then passed tolayerExecutor(line 241),baseBuilder(line 251), andpostProcessingBuilder(line 293). Additionally, the unwrappedbuilder.templateStorageis used at line 327 forgetRootfsSize. This means the cache wrapping is never actually used for any storage operations, defeating the entire purpose of the caching feature introduced in this PR.