-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshutdown.go
More file actions
143 lines (107 loc) · 2.54 KB
/
shutdown.go
File metadata and controls
143 lines (107 loc) · 2.54 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package shutdown
import (
"context"
"fmt"
"log/slog"
"os"
"os/signal"
"sync"
"syscall"
)
// Watch starts a shutdown watcher.
func Watch(opts ...func(*config)) (context.Context, context.CancelFunc) {
cfg := config{
ctx: context.Background(),
logFn: slog.Error,
signals: []os.Signal{os.Interrupt, syscall.SIGTERM},
exit: os.Exit,
forceExitCode: 1,
timeoutExitCode: 1,
}
for _, opt := range opts {
opt(&cfg)
}
ctx, ctxCancel := context.WithCancelCause(cfg.ctx)
if len(cfg.signals) > 0 {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, cfg.signals...)
WithWatcher(func(ctx context.Context, ch chan<- error) error {
defer close(sigCh)
defer signal.Stop(sigCh)
select {
case <-ctx.Done():
return nil
case sig := <-sigCh:
ch <- fmt.Errorf("signal %q received", sig.String()) //nolint:goerr113
if cfg.doubleSignal {
shutdownCtx, shutdownCtxCancel := context.WithCancel(context.Background())
if cfg.timeout > 0 {
shutdownCtx, shutdownCtxCancel = context.WithTimeout(shutdownCtx, cfg.timeout)
}
defer shutdownCtxCancel()
select {
case <-shutdownCtx.Done():
return nil
case sig = <-sigCh:
ch <- fmt.Errorf("second %q signal received", sig.String()) //nolint:goerr113
}
}
return nil
}
})(&cfg)
}
var wg sync.WaitGroup
wg.Add(len(cfg.watchers))
for _, w := range cfg.watchers {
go func(watcher func(context.Context, chan<- error) error) {
ch := make(chan error, 1)
go func() {
defer close(ch)
wg.Done()
if err := watcher(ctx, ch); err != nil {
cfg.logFn(fmt.Sprintf("watcher error: %s", err))
ctxCancel(err)
}
}()
select {
case <-ctx.Done():
return
case err, ok := <-ch:
if !ok {
return
}
if err != nil {
cfg.logFn(err.Error())
}
ctxCancel(err)
shutdownCtx, shutdownCtxCancel := context.WithCancel(context.Background())
if cfg.timeout > 0 {
shutdownCtx, shutdownCtxCancel = context.WithTimeout(shutdownCtx, cfg.timeout)
}
defer shutdownCtxCancel()
for {
select {
case <-shutdownCtx.Done():
cfg.logFn("shutdown timeout reached, force exit")
cfg.exit(cfg.timeoutExitCode)
return
case err, ok := <-ch:
if !ok {
if cfg.timeout > 0 {
continue
}
return
}
if err != nil {
cfg.logFn(err.Error())
}
cfg.exit(cfg.forceExitCode)
return
}
}
}
}(w)
}
wg.Wait()
return ctx, func() { ctxCancel(nil) }
}