-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathappcontext.go
More file actions
48 lines (40 loc) · 973 Bytes
/
appcontext.go
File metadata and controls
48 lines (40 loc) · 973 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package appcontext
import (
"context"
"os"
"os/signal"
"sync"
"github.com/moby/buildkit/util/bklog"
"github.com/pkg/errors"
)
var appContextCache context.Context
var appContextOnce sync.Once
// Context returns a static context that reacts to termination signals of the
// running process. Useful in CLI tools.
func Context() context.Context {
appContextOnce.Do(func() {
signals := make(chan os.Signal, 2048)
signal.Notify(signals, terminationSignals...)
const exitLimit = 3
retries := 0
ctx := context.Background()
for _, f := range inits {
ctx = f(ctx) //nolint:fatcontext
}
ctx, cancel := context.WithCancelCause(ctx)
appContextCache = ctx //nolint:fatcontext
go func() {
for {
<-signals
retries++
err := errors.Errorf("got %d SIGTERM/SIGINTs, forcing shutdown", retries)
cancel(err)
if retries >= exitLimit {
bklog.G(ctx).Error(err.Error())
os.Exit(1)
}
}
}()
})
return appContextCache
}