-
Notifications
You must be signed in to change notification settings - Fork 2
/
context.go
76 lines (69 loc) · 1.76 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
65
66
67
68
69
70
71
72
73
74
75
76
// Package grace implements set of helper functions around syscal.Signals
// for gracefully shutdown and reload the service.
package grace
import (
"context"
"os"
"os/signal"
"syscall"
)
// ShutdownContext returns child context from passed context which will be canceled
// on incoming signals: SIGINT, SIGTERM, SIGHUP.
// Ends immediately by os.Exit(1) after second signal
func ShutdownContext(c context.Context) context.Context {
return cancelContextOnSignals(c, true, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
}
// StopContext returns child context which will be canceled on syscall.SIGINT or syscall.SIGTERM signal
func StopContext(c context.Context) context.Context {
return cancelContextOnSignals(c, true, syscall.SIGINT, syscall.SIGTERM)
}
// ReloadContext returns reload signals channel
func ReloadChannel(ctx context.Context) <-chan struct{} {
done := make(chan struct{})
sighups := make(chan struct{})
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP)
close(done)
for {
select {
case <-ctx.Done():
return
case <-ch:
sighups <- struct{}{}
}
}
}()
<-done
return sighups
}
func cancelContextOnSignals(c context.Context, osExitOnSecond bool, signals ...os.Signal) context.Context {
ctx, cancel := context.WithCancel(c)
done := make(chan struct{})
go listenSignalsFunc(ctx, cancel, done, osExitOnSecond, signals...)()
<-done
return ctx
}
func listenSignalsFunc(
ctx context.Context,
cancel context.CancelFunc,
done chan struct{},
osExitOnSecond bool,
signals ...os.Signal,
) func() {
return func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, signals...)
close(done)
select {
case <-ctx.Done():
return
case <-ch:
cancel()
if osExitOnSecond {
<-ch
os.Exit(1)
}
}
}
}