Skip to content

Commit 788e996

Browse files
authored
Merge pull request docker#5295 from laurazard/fix-context-cancel-attach
attach: don't return context cancelled error
2 parents 0cc1b8c + 66aa0f6 commit 788e996

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

cli/command/container/attach.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ func RunAttach(ctx context.Context, dockerCLI command.Cli, containerID string, o
145145
detachKeys: options.DetachKeys,
146146
}
147147

148-
if err := streamer.stream(ctx); err != nil {
148+
// if the context was canceled, this was likely intentional and we shouldn't return an error
149+
if err := streamer.stream(ctx); err != nil && !errors.Is(err, context.Canceled) {
149150
return err
150151
}
151152

@@ -162,6 +163,9 @@ func getExitStatus(errC <-chan error, resultC <-chan container.WaitResponse) err
162163
return cli.StatusError{StatusCode: int(result.StatusCode)}
163164
}
164165
case err := <-errC:
166+
if errors.Is(err, context.Canceled) {
167+
return nil
168+
}
165169
return err
166170
}
167171

cli/command/container/attach_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package container
22

33
import (
4+
"context"
45
"io"
56
"testing"
67

@@ -117,6 +118,10 @@ func TestGetExitStatus(t *testing.T) {
117118
},
118119
expectedError: cli.StatusError{StatusCode: 15},
119120
},
121+
{
122+
err: context.Canceled,
123+
expectedError: nil,
124+
},
120125
}
121126

122127
for _, testcase := range testcases {

e2e/container/attach_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
package container
22

33
import (
4+
"bytes"
45
"fmt"
6+
"os"
7+
"os/exec"
58
"strings"
69
"testing"
10+
"time"
711

12+
"github.com/creack/pty"
813
"github.com/docker/cli/e2e/internal/fixtures"
14+
"gotest.tools/v3/assert"
915
"gotest.tools/v3/icmd"
1016
)
1117

@@ -23,3 +29,26 @@ func TestAttachExitCode(t *testing.T) {
2329
func withStdinNewline(cmd *icmd.Cmd) {
2430
cmd.Stdin = strings.NewReader("\n")
2531
}
32+
33+
// Regression test for https://github.com/docker/cli/issues/5294
34+
func TestAttachInterrupt(t *testing.T) {
35+
result := icmd.RunCommand("docker", "run", "-d", fixtures.AlpineImage, "sh", "-c", "sleep 5")
36+
result.Assert(t, icmd.Success)
37+
containerID := strings.TrimSpace(result.Stdout())
38+
39+
// run it as such so we can signal it later
40+
c := exec.Command("docker", "attach", containerID)
41+
d := bytes.Buffer{}
42+
c.Stdout = &d
43+
c.Stderr = &d
44+
_, err := pty.Start(c)
45+
assert.NilError(t, err)
46+
47+
// have to wait a bit to give time for the command to execute/print
48+
time.Sleep(500 * time.Millisecond)
49+
c.Process.Signal(os.Interrupt)
50+
51+
_ = c.Wait()
52+
assert.Equal(t, c.ProcessState.ExitCode(), 0)
53+
assert.Equal(t, d.String(), "")
54+
}

0 commit comments

Comments
 (0)