Skip to content

Commit

Permalink
Merge pull request #182 from luthermonson/signal-shutdown
Browse files Browse the repository at this point in the history
adding the RequestShutdown func from upstream
  • Loading branch information
ibuildthecloud authored Nov 4, 2021
2 parents bf9045f + 8515aa0 commit 9460166
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions pkg/signals/signal.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -23,22 +20,47 @@ import (
)

var onlyOneSignalHandler = make(chan struct{})
var shutdownHandler chan os.Signal

// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler(parent context.Context) context.Context {
// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
// be called once.
func SetupSignalHandler() <-chan struct{} {
return SetupSignalContext().Done()
}

// SetupSignalContext is same as SetupSignalHandler, but a context.Context is returned.
// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
// be called once.
func SetupSignalContext() context.Context {
close(onlyOneSignalHandler) // panics when called twice
ctx, cancel := context.WithCancel(parent)

c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
shutdownHandler = make(chan os.Signal, 2)

ctx, cancel := context.WithCancel(context.Background())
signal.Notify(shutdownHandler, shutdownSignals...)
go func() {
<-c
<-shutdownHandler
cancel()
<-c
<-shutdownHandler
os.Exit(1) // second signal. Exit directly.
}()

return ctx
}

// RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT)
// This returns whether a handler was notified
func RequestShutdown() bool {
if shutdownHandler != nil {
select {
case shutdownHandler <- shutdownSignals[0]:
return true
default:
}
}

return false
}

0 comments on commit 9460166

Please sign in to comment.