-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrace.go
97 lines (81 loc) · 1.55 KB
/
grace.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package gracefully
import (
"context"
"errors"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type Shutdown interface {
Shutdown(context.Context) error
}
type GraceFn func(*grace)
func WithTimeout(t time.Duration) GraceFn {
return func(g *grace) {
g.td = t
}
}
func WithShutdown(s Shutdown) GraceFn {
return func(g *grace) {
g.ss = append(g.ss, s)
}
}
func WithSignaler(sig chan os.Signal) GraceFn {
return func(g *grace) {
g.sig = sig
}
}
type Grace interface {
Grace() error
}
type grace struct {
ss []Shutdown
td time.Duration
sig chan os.Signal
}
func New(fns ...GraceFn) Grace {
g := &grace{}
WithTimeout(time.Second * 5)(g)
WithSignaler(make(chan os.Signal, 1))(g)
for _, fn := range fns {
fn(g)
}
return g
}
func (g *grace) Grace() error {
ctx, cancel := context.WithTimeout(context.Background(), g.td)
defer cancel()
timeout := ctx.Done()
signal.Notify(g.sig, os.Interrupt, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGTERM)
<-g.sig
done := make(chan struct{})
go g.shutdownAll(ctx, done)
select {
case <-done:
return nil
case <-timeout:
return errors.New("closed by timeout")
}
}
func (g *grace) shutdownAll(ctx context.Context, done chan<- struct{}) {
defer close(done)
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for _, s := range g.ss {
wg.Add(1)
go g.shutdownOne(ctx, wg, s)
}
}()
wg.Wait()
}
func (g *grace) shutdownOne(ctx context.Context, wg *sync.WaitGroup, s Shutdown) {
defer wg.Done()
if err := s.Shutdown(ctx); err != nil {
log.Println(err)
}
}