Skip to content

Commit 5f22178

Browse files
committed
feat: cause on user-terminated context
Signed-off-by: Alano Terblanche <[email protected]>
1 parent e7078bf commit 5f22178

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

cmd/docker/docker.go

+30-3
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,43 @@ import (
2828
"go.opentelemetry.io/otel"
2929
)
3030

31+
var errCtxUserTerminated = errors.New("user terminated the process")
32+
3133
func main() {
32-
err := dockerMain(context.Background())
33-
if err != nil && !errdefs.IsCancelled(err) {
34+
ctx := context.Background()
35+
err := dockerMain(ctx)
36+
if err != nil && !errdefs.IsCancelled(err) && !errors.Is(err, errCtxUserTerminated) {
3437
_, _ = fmt.Fprintln(os.Stderr, err)
3538
os.Exit(getExitCode(err))
3639
}
3740
}
3841

42+
func notifyContext(ctx context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) {
43+
ch := make(chan os.Signal, 1)
44+
signal.Notify(ch, signals...)
45+
46+
ctx, cancel := context.WithCancelCause(ctx)
47+
48+
go func() {
49+
select {
50+
case <-ctx.Done():
51+
signal.Stop(ch)
52+
return
53+
case <-ch:
54+
cancel(errCtxUserTerminated)
55+
signal.Stop(ch)
56+
return
57+
}
58+
}()
59+
60+
return ctx, func() {
61+
signal.Stop(ch)
62+
cancel(nil)
63+
}
64+
}
65+
3966
func dockerMain(ctx context.Context) error {
40-
ctx, cancelNotify := signal.NotifyContext(ctx, platformsignals.TerminationSignals...)
67+
ctx, cancelNotify := notifyContext(ctx, platformsignals.TerminationSignals...)
4168
defer cancelNotify()
4269

4370
dockerCli, err := command.NewDockerCli(command.WithBaseContext(ctx))

0 commit comments

Comments
 (0)