-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmanager.go
188 lines (165 loc) · 4.15 KB
/
manager.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
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package graceful
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
// manager represents the graceful server manager interface
var manager *Manager
// startOnce initial graceful manager once
var startOnce = sync.Once{}
type (
RunningJob func(context.Context) error
ShtdownJob func() error
)
// Manager manages the graceful shutdown process
type Manager struct {
lock *sync.RWMutex
shutdownCtx context.Context
shutdownCtxCancel context.CancelFunc
doneCtx context.Context
doneCtxCancel context.CancelFunc
logger Logger
runningWaitGroup *routineGroup
errors []error
runAtShutdown []ShtdownJob
}
func (g *Manager) start(ctx context.Context) {
g.shutdownCtx, g.shutdownCtxCancel = context.WithCancel(ctx)
g.doneCtx, g.doneCtxCancel = context.WithCancel(context.Background())
go g.handleSignals(ctx)
}
// doGracefulShutdown graceful shutdown all task
func (g *Manager) doGracefulShutdown() {
g.shutdownCtxCancel()
// doing shutdown job
for _, f := range g.runAtShutdown {
func(run ShtdownJob) {
g.runningWaitGroup.Run(func() {
g.doShutdownJob(run)
})
}(f)
}
go func() {
g.waitForJobs()
g.lock.Lock()
g.doneCtxCancel()
g.lock.Unlock()
}()
}
func (g *Manager) waitForJobs() {
g.runningWaitGroup.Wait()
}
func (g *Manager) handleSignals(ctx context.Context) {
c := make(chan os.Signal, 1)
signal.Notify(
c,
signals...,
)
defer signal.Stop(c)
pid := syscall.Getpid()
for {
select {
case sig := <-c:
switch sig {
case syscall.SIGINT:
g.logger.Infof("PID %d. Received SIGINT. Shutting down...", pid)
g.doGracefulShutdown()
return
case syscall.SIGTERM:
g.logger.Infof("PID %d. Received SIGTERM. Shutting down...", pid)
g.doGracefulShutdown()
return
default:
g.logger.Infof("PID %d. Received %v.", pid, sig)
}
case <-ctx.Done():
g.logger.Infof("PID: %d. Background context for manager closed - %v - Shutting down...", pid, ctx.Err())
g.doGracefulShutdown()
return
}
}
}
// doShutdownJob execute shutdown task
func (g *Manager) doShutdownJob(f ShtdownJob) {
// to handle panic cases from inside the worker
defer func() {
if err := recover(); err != nil {
msg := fmt.Errorf("panic in shutdown job: %v", err)
g.logger.Error(msg)
g.lock.Lock()
g.errors = append(g.errors, msg)
g.lock.Unlock()
}
}()
if err := f(); err != nil {
g.lock.Lock()
g.errors = append(g.errors, err)
g.lock.Unlock()
}
}
// AddShutdownJob add shutdown task
func (g *Manager) AddShutdownJob(f ShtdownJob) {
g.lock.Lock()
g.runAtShutdown = append(g.runAtShutdown, f)
g.lock.Unlock()
}
// AddRunningJob add running task
func (g *Manager) AddRunningJob(f RunningJob) {
g.runningWaitGroup.Run(func() {
// to handle panic cases from inside the worker
defer func() {
if err := recover(); err != nil {
msg := fmt.Errorf("panic in running job: %v", err)
g.logger.Error(msg)
g.lock.Lock()
g.errors = append(g.errors, msg)
g.lock.Unlock()
}
}()
if err := f(g.shutdownCtx); err != nil {
g.lock.Lock()
g.errors = append(g.errors, err)
g.lock.Unlock()
}
})
}
// Done allows the manager to be viewed as a context.Context.
func (g *Manager) Done() <-chan struct{} {
return g.doneCtx.Done()
}
// ShutdownContext returns a context.Context that is Done at shutdown
func (g *Manager) ShutdownContext() context.Context {
return g.shutdownCtx
}
func newManager(opts ...Option) *Manager {
startOnce.Do(func() {
o := newOptions(opts...)
manager = &Manager{
lock: &sync.RWMutex{},
logger: o.logger,
errors: make([]error, 0),
runningWaitGroup: newRoutineGroup(),
}
manager.start(o.ctx)
})
return manager
}
// NewManager initial the Manager
func NewManager(opts ...Option) *Manager {
return newManager(opts...)
}
// NewManagerWithContext initial the Manager with custom context
func NewManagerWithContext(ctx context.Context, opts ...Option) *Manager {
return newManager(append(opts, WithContext(ctx))...)
}
// NewManager get the Manager
func GetManager() *Manager {
if manager == nil {
panic("please use NewManager to initial the manager first")
}
return manager
}