Skip to content

Commit

Permalink
binaryfetcher: atomically rename binary file when fetch succeeds (#57)
Browse files Browse the repository at this point in the history
* binaryfetcher: atomically rename binary file when fetch succeeds

Otherwise an empty file will be created on errors like HTTP 403
and cached, which will prevent future VMs from running.

* Fix linter errors
  • Loading branch information
edigaryev authored Aug 16, 2024
1 parent dd024ba commit cdc6964
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
17 changes: 15 additions & 2 deletions internal/binaryfetcher/binaryfetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,36 @@ func GetOrFetch(ctx context.Context, fetchFunc FetchFunc, binaryName string, exe

// Run the user-provided function to fetch the binary file
// if not available in the cache
binaryFile, err := os.Create(binaryPath)
binaryFile, err := os.CreateTemp("", "vetu-binary-file-*")
if err != nil {
return "", err
}
defer binaryFile.Close()

if err := fetchFunc(ctx, binaryFile); err != nil {
_ = binaryFile.Close()
_ = os.Remove(binaryFile.Name())

return "", err
}

// Make the binary executable if requested
if executable {
if err := binaryFile.Chmod(0755); err != nil {
_ = binaryFile.Close()
_ = os.Remove(binaryFile.Name())

return "", err
}
}

if err := binaryFile.Close(); err != nil {
return "", err
}

if err := os.Rename(binaryFile.Name(), binaryPath); err != nil {
return "", err
}

return binaryPath, nil
}

Expand Down
2 changes: 1 addition & 1 deletion internal/filelock/filelock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestMain(m *testing.M) {
} else if lockPath, ok := os.LookupEnv(envTestHelperTrylockShared); ok {
testHelperTrylockShared(lockPath)
} else {
m.Run()
os.Exit(m.Run())
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/pidlock/pidlock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestMain(m *testing.M) {
} else if lockPath, ok := os.LookupEnv(envTestHelperPid); ok {
testHelperPid(lockPath)
} else {
m.Run()
os.Exit(m.Run())
}
}

Expand Down
1 change: 0 additions & 1 deletion internal/sparseio/sparseio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ func TestCopyRandomized(t *testing.T) {

// Randomize the contents of some chunks
if rand.Intn(2) == 1 {
//nolint:staticcheck // what's the alternative to the deprecated rand.Read() anyways?
_, err = rand.Read(chunk)
require.NoError(t, err)
}
Expand Down

0 comments on commit cdc6964

Please sign in to comment.