2017-07-03 04:21:40 +00:00
|
|
|
package appcontext
|
2017-06-29 22:31:08 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"sync"
|
|
|
|
|
2017-07-19 01:05:19 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2017-06-29 22:31:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var appContextCache context.Context
|
|
|
|
var appContextOnce sync.Once
|
|
|
|
|
2017-07-03 04:21:40 +00:00
|
|
|
// Context returns a static context that reacts to termination signals of the
|
|
|
|
// running process. Useful in CLI tools.
|
|
|
|
func Context() context.Context {
|
2017-06-29 22:31:08 +00:00
|
|
|
appContextOnce.Do(func() {
|
|
|
|
signals := make(chan os.Signal, 2048)
|
2017-07-12 05:08:53 +00:00
|
|
|
signal.Notify(signals, terminationSignals...)
|
2017-06-29 22:31:08 +00:00
|
|
|
|
|
|
|
const exitLimit = 3
|
|
|
|
retries := 0
|
|
|
|
|
2021-06-09 03:01:18 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
for _, f := range inits {
|
|
|
|
ctx = f(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
2017-06-29 22:31:08 +00:00
|
|
|
appContextCache = ctx
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
<-signals
|
|
|
|
cancel()
|
|
|
|
retries++
|
|
|
|
if retries >= exitLimit {
|
2017-07-03 04:21:40 +00:00
|
|
|
logrus.Errorf("got %d SIGTERM/SIGINTs, forcing shutdown", retries)
|
2017-06-29 22:31:08 +00:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
})
|
|
|
|
return appContextCache
|
|
|
|
}
|