-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathstatus_manager.go
More file actions
282 lines (224 loc) · 5.82 KB
/
status_manager.go
File metadata and controls
282 lines (224 loc) · 5.82 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package nutsdb
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
type StatusManager struct {
components map[string]Component
componentsMu sync.RWMutex
componentNames []string
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
activeGoCount atomic.Int64
config StatusManagerConfig
startMu sync.Mutex
started bool
closing atomic.Bool
closed atomic.Bool
closedCh chan struct{}
closeErrMu sync.Mutex
closeErr error
}
type StatusManagerConfig struct {
ShutdownTimeout time.Duration
}
func DefaultStatusManagerConfig() StatusManagerConfig {
return StatusManagerConfig{
ShutdownTimeout: 5 * time.Second,
}
}
func NewStatusManager(config StatusManagerConfig) *StatusManager {
ctx, cancel := context.WithCancel(context.Background())
sm := &StatusManager{
componentNames: make([]string, 0),
components: make(map[string]Component),
ctx: ctx,
cancel: cancel,
config: config,
closedCh: make(chan struct{}),
}
return sm
}
func (sm *StatusManager) Context() context.Context {
return sm.ctx
}
func (sm *StatusManager) RegisterComponent(name string, component Component) error {
sm.componentsMu.Lock()
defer sm.componentsMu.Unlock()
if _, exists := sm.components[name]; exists {
return fmt.Errorf("component %s already registered", name)
}
sm.components[name] = component
sm.componentNames = append(sm.componentNames, name)
return nil
}
func (sm *StatusManager) getComponent(name string) (Component, error) {
sm.componentsMu.RLock()
defer sm.componentsMu.RUnlock()
component, ok := sm.components[name]
if !ok {
return nil, fmt.Errorf("component %s not found", name)
}
return component, nil
}
func (sm *StatusManager) getAllComponents() []string {
sm.componentsMu.RLock()
defer sm.componentsMu.RUnlock()
names := make([]string, len(sm.componentNames))
copy(names, sm.componentNames)
return names
}
func (sm *StatusManager) Start() error {
if sm.isClosingOrClosed() {
return ErrDBClosed
}
sm.startMu.Lock()
defer sm.startMu.Unlock()
if sm.started {
return fmt.Errorf("status manager already started")
}
componentNames := sm.getAllComponents()
startedComponents := make([]string, 0, len(componentNames))
for _, name := range componentNames {
component, err := sm.getComponent(name)
if err != nil {
sm.rollbackStartup(startedComponents)
return err
}
if err := component.Start(sm.ctx); err != nil {
sm.rollbackStartup(startedComponents)
return fmt.Errorf("component %s failed to start: %w", name, err)
}
startedComponents = append(startedComponents, name)
}
sm.started = true
return nil
}
func (sm *StatusManager) rollbackStartup(startedComponents []string) {
for i := len(startedComponents) - 1; i >= 0; i-- {
name := startedComponents[i]
component, err := sm.getComponent(name)
if err != nil {
continue
}
_ = component.Stop(5 * time.Second)
}
}
func (sm *StatusManager) Close() error {
if sm.closed.Load() {
return sm.loadCloseErr()
}
if !sm.closing.CompareAndSwap(false, true) {
<-sm.closedCh
return sm.loadCloseErr()
}
err := sm.close()
sm.setCloseErr(err)
sm.closed.Store(true)
close(sm.closedCh)
return err
}
func (sm *StatusManager) close() error {
sm.cancel()
componentNames := sm.getAllComponents()
for i, j := 0, len(componentNames)-1; i < j; i, j = i+1, j-1 {
componentNames[i], componentNames[j] = componentNames[j], componentNames[i]
}
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), sm.config.ShutdownTimeout)
deadline, _ := shutdownCtx.Deadline()
doneCh := make(chan struct{})
go func() {
sm.shutdownComponents(shutdownCtx, componentNames)
close(doneCh)
}()
var shutdownErr error
select {
case <-doneCh:
case <-shutdownCtx.Done():
shutdownErr = fmt.Errorf("timeout stopping components")
}
shutdownCancel()
if err := sm.waitForGoroutines(deadline); err != nil {
if shutdownErr != nil {
shutdownErr = fmt.Errorf("%v; %w", shutdownErr, err)
} else {
shutdownErr = err
}
}
return shutdownErr
}
func (sm *StatusManager) shutdownComponents(ctx context.Context, order []string) {
if len(order) == 0 {
return
}
deadline, hasDeadline := ctx.Deadline()
for idx, name := range order {
select {
case <-ctx.Done():
return
default:
}
component, err := sm.getComponent(name)
if err != nil {
continue
}
remainingTimeout := sm.config.ShutdownTimeout
if hasDeadline {
remainingTimeout = time.Until(deadline)
}
if remainingTimeout <= 0 {
continue
}
remainingComponents := len(order) - idx
componentTimeout := remainingTimeout / time.Duration(remainingComponents)
if componentTimeout <= 0 {
componentTimeout = remainingTimeout
}
_ = component.Stop(componentTimeout)
}
}
func (sm *StatusManager) waitForGoroutines(deadline time.Time) error {
remaining := time.Until(deadline)
if remaining <= 0 {
return fmt.Errorf("timeout waiting for background goroutines to stop")
}
doneCh := make(chan struct{})
go func() {
sm.wg.Wait()
close(doneCh)
}()
select {
case <-doneCh:
return nil
case <-time.After(remaining):
return fmt.Errorf("timeout waiting for background goroutines to stop (count=%d)", sm.activeGoCount.Load())
}
}
func (sm *StatusManager) isClosingOrClosed() bool {
return sm.closing.Load() || sm.closed.Load()
}
func (sm *StatusManager) isClosed() bool {
return sm.closed.Load()
}
func (sm *StatusManager) loadCloseErr() error {
sm.closeErrMu.Lock()
defer sm.closeErrMu.Unlock()
return sm.closeErr
}
func (sm *StatusManager) setCloseErr(err error) {
sm.closeErrMu.Lock()
defer sm.closeErrMu.Unlock()
sm.closeErr = err
}
func (sm *StatusManager) Add(delta int) {
sm.wg.Add(delta)
sm.activeGoCount.Add(int64(delta))
}
func (sm *StatusManager) Done() {
sm.wg.Done()
sm.activeGoCount.Add(-1)
}