forked from hanagantig/gracy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gracy.go
74 lines (59 loc) · 1.23 KB
/
gracy.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
package gracy
import (
"context"
"errors"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
const defaultTimeout = 10 * time.Second
var defaultSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP, syscall.SIGKILL}
type CallbackFunc func() error
var gracy *Gracy
type Gracy struct {
stop chan os.Signal
mu sync.RWMutex
callbacks []CallbackFunc
}
func init() {
stop := make(chan os.Signal, 1)
signal.Notify(stop, defaultSignals...)
gracy = &Gracy{stop: stop}
}
func AddCallback(f CallbackFunc) {
gracy.mu.Lock()
gracy.callbacks = append(gracy.callbacks, f)
gracy.mu.Unlock()
}
func Wait() error {
select {
case <-gracy.stop:
}
return GracefulShutdown()
}
func GracefulShutdown() error {
stop := make(chan os.Signal, 1)
signal.Notify(stop, defaultSignals...)
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
done := make(chan struct{})
go func() {
defer close(done)
for _, f := range gracy.callbacks {
err := f()
if err != nil {
_ = err // todo handle err
}
}
}()
select {
case <-done:
return nil
case <-stop:
return errors.New("gracy force stopped")
case <-ctx.Done():
return errors.New("gracy waiting timeout")
}
}