@@ -20,14 +20,19 @@ import (
20
20
"context"
21
21
"os"
22
22
"os/signal"
23
+ "time"
23
24
)
24
25
25
26
var onlyOneSignalHandler = make (chan struct {})
26
27
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 {
31
36
close (onlyOneSignalHandler ) // panics when called twice
32
37
33
38
ctx , cancel := context .WithCancel (context .Background ())
@@ -36,10 +41,21 @@ func SetupSignalHandler() context.Context {
36
41
signal .Notify (c , shutdownSignals ... )
37
42
go func () {
38
43
<- 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
+ }()
40
50
<- c
41
51
os .Exit (1 ) // second signal. Exit directly.
42
52
}()
43
53
44
54
return ctx
45
55
}
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