Add a new method to wrap the signal channel in a context. (#420)

* Add a new method to wrap the signal channel in a context.

* Adjust the Deadline and Err implementations based on feedback.
This commit is contained in:
Matt Moore 2019-05-24 15:35:29 +02:00 committed by Knative Prow Robot
parent 34792a92ce
commit 365d80ec5b
1 changed files with 40 additions and 0 deletions

View File

@ -17,8 +17,11 @@ limitations under the License.
package signals
import (
"context"
"errors"
"os"
"os/signal"
"time"
)
var onlyOneSignalHandler = make(chan struct{})
@ -41,3 +44,40 @@ func SetupSignalHandler() (stopCh <-chan struct{}) {
return stop
}
// NewContext creates a new context with SetupSignalHandler()
// as our Done() channel.
func NewContext() context.Context {
return &signalContext{stopCh: SetupSignalHandler()}
}
type signalContext struct {
stopCh <-chan struct{}
}
// Deadline implements context.Context
func (scc *signalContext) Deadline() (deadline time.Time, ok bool) {
return
}
// Done implements context.Context
func (scc *signalContext) Done() <-chan struct{} {
return scc.stopCh
}
// Err implements context.Context
func (scc *signalContext) Err() error {
select {
case _, ok := <-scc.Done():
if !ok {
return errors.New("received a termination signal.")
}
default:
}
return nil
}
// Value implements context.Context
func (scc *signalContext) Value(key interface{}) interface{} {
return nil
}