Skip to content

✨ Enable signal handler to close channel after sleeping for some seconds #782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/manager/signals/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@ limitations under the License.
// shutdown the manager in combination with Kubernetes pod graceful termination
// policy.
package signals

import (
logf "sigs.k8s.io/controller-runtime/pkg/internal/log"
)

var log = logf.RuntimeLog.WithName("signal")
29 changes: 29 additions & 0 deletions pkg/manager/signals/signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ package signals
import (
"os"
"os/signal"
"strconv"
"time"
)

const (
channelClosureDelaySecondsEnv = "CHANNEL_CLOSURE_DELAY_SECONDS"

defaultChannelClosureDelaySeconds = 0
)

var onlyOneSignalHandler = make(chan struct{})
Expand All @@ -34,10 +42,31 @@ func SetupSignalHandler() (stopCh <-chan struct{}) {
signal.Notify(c, shutdownSignals...)
go func() {
<-c
d := getDelaySecondsFromEnv()
log.Info("receive signal", "delay", d)
time.Sleep(time.Duration(d) * time.Second)
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()

return stop
}

func getDelaySecondsFromEnv() int {
delayStr := os.Getenv(channelClosureDelaySecondsEnv)
if len(delayStr) == 0 {
return defaultChannelClosureDelaySeconds
}

delay, err := strconv.Atoi(delayStr)
if err != nil {
log.Info("failed to convert channel closure delay", "envvar", delayStr)
return defaultChannelClosureDelaySeconds
}
if delay < 0 {
log.Info("get invalid channel closure delay from envvar", "envvar", delayStr)
return 0
}
return delay
}