diff --git a/cmd/docker/docker.go b/cmd/docker/docker.go index 29a3ed595755..ead393b7c51d 100644 --- a/cmd/docker/docker.go +++ b/cmd/docker/docker.go @@ -28,16 +28,43 @@ import ( "go.opentelemetry.io/otel" ) +var errCtxUserTerminated = errors.New("user terminated the process") + func main() { - err := dockerMain(context.Background()) - if err != nil && !errdefs.IsCancelled(err) { + ctx := context.Background() + err := dockerMain(ctx) + if err != nil && !errdefs.IsCancelled(err) && !errors.Is(err, errCtxUserTerminated) { _, _ = fmt.Fprintln(os.Stderr, err) os.Exit(getExitCode(err)) } } +func notifyContext(ctx context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) { + ch := make(chan os.Signal, 1) + signal.Notify(ch, signals...) + + ctxCause, cancel := context.WithCancelCause(ctx) + + go func() { + select { + case <-ctx.Done(): + signal.Stop(ch) + return + case <-ch: + cancel(errCtxUserTerminated) + signal.Stop(ch) + return + } + }() + + return ctxCause, func() { + signal.Stop(ch) + cancel(nil) + } +} + func dockerMain(ctx context.Context) error { - ctx, cancelNotify := signal.NotifyContext(ctx, platformsignals.TerminationSignals...) + ctx, cancelNotify := notifyContext(ctx, platformsignals.TerminationSignals...) defer cancelNotify() dockerCli, err := command.NewDockerCli(command.WithBaseContext(ctx)) diff --git a/cmd/docker/docker_test.go b/cmd/docker/docker_test.go index 1998b77c9904..9c7eb766d537 100644 --- a/cmd/docker/docker_test.go +++ b/cmd/docker/docker_test.go @@ -5,10 +5,14 @@ import ( "context" "io" "os" + "syscall" "testing" + "time" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/debug" + platformsignals "github.com/docker/cli/cmd/docker/internal/signals" + "github.com/pkg/errors" "github.com/sirupsen/logrus" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" @@ -75,3 +79,16 @@ func TestVersion(t *testing.T) { assert.NilError(t, err) assert.Check(t, is.Contains(b.String(), "Docker version")) } + +func TestUserTerminatedError(t *testing.T) { + ctx, cancel := context.WithTimeoutCause(context.Background(), time.Second*1, errors.New("test timeout")) + t.Cleanup(cancel) + + notifyCtx, cancelNotify := notifyContext(ctx, platformsignals.TerminationSignals...) + t.Cleanup(cancelNotify) + + syscall.Kill(syscall.Getpid(), syscall.SIGINT) + + <-notifyCtx.Done() + assert.ErrorIs(t, context.Cause(notifyCtx), errCtxUserTerminated) +}