Skip to content

Commit 121fbc7

Browse files
committed
Add support for shutdown delay
1 parent a50d5d7 commit 121fbc7

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

pkg/manager/signals/signal.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,19 @@ import (
2020
"context"
2121
"os"
2222
"os/signal"
23+
"time"
2324
)
2425

2526
var onlyOneSignalHandler = make(chan struct{})
2627

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

3338
ctx, cancel := context.WithCancel(context.Background())
@@ -36,10 +41,21 @@ func SetupSignalHandler() context.Context {
3641
signal.Notify(c, shutdownSignals...)
3742
go func() {
3843
<-c
39-
cancel()
44+
// Cancel the context after delaying for the specified duration but
45+
// avoid blocking if a second signal is caught
46+
go func() {
47+
<-time.After(delay)
48+
cancel()
49+
}()
4050
<-c
4151
os.Exit(1) // second signal. Exit directly.
4252
}()
4353

4454
return ctx
4555
}
56+
57+
// SetupSignalHandler is a special case of SetupSignalHandlerWithDelay with no
58+
// delay for backwards compatibility
59+
func SetupSignalHandler() context.Context {
60+
return SetupSignalHandlerWithDelay(time.Duration(0))
61+
}

0 commit comments

Comments
 (0)