Skip to content

Commit

Permalink
shutdown: introduce the new NotifyContext
Browse files Browse the repository at this point in the history
As of Go 1.16 signal.NotifyContext ties the context to
the signal handling instead of having to do it manually.
This PR also bumps the Go version.

Signed-off-by: crozzy <joseph.crosland@gmail.com>
  • Loading branch information
crozzy committed Sep 13, 2021
1 parent 66a3137 commit 6b7029d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 32 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/cut-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
release-binaries:
name: Create Release Binaries
runs-on: 'ubuntu-latest'
container: quay.io/projectquay/golang:1.15
container: quay.io/projectquay/golang:1.16
needs: release-archive
strategy:
matrix:
Expand Down
44 changes: 13 additions & 31 deletions cmd/clair/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,44 +117,26 @@ func main() {
})

// Signal handler goroutine.
srvs.Go(func() error {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer func() {
signal.Stop(c)
close(c)
zlog.Info(ctx).Msg("unregistered signal handler")
}()
zlog.Info(ctx).Msg("registered signal handler")
select {
case sig := <-c:
zlog.Info(ctx).
Stringer("signal", sig).
Msg("gracefully shutting down")
// Note that we're using the root context here, so that we get a
// full timeout if one errgroup goroutine returns uncleanly.
tctx, done := context.WithTimeout(ctx, 10*time.Second)
// Note that we're using a background context here, so that we get a
// full timeout if the signal handler has fired.
tctx, done := context.WithTimeout(context.Background(), 10*time.Second)
err := down.Shutdown(tctx)
done()
if err != nil {
zlog.Error(ctx).Err(err).Msg("error shutting down server")
}
done()
stop()
zlog.Info(ctx).Msg("unregistered signal handler")
}()
zlog.Info(ctx).Msg("registered signal handler")
select {
case <-ctx.Done():
zlog.Info(ctx).Stringer("signal", os.Interrupt).Msg("gracefully shutting down")
case <-srvctx.Done():
}
return nil
})
// Spawn a goroutine outside to wait on the errgroup.
//
// This is needed to call shutdown and cause the servers to return when only
// one has returned an error.
go func() {
<-srvctx.Done()
tctx, done := context.WithTimeout(ctx, 10*time.Second)
err := down.Shutdown(tctx)
done()
if err != nil {
zlog.Error(ctx).Err(err).Msg("error shutting down server")
}
}()

zlog.Info(ctx).Str("version", Version).Msg("ready")
Expand Down

0 comments on commit 6b7029d

Please sign in to comment.