-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.go
326 lines (279 loc) · 7.65 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
package gorman
import (
"bytes"
"context"
"fmt"
"github.com/morebec/go-errors/errors"
"golang.org/x/exp/slog"
"sync"
"time"
)
const GoroutineNotFoundErrorCode = "goroutine_not_found"
type Options struct {
Logger *slog.Logger
}
// RestartPolicy is an interface responsible for deciding whether a Goroutine should be restarted when its stops
// from the Manager's point of view.
type RestartPolicy interface {
// MustRestart indicates if a goroutine should be restarted according to this policy.
// This method will return true to indicate that the provided Goroutine should be restarted,
// otherwise it will return false.
// To apply a delay between restarts, one can simply make this function wait before returning the result.
MustRestart(g *Goroutine) bool
}
type RestartPolicyFunc func(g *Goroutine) bool
func (r RestartPolicyFunc) MustRestart(g *Goroutine) bool {
return r(g)
}
// AlwaysRestart this policy indicates that a Goroutine should always be restarted.
func AlwaysRestart() RestartPolicy {
return RestartPolicyFunc(func(g *Goroutine) bool {
return true
})
}
// NeverRestart returns a policy that indicates that a Goroutine should never be restarted.
func NeverRestart() RestartPolicy {
return RestartPolicyFunc(func(g *Goroutine) bool {
return false
})
}
// RestartOnError returns a policy that indicates that a Goroutine should be restarted when an error occurred.
func RestartOnError() RestartPolicy {
return RestartPolicyFunc(func(g *Goroutine) bool {
exec, _ := g.LastExecution()
return exec.Error != nil
})
}
// managedGoroutine is a decorator for Goroutine that allows specifying restart policies.
type managedGoroutine struct {
Goroutine
restartPolicy RestartPolicy
}
func (g *managedGoroutine) mustRestart() bool {
return g.restartPolicy.MustRestart(&g.Goroutine)
}
type Manager struct {
goroutines map[string]*managedGoroutine
mu sync.Mutex
cancelFunc context.CancelFunc
logger *slog.Logger
shuttingDown bool
}
func NewManager(opts Options) *Manager {
if opts.Logger == nil {
void := &bytes.Buffer{}
opts.Logger = slog.New(slog.NewTextHandler(void))
}
return &Manager{
goroutines: map[string]*managedGoroutine{},
logger: opts.Logger,
}
}
// Add a Goroutine to this manager.
func (m *Manager) Add(name string, f GoroutineFunc, rp RestartPolicy) {
m.mu.Lock()
defer m.mu.Unlock()
if m.goroutines == nil {
m.goroutines = map[string]*managedGoroutine{}
}
if rp == nil {
rp = NeverRestart()
}
m.goroutines[name] = &managedGoroutine{
Goroutine: Goroutine{
Name: name,
Func: f,
},
restartPolicy: rp,
}
}
// Start a Goroutine or returns an error if there was a problem starting the goroutine.
// The goroutine must have been added to the manager.
func (m *Manager) Start(ctx context.Context, name string) error {
gr, err := m.findGoroutineByName(name)
if err != nil {
return err
}
if gr.Running() {
return nil
}
m.logger.Info(fmt.Sprintf("starting %s...", name))
listener := gr.Listen()
gr.Start(ctx)
go func() {
for {
select {
case evt := <-listener:
switch evt.(type) {
case GoroutineStartedEvent:
e := evt.(GoroutineStartedEvent)
m.logger.Info(fmt.Sprintf("%s started", e.Name))
case GoroutineStoppedEvent:
e := evt.(GoroutineStoppedEvent)
if e.Error != nil {
m.logger.Error(fmt.Sprintf("%s encontered error %s", e.Name, e.Error.Error()))
}
m.logger.Info(fmt.Sprintf("%s stopped", e.Name))
gr.Unlisten(listener)
if !m.shuttingDown && gr.mustRestart() {
m.logger.Info(fmt.Sprintf("will restart %s ...", e.Name))
if err := m.Start(ctx, gr.Name); err != nil {
m.logger.Error(fmt.Sprintf("failed restarting %s, encontered error %s", e.Name, e.Error.Error()))
}
}
}
}
}
//eventChan := gr.Listen()
//
//// started
//started := <-eventChan
//startedEvt := started.(GoroutineStartedEvent)
//log.Printf("%s started \n", startedEvt.Name)
//
//// stopped
//stopped := <-eventChan
//stoppedEvt := stopped.(GoroutineStoppedEvent)
//if stoppedEvt.Error != nil {
// log.Printf("%s encountered error %s \n", stoppedEvt.Name, stoppedEvt.Error)
//}
//log.Printf("%s stopped \n", stoppedEvt.Name)
}()
return nil
}
// Stop a Goroutine by its name.
func (m *Manager) Stop(name string) error {
gr, err := m.findGoroutineByName(name)
if err != nil {
return err
}
if !gr.Running() {
return nil
}
m.logger.Info(fmt.Sprintf("stopping %s...", name))
return gr.Stop()
}
// Run the manager and all the registered Goroutine, until the manager is shutdown.
func (m *Manager) Run(ctx context.Context) {
m.logger.Info("gorman started")
// Start Goroutines
ctx, cancel := context.WithCancel(ctx)
m.cancelFunc = cancel
m.StartAll(ctx)
var wg sync.WaitGroup
wg.Add(1)
go func() {
select {
case <-ctx.Done():
m.logger.Info("shutting down gorman...")
// Perform shutdown
m.StopAll(true)
wg.Done()
}
return
}()
wg.Wait()
}
// StartAll the Goroutine managed by this manager.
func (m *Manager) StartAll(ctx context.Context) {
m.mu.Lock()
goroutines := m.goroutines
m.mu.Unlock()
for name := range goroutines {
if err := m.Start(ctx, name); err != nil {
continue
}
}
}
// StopAll the Goroutine managed by this manager.
func (m *Manager) StopAll(wait bool) {
m.mu.Lock()
goroutines := m.goroutines
m.mu.Unlock()
for name := range goroutines {
if err := m.Stop(name); err != nil {
continue
}
}
for wait {
wait = false
m.mu.Lock()
goroutines = m.goroutines
m.mu.Unlock()
for _, gr := range goroutines {
if gr.Running() {
wait = true
break
}
}
if wait {
time.Sleep(time.Second * 2)
}
}
}
// Status returns the current executions of all Goroutine managed by this manager.
func (m *Manager) Status() map[string]GoroutineStatus {
statuses := map[string]GoroutineStatus{}
for name := range m.goroutines {
status, _ := m.StatusByName(name)
statuses[name] = status
}
return statuses
}
// StatusByName returns the status of a Goroutine by its name, or an error with code GoroutineNotFoundErrorCode.
func (m *Manager) StatusByName(name string) (GoroutineStatus, error) {
gr, err := m.findGoroutineByName(name)
if err != nil {
return GoroutineStatus{}, err
}
return GoroutineStatus{
Name: gr.Name,
Executions: gr.executions,
}, nil
}
// Shutdown requests shutting down the manager and all its Goroutine.
func (m *Manager) Shutdown() {
if m.cancelFunc == nil {
return
}
m.cancelFunc()
m.shuttingDown = true
}
// returns a Goroutine by its name, or returns an error with code GoroutineNotFoundErrorCode.
func (m *Manager) findGoroutineByName(name string) (*managedGoroutine, error) {
m.mu.Lock()
defer m.mu.Unlock()
gr, ok := m.goroutines[name]
if !ok {
return nil, errors.NewWithMessage(GoroutineNotFoundErrorCode, fmt.Sprintf("no goroutine named %s", name))
}
return gr, nil
}
type GoroutineStatus struct {
Name string
Executions []GoroutineExecution
}
// LastExecution returns the last execution of the Goroutine. If this Goroutine is currently running, will return
// the currently running execution.
func (g *GoroutineStatus) LastExecution() (GoroutineExecution, bool) {
nbExecutions := len(g.Executions)
if nbExecutions == 0 {
return GoroutineExecution{}, false
}
return g.Executions[nbExecutions-1], true
}
// FirstExecution returns the first execution of the Goroutine
func (g *GoroutineStatus) FirstExecution() (GoroutineExecution, bool) {
if len(g.Executions) == 0 {
return GoroutineExecution{}, false
}
return g.Executions[0], true
}
// Running indicates if the Goroutine is currently running
func (g *GoroutineStatus) Running() bool {
le, ok := g.LastExecution()
if !ok {
return false
}
return le.Running
}