From 12d4ebab139887b0cb286986a581c9d41ced9fcb Mon Sep 17 00:00:00 2001 From: phuphung330 <58984921+phuphung330@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:20:36 +0700 Subject: [PATCH] fix: suggest recovery for Docker exec format errors --- apps/cli-go/internal/utils/docker.go | 56 +++++++++++++- apps/cli-go/internal/utils/docker_test.go | 91 +++++++++++++++++++++++ 2 files changed, 145 insertions(+), 2 deletions(-) diff --git a/apps/cli-go/internal/utils/docker.go b/apps/cli-go/internal/utils/docker.go index 29d2edd397..9172b60d94 100644 --- a/apps/cli-go/internal/utils/docker.go +++ b/apps/cli-go/internal/utils/docker.go @@ -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 @@ -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) + } + 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. diff --git a/apps/cli-go/internal/utils/docker_test.go b/apps/cli-go/internal/utils/docker_test.go index 5c58d5aea0..4465278e54 100644 --- a/apps/cli-go/internal/utils/docker_test.go +++ b/apps/cli-go/internal/utils/docker_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "net/http" + "strings" "testing" "time" @@ -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 @@ -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) + }) +}