Skip to content

Commit c37453b

Browse files
committed
Add shutdown grace period flag
1 parent 6276cb2 commit c37453b

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

main.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ import (
2626
"net/http"
2727
_ "net/http/pprof"
2828
"os"
29+
"os/signal"
2930
"path/filepath"
31+
"syscall"
3032
"time"
3133

3234
"github.com/go-logr/zapr"
@@ -115,6 +117,7 @@ var (
115117
disabledBuiltins = util.NewFlagSet()
116118
enableK8sCel = flag.Bool("experimental-enable-k8s-native-validation", false, "PROTOTYPE (not stable): enable the validating admission policy driver")
117119
externaldataProviderResponseCacheTTL = flag.Duration("external-data-provider-response-cache-ttl", 3*time.Minute, "TTL for the external data provider response cache. Specify the duration in 'h', 'm', or 's' for hours, minutes, or seconds respectively. Defaults to 3 minutes if unspecified. Setting the TTL to 0 disables the cache.")
120+
shutdownGracePeriod = flag.Duration("shutdown-grace-period", 10*time.Second, "time to wait before shutting down")
118121
)
119122

120123
func init() {
@@ -309,7 +312,7 @@ func innerMain() int {
309312

310313
// Setup controllers asynchronously, they will block for certificate generation if needed.
311314
setupErr := make(chan error)
312-
ctx := ctrl.SetupSignalHandler()
315+
ctx := setupSignalHandler(*shutdownGracePeriod)
313316
go func() {
314317
setupErr <- setupControllers(ctx, mgr, sw, tracker, setupFinished)
315318
}()
@@ -579,3 +582,28 @@ func setLoggerForProduction(encoder zapcore.LevelEncoder, dest io.Writer) {
579582
ctrl.SetLogger(newlogger)
580583
klog.SetLogger(newlogger)
581584
}
585+
586+
// setupSignalHandler registers a signal handler for SIGTERM and SIGINT and
587+
// returns a context which is canceled when one of these signals is caught after
588+
// waiting for a grace period. If a second signal is caught then the program
589+
// terminates with exit code 1. Implementation stolen from controller-runtime
590+
// and then extended with grace period support:
591+
// https://github.com/kubernetes-sigs/controller-runtime/blob/2154ffbc22e26ffd8c3b713927f0df2fa40841f2/pkg/manager/signals/signal.go#L27-L45
592+
func setupSignalHandler(gracePeriod time.Duration) context.Context {
593+
ctx, cancel := context.WithCancel(context.Background())
594+
595+
c := make(chan os.Signal, 2)
596+
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
597+
go func() {
598+
<-c
599+
// Cancel the context once the grace period expires
600+
go func() {
601+
<-time.After(gracePeriod)
602+
cancel()
603+
}()
604+
<-c
605+
os.Exit(1) // Second signal received, exit directly...
606+
}()
607+
608+
return ctx
609+
}

0 commit comments

Comments
 (0)