mirror of https://github.com/knative/pkg.git
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:
parent
34792a92ce
commit
365d80ec5b
|
@ -17,8 +17,11 @@ limitations under the License.
|
||||||
package signals
|
package signals
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var onlyOneSignalHandler = make(chan struct{})
|
var onlyOneSignalHandler = make(chan struct{})
|
||||||
|
@ -41,3 +44,40 @@ func SetupSignalHandler() (stopCh <-chan struct{}) {
|
||||||
|
|
||||||
return stop
|
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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue