Skip to content

Commit

Permalink
Add support for shutdown delay
Browse files Browse the repository at this point in the history
  • Loading branch information
dippynark committed Dec 2, 2023
1 parent a50d5d7 commit 121fbc7
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions pkg/manager/signals/signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,19 @@ import (
"context"
"os"
"os/signal"
"time"
)

var onlyOneSignalHandler = make(chan struct{})

// SetupSignalHandler registers for SIGTERM and SIGINT. A context is returned
// which is canceled on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() context.Context {
// SetupSignalHandlerWithDelay registers for SIGTERM and SIGINT. A context is
// returned which is canceled on one of these signals after waiting for the
// specified delay. In particular, the delay can be used to give external
// Kubernetes controllers (such as kube-proxy) time to observe the termination
// of this manager before starting shutdown of any webhook servers to avoid
// receiving connection attempts after closing webhook listeners. If a second
// signal is caught, the program is terminated with exit code 1.
func SetupSignalHandlerWithDelay(delay time.Duration) context.Context {
close(onlyOneSignalHandler) // panics when called twice

ctx, cancel := context.WithCancel(context.Background())
Expand All @@ -36,10 +41,21 @@ func SetupSignalHandler() context.Context {
signal.Notify(c, shutdownSignals...)
go func() {
<-c
cancel()
// Cancel the context after delaying for the specified duration but
// avoid blocking if a second signal is caught
go func() {
<-time.After(delay)
cancel()
}()
<-c
os.Exit(1) // second signal. Exit directly.
}()

return ctx
}

// SetupSignalHandler is a special case of SetupSignalHandlerWithDelay with no
// delay for backwards compatibility
func SetupSignalHandler() context.Context {
return SetupSignalHandlerWithDelay(time.Duration(0))
}

0 comments on commit 121fbc7

Please sign in to comment.