Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix: use concurrency-safe bytes buffer to avoid race #15142

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
merged 2 commits into from
Oct 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 34 additions & 9 deletions provisionersdk/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package provisionersdk_test

import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -47,12 +46,10 @@ func TestAgentScript(t *testing.T) {
t.Run("Valid", func(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitShort)
script := serveScript(t, bashEcho)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
t.Cleanup(cancel)

var output bytes.Buffer
var output safeBuffer
// This is intentionally ran in single quotes to mimic how a customer may
// embed our script. Our scripts should not include any single quotes.
// nolint:gosec
Expand Down Expand Up @@ -84,12 +81,10 @@ func TestAgentScript(t *testing.T) {
t.Run("Invalid", func(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitShort)
script := serveScript(t, unexpectedEcho)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
t.Cleanup(cancel)

var output bytes.Buffer
var output safeBuffer
// This is intentionally ran in single quotes to mimic how a customer may
// embed our script. Our scripts should not include any single quotes.
// nolint:gosec
Expand Down Expand Up @@ -159,3 +154,33 @@ func serveScript(t *testing.T, in string) string {
script = strings.ReplaceAll(script, "${AUTH_TYPE}", "token")
return script
}

// safeBuffer is a concurrency-safe bytes.Buffer
type safeBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}

func (sb *safeBuffer) Write(p []byte) (n int, err error) {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Write(p)
}

func (sb *safeBuffer) Read(p []byte) (n int, err error) {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Read(p)
}

func (sb *safeBuffer) Bytes() []byte {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Bytes()
}

func (sb *safeBuffer) String() string {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.String()
}
Loading