Skip to content

Commit

Permalink
cmd/docker: print status on SIGTERM and not SIGINT
Browse files Browse the repository at this point in the history
Signed-off-by: Alano Terblanche <[email protected]>
  • Loading branch information
Benehiko committed Feb 3, 2025
1 parent bdd630c commit 4e7cf34
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
27 changes: 23 additions & 4 deletions cmd/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,19 @@ import (
"go.opentelemetry.io/otel"
)

var errCtxUserTerminated = errors.New("user terminated the process")
type errCtxSignalTerminated struct {
signal os.Signal
}

func (e errCtxSignalTerminated) Error() string {
return ""
}

func main() {
ctx := context.Background()
err := dockerMain(ctx)
if err != nil && !errdefs.IsCancelled(err) && !errors.Is(err, errCtxUserTerminated) {

if err != nil && !errdefs.IsCancelled(err) {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(getExitCode(err))
}
Expand All @@ -50,8 +57,10 @@ func notifyContext(ctx context.Context, signals ...os.Signal) (context.Context,
case <-ctx.Done():
signal.Stop(ch)
return
case <-ch:
cancel(errCtxUserTerminated)
case sig := <-ch:
cancel(errCtxSignalTerminated{
signal: sig,
})
signal.Stop(ch)
return
}
Expand Down Expand Up @@ -84,6 +93,16 @@ func getExitCode(err error) int {
if err == nil {
return 0
}

var userTerminatedErr errCtxSignalTerminated
if errors.As(err, &userTerminatedErr) {
signal, ok := userTerminatedErr.signal.(syscall.Signal)
if !ok {
return 1
}
return 128 + int(signal)
}

var stErr cli.StatusError
if errors.As(err, &stErr) && stErr.StatusCode != 0 { // FIXME(thaJeztah): StatusCode should never be used with a zero status-code. Check if we do this anywhere.
return stErr.StatusCode
Expand Down
18 changes: 17 additions & 1 deletion cmd/docker/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,21 @@ func TestUserTerminatedError(t *testing.T) {
syscall.Kill(syscall.Getpid(), syscall.SIGINT)

<-notifyCtx.Done()
assert.ErrorIs(t, context.Cause(notifyCtx), errCtxUserTerminated)
assert.ErrorIs(t, context.Cause(notifyCtx), errCtxSignalTerminated{
signal: syscall.SIGINT,
})

assert.Equal(t, getExitCode(context.Cause(notifyCtx)), 130)

notifyCtx, cancelNotify = notifyContext(ctx, platformsignals.TerminationSignals...)
t.Cleanup(cancelNotify)

syscall.Kill(syscall.Getpid(), syscall.SIGTERM)

<-notifyCtx.Done()
assert.ErrorIs(t, context.Cause(notifyCtx), errCtxSignalTerminated{
signal: syscall.SIGTERM,
})

assert.Equal(t, getExitCode(context.Cause(notifyCtx)), 143)
}

0 comments on commit 4e7cf34

Please sign in to comment.