-
Notifications
You must be signed in to change notification settings - Fork 784
/
manager.go
333 lines (275 loc) · 8.82 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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package services
import (
"context"
"errors"
"fmt"
"sync"
)
type managerState int
const (
unknown managerState = iota // initial state
healthy // all services running
stopped // all services stopped (failed or terminated)
)
// ManagerListener listens for events from Manager.
type ManagerListener interface {
// Called when Manager reaches Healthy state (all services Running)
Healthy()
// Called when Manager reaches Stopped state (all services are either Terminated or Failed)
Stopped()
// Called when service fails.
Failure(service Service)
}
// Service Manager is initialized with a collection of services. They all must be in New state.
// Service manager can start them, and observe their state as a group.
// Once all services are running, Manager is said to be Healthy. It is possible for manager to never reach the Healthy state, if some services fail to start.
// When all services are stopped (Terminated or Failed), manager is Stopped.
type Manager struct {
services []Service
healthyCh chan struct{} // closed when healthy state is reached, or if it cannot be reached anymore (whatever happens first)
stoppedCh chan struct{} // closed when stopped state is reached.
mu sync.Mutex
state managerState
byState map[State][]Service // Services sorted by state
healthyClosed bool // was healthyCh closed already?
listeners []chan func(listener ManagerListener)
}
// NewManager creates new service manager. It needs at least one service, and all services must be in New state.
func NewManager(services ...Service) (*Manager, error) {
if len(services) == 0 {
return nil, errors.New("no services")
}
m := &Manager{
services: services,
byState: map[State][]Service{},
healthyCh: make(chan struct{}),
stoppedCh: make(chan struct{}),
}
for _, s := range services {
st := s.State()
if st != New {
return nil, fmt.Errorf("unexpected service state: %v", st)
}
m.byState[st] = append(m.byState[st], s)
}
for _, s := range services {
s.AddListener(newManagerServiceListener(m, s))
}
return m, nil
}
// Initiates service startup on all the services being managed.
// It is only valid to call this method if all of the services are New.
func (m *Manager) StartAsync(ctx context.Context) error {
for _, s := range m.services {
err := s.StartAsync(ctx)
if err != nil {
return err
}
}
return nil
}
// Initiates service shutdown if necessary on all the services being managed.
func (m *Manager) StopAsync() {
if m == nil {
return
}
for _, s := range m.services {
s.StopAsync()
}
}
// Returns true if all services are currently in the Running state.
func (m *Manager) IsHealthy() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.state == healthy
}
// Waits for the ServiceManager to become healthy. Returns nil, if manager is healthy, error otherwise (eg. manager
// is in a state in which it cannot get healthy anymore).
func (m *Manager) AwaitHealthy(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-m.healthyCh:
}
m.mu.Lock()
defer m.mu.Unlock()
if m.state != healthy {
return errors.New("not healthy")
}
return nil
}
// Returns true if all services are in terminal state (Terminated or Failed)
func (m *Manager) IsStopped() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.state == stopped
}
// Waits for the ServiceManager to become stopped. Returns nil, if manager is stopped, error when context finishes earlier.
func (m *Manager) AwaitStopped(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-m.stoppedCh:
return nil
}
}
// Provides a snapshot of the current state of all the services under management.
func (m *Manager) ServicesByState() map[State][]Service {
m.mu.Lock()
defer m.mu.Unlock()
result := map[State][]Service{}
for st, ss := range m.byState {
result[st] = append([]Service(nil), ss...) // make a copy
}
return result
}
func (m *Manager) serviceStateChanged(s Service, from State, to State) {
m.mu.Lock()
defer m.mu.Unlock()
fs := m.byState[from]
for ix, ss := range fs {
if s == ss {
fs = append(fs[:ix], fs[ix+1:]...)
break
}
}
if len(fs) == 0 {
delete(m.byState, from)
} else {
m.byState[from] = fs
}
m.byState[to] = append(m.byState[to], s)
if to == Failed {
m.notifyListeners(func(l ManagerListener) { l.Failure(s) }, false)
}
running := len(m.byState[Running])
stopping := len(m.byState[Stopping])
done := len(m.byState[Terminated]) + len(m.byState[Failed])
all := len(m.services)
switch {
case running == all:
close(m.healthyCh)
m.state = healthy
m.healthyClosed = true
m.notifyListeners(func(l ManagerListener) { l.Healthy() }, false)
case done == all:
if !m.healthyClosed {
// healthy cannot be reached anymore
close(m.healthyCh)
m.healthyClosed = true
}
close(m.stoppedCh) // happens at most once
m.state = stopped
m.notifyListeners(func(l ManagerListener) { l.Stopped() }, true)
default:
if !m.healthyClosed && (done > 0 || stopping > 0) {
// healthy cannot be reached anymore
close(m.healthyCh)
m.healthyClosed = true
}
m.state = unknown
}
}
// Registers a ManagerListener to be run when this Manager changes state.
// The listener will not have previous state changes replayed, so it is suggested that listeners are added before any of the managed services are started.
//
// AddListener guarantees execution ordering across calls to a given listener but not across calls to multiple listeners.
// Specifically, a given listener will have its callbacks invoked in the same order as the underlying service enters those states.
// Additionally, at most one of the listener's callbacks will execute at once.
// However, multiple listeners' callbacks may execute concurrently, and listeners may execute in an order different from the one in which they were registered.
func (m *Manager) AddListener(listener ManagerListener) {
m.mu.Lock()
defer m.mu.Unlock()
if m.state == stopped {
// no need to register listener, as no more events will be sent
return
}
// max number of events is: failed notification for each service + healthy + stopped.
// we use buffer to avoid blocking the sender, which holds the manager's lock.
ch := make(chan func(l ManagerListener), len(m.services)+2)
m.listeners = append(m.listeners, ch)
go func() {
for fn := range ch {
fn(listener)
}
}()
}
// called with lock
func (m *Manager) notifyListeners(fn func(l ManagerListener), closeChan bool) {
for _, ch := range m.listeners {
ch <- fn
if closeChan {
close(ch)
}
}
}
func newManagerServiceListener(m *Manager, s Service) *managerServiceListener {
return &managerServiceListener{m: m, s: s}
}
// managerServiceListener is a service listener, that updates Service state in the Manager
type managerServiceListener struct {
m *Manager
s Service
}
func (l managerServiceListener) Starting() {
l.m.serviceStateChanged(l.s, New, Starting)
}
func (l managerServiceListener) Running() {
l.m.serviceStateChanged(l.s, Starting, Running)
}
func (l managerServiceListener) Stopping(from State) {
l.m.serviceStateChanged(l.s, from, Stopping)
}
func (l managerServiceListener) Terminated(from State) {
l.m.serviceStateChanged(l.s, from, Terminated)
}
func (l managerServiceListener) Failed(from State, failure error) {
l.m.serviceStateChanged(l.s, from, Failed)
}
// NewManagerListener provides a simple way to build manager listener from supplied functions.
// Functions will only be called when not nil.
func NewManagerListener(healthy, stopped func(), failure func(service Service)) ManagerListener {
return &funcBasedManagerListener{
healthy: healthy,
stopped: stopped,
failure: failure,
}
}
type funcBasedManagerListener struct {
healthy func()
stopped func()
failure func(service Service)
}
func (f *funcBasedManagerListener) Healthy() {
if f.healthy != nil {
f.healthy()
}
}
func (f funcBasedManagerListener) Stopped() {
if f.stopped != nil {
f.stopped()
}
}
func (f funcBasedManagerListener) Failure(service Service) {
if f.failure != nil {
f.failure(service)
}
}
// StartManagerAndAwaitHealthy starts the manager (which in turns starts all services managed by it), and then waits
// until it reaches Running state. All services that this manager manages must be in New state, otherwise starting
// will fail.
//
// Notice that context passed to the manager for starting its services is the same as context used for waiting!
func StartManagerAndAwaitHealthy(ctx context.Context, manager *Manager) error {
err := manager.StartAsync(ctx)
if err != nil {
return err
}
return manager.AwaitHealthy(ctx)
}
// StopManagerAndAwaitStopped asks manager to stop its services, and then waits
// until manager reaches the stopped state or context is stopped.
func StopManagerAndAwaitStopped(ctx context.Context, manager *Manager) error {
manager.StopAsync()
return manager.AwaitStopped(ctx)
}