-
Notifications
You must be signed in to change notification settings - Fork 280
/
context.go
65 lines (57 loc) · 1.62 KB
/
context.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package context
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
"github.com/assetnote/kiterunner/pkg/log"
)
var (
ctx context.Context
cancel context.CancelFunc
ctxInitialized sync.Once
)
// AddInterruptCancellation will add an interrupt handler that will catch the first SIGTERM and cancel the context
// upon second SIGTERM, the program will exit immediately
// This wrapping allows for graceful shutdown of the application
func AddInterruptCancellation(ctx context.Context, cancel context.CancelFunc) {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
interrupts := 0
for {
select {
case <-c:
interrupts++
if interrupts > 1 {
log.Info().Msg("Received multiple interrupt signals. Exiting")
os.Exit(1)
}
log.Info().Msg("Received interrupt signal")
cancel()
case <-ctx.Done():
}
}
}()
}
// InitContext will initialize the global context used to catch interrupts. This is automatically called
// by Context and Cancel
func InitContext() {
ctxInitialized.Do(func() {
ctx, cancel = context.WithCancel(context.Background())
AddInterruptCancellation(ctx, cancel)
})
}
// Context will initialize the global context and attach the interrupt handler that will cancel the context
// upon SIGTERM. This is safe to call from multiple goroutines and will always return the same context
func Context() context.Context {
InitContext()
return ctx
}
// Cancel will cancel the global context. Calling this multiple times is the equivalent of cancelling
// the same context multiple times
func Cancel() {
InitContext()
cancel()
}