Skip to content
Closed
Show file tree
Hide file tree
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
56 changes: 54 additions & 2 deletions apps/cli-go/internal/utils/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ func CliProjectFilter(projectId string) filters.Args {
}

var (
registryAuth sync.Map
registryAuth sync.Map
dockerSuggestion sync.Mutex
)

// registryAuthEntry memoises a single registry's encoded auth so that
Expand Down Expand Up @@ -454,8 +455,59 @@ type DockerJob struct {
Cmd []string
}

const dockerDiagnosticLogLimit = 64 << 10

type boundedLogBuffer struct {
bytes.Buffer
}

func (b *boundedLogBuffer) Write(p []byte) (int, error) {
written := len(p)
if written >= dockerDiagnosticLogLimit {
b.Reset()
_, _ = b.Buffer.Write(p[written-dockerDiagnosticLogLimit:])
return written, nil
}
if overflow := b.Len() + written - dockerDiagnosticLogLimit; overflow > 0 {
b.Next(overflow)
}
_, _ = b.Buffer.Write(p)
return written, nil
}

func DockerRunJob(ctx context.Context, job DockerJob, stdout, stderr io.Writer) error {
return DockerRunOnceWithStream(ctx, job.Image, job.Env, job.Cmd, stdout, stderr)
var stdoutLogs, stderrLogs boundedLogBuffer
err := DockerRunOnceWithStream(ctx, job.Image, job.Env, job.Cmd, io.MultiWriter(stdout, &stdoutLogs), io.MultiWriter(stderr, &stderrLogs))
if err != nil {
SuggestDockerExecFormat(stdoutLogs.String()+stderrLogs.String(), job.Image)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the resolved Docker image in the recovery hint

When no INTERNAL_IMAGE_REGISTRY override is set, DockerStart resolves job.Image to the actual cached/pulled image URL (defaulting to public.ecr.aws, then ghcr.io, then Docker Hub) before creating the container, but this hint passes the original job image. If a normal supabase start init job fails with exec format error, the user is told to remove supabase/..., which does not remove the corrupted public.ecr.aws/... or ghcr.io/... image that was actually started, so retrying can keep using the bad image and the suggested recovery does not work.

Useful? React with 👍 / 👎.

}
return err
}

// SuggestDockerExecFormat adds an actionable hint when Docker reports that an
// image entrypoint or shell cannot be executed. This commonly means the pulled
// image has corrupt/truncated files or targets the wrong architecture; retrying
// the same start command otherwise only surfaces a generic container exit code.
func SuggestDockerExecFormat(logs, image string) bool {
if !strings.Contains(strings.ToLower(logs), "exec format error") {
return false
}
suggestion := "A Docker image entrypoint could not be executed. Check free disk space and image architecture"
if image != "" {
suggestion += fmt.Sprintf(", then remove image %q and retry so Docker pulls a fresh copy", image)
} else {
suggestion += ", then remove and pull the affected image again"
}
suggestion += ". If multiple images fail, restart Docker before retrying."
dockerSuggestion.Lock()
defer dockerSuggestion.Unlock()
if !strings.Contains(CmdSuggestion, suggestion) {
if CmdSuggestion != "" {
CmdSuggestion += "\n"
}
CmdSuggestion += suggestion
}
return true
}

// Runs a container image exactly once, returning stdout and throwing error on non-zero exit code.
Expand Down
91 changes: 91 additions & 0 deletions apps/cli-go/internal/utils/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"net/http"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -352,6 +353,59 @@ func TestRunOnce(t *testing.T) {
})
}

func TestDockerRunJobSuggestsCorruptImageRecovery(t *testing.T) {
viper.Set("INTERNAL_IMAGE_REGISTRY", "docker.io")
require.NoError(t, apitest.MockDocker(Docker))
defer gock.OffAll()
apitest.MockDockerStart(Docker, imageId, containerId)
var body bytes.Buffer
writer := stdcopy.NewStdWriter(&body, stdcopy.Stderr)
_, err := writer.Write([]byte("exec /usr/bin/sh: exec format error"))
require.NoError(t, err)
gock.New("http:///var/run/docker.sock").
Get("/v"+Docker.ClientVersion()+"/containers/"+containerId+"/logs").
Reply(http.StatusOK).
SetHeader("Content-Type", "application/vnd.docker.raw-stream").
Body(&body)
gock.New("http:///var/run/docker.sock").
Get("/v" + Docker.ClientVersion() + "/containers/" + containerId + "/json").
Reply(http.StatusOK).
JSON(container.InspectResponse{ContainerJSONBase: &container.ContainerJSONBase{
State: &container.State{ExitCode: 1},
}})
gock.New(Docker.DaemonHost()).
Delete("/v" + Docker.ClientVersion() + "/containers/" + containerId).
Reply(http.StatusOK)
original := CmdSuggestion
t.Cleanup(func() { CmdSuggestion = original })
CmdSuggestion = ""
var stderr bytes.Buffer

err = DockerRunJob(context.Background(), DockerJob{Image: imageId}, &bytes.Buffer{}, &stderr)

assert.ErrorContains(t, err, "error running container: exit 1")
assert.Contains(t, stderr.String(), "exec format error")
assert.Contains(t, CmdSuggestion, `remove image "`+imageId+`"`)
assert.Empty(t, apitest.ListUnmatchedRequests())
}

func TestDockerRunJobIgnoresSuccessfulMarker(t *testing.T) {
viper.Set("INTERNAL_IMAGE_REGISTRY", "docker.io")
require.NoError(t, apitest.MockDocker(Docker))
defer gock.OffAll()
apitest.MockDockerStart(Docker, imageId, containerId)
require.NoError(t, apitest.MockDockerLogs(Docker, containerId, "exec format error"))
original := CmdSuggestion
t.Cleanup(func() { CmdSuggestion = original })
CmdSuggestion = "existing suggestion"

err := DockerRunJob(context.Background(), DockerJob{Image: imageId}, &bytes.Buffer{}, &bytes.Buffer{})

assert.NoError(t, err)
assert.Equal(t, "existing suggestion", CmdSuggestion)
assert.Empty(t, apitest.ListUnmatchedRequests())
}

func TestExecOnce(t *testing.T) {
t.Run("throws error on failure to exec", func(t *testing.T) {
// Setup mock server
Expand Down Expand Up @@ -384,3 +438,40 @@ func TestExecOnce(t *testing.T) {

// TODO: mock tcp hijack
}

func TestBoundedLogBufferKeepsTail(t *testing.T) {
var logs boundedLogBuffer
_, err := logs.Write(bytes.Repeat([]byte("a"), dockerDiagnosticLogLimit))
require.NoError(t, err)
_, err = logs.Write([]byte("exec for"))
require.NoError(t, err)
_, err = logs.Write([]byte("mat error"))
require.NoError(t, err)

assert.Equal(t, dockerDiagnosticLogLimit, logs.Len())
assert.NotContains(t, logs.String(), strings.Repeat("a", dockerDiagnosticLogLimit))
assert.True(t, strings.HasSuffix(logs.String(), "exec format error"))
}

func TestSuggestDockerExecFormat(t *testing.T) {
t.Run("sets actionable suggestion", func(t *testing.T) {
original := CmdSuggestion
t.Cleanup(func() { CmdSuggestion = original })
CmdSuggestion = "existing suggestion"

assert.True(t, SuggestDockerExecFormat("exec /usr/bin/sh: exec format error", "test-image"))
assert.True(t, strings.HasPrefix(CmdSuggestion, "existing suggestion\n"))
assert.Contains(t, CmdSuggestion, `remove image "test-image"`)
assert.True(t, SuggestDockerExecFormat("exec format error", "test-image"))
assert.Equal(t, 1, strings.Count(CmdSuggestion, `remove image "test-image"`))
})

t.Run("ignores unrelated logs", func(t *testing.T) {
original := CmdSuggestion
t.Cleanup(func() { CmdSuggestion = original })
CmdSuggestion = "existing suggestion"

assert.False(t, SuggestDockerExecFormat("connection refused", "test-image"))
assert.Equal(t, "existing suggestion", CmdSuggestion)
})
}
Loading