-
Notifications
You must be signed in to change notification settings - Fork 4
/
supervisor.go
182 lines (170 loc) · 4.52 KB
/
supervisor.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
package supervisor
import (
"context"
"fmt"
"path"
"reflect"
"runtime/debug"
"time"
"github.com/go-logr/logr"
"go.einride.tech/clock"
"go.einride.tech/clock/systemclock"
)
// Config contains the full set of dependencies for a supervisor.
type Config struct {
Services []Service
StatusUpdateListeners []func([]StatusUpdate)
RestartInterval time.Duration
Clock clock.Clock
Logger logr.Logger
}
type supervisedService struct {
service Service
id int
name string
}
type Supervisor struct {
cfg *Config
statusUpdateChan chan StatusUpdate
// immutable, initialized by constructor
supervisedServices []*supervisedService
// mutable, only accessible by the supervisor thread
latestStatusUpdates []StatusUpdate
}
// New creates a new supervisor from a config.
func New(cfg *Config) *Supervisor {
s := &Supervisor{
cfg: cfg,
statusUpdateChan: make(chan StatusUpdate),
}
if cfg.Clock == nil {
s.cfg.Clock = systemclock.New()
}
if cfg.Logger.GetSink() == nil {
s.cfg.Logger = logr.Discard()
}
cfg.Logger = cfg.Logger.WithName("supervisor")
var id int
for _, service := range cfg.Services {
if service != nil && !reflect.ValueOf(service).IsNil() {
s.supervisedServices = append(s.supervisedServices, &supervisedService{
service: service,
id: id,
name: serviceName(service),
})
id++
}
}
s.latestStatusUpdates = make([]StatusUpdate, len(s.supervisedServices))
return s
}
// Run the supervisor and all its services.
func (s *Supervisor) Run(ctx context.Context) error {
// start all services
for _, ss := range s.supervisedServices {
s.start(ctx, ss)
}
s.notifyListeners()
// monitor running services
restartTicker := s.cfg.Clock.NewTicker(s.cfg.RestartInterval)
restartTickChan := restartTicker.C()
ctxDone := ctx.Done()
for {
select {
case <-restartTickChan:
for id, update := range s.latestStatusUpdates {
if !update.Status.IsAlive() {
s.cfg.Logger.Info("restarting service", "update", update)
s.start(ctx, s.supervisedServices[id])
s.notifyListeners()
}
}
case update := <-s.statusUpdateChan:
s.handleStatusUpdate(update)
case <-ctxDone:
restartTicker.Stop()
for isAnyAlive(s.latestStatusUpdates) {
for _, u := range s.latestStatusUpdates {
if u.Status.IsAlive() {
s.cfg.Logger.V(1).Info("service alive", "update", u)
}
}
s.handleStatusUpdate(<-s.statusUpdateChan) // TODO: add a timeout
}
return nil // TODO: error if any service failed
}
}
}
func (s *Supervisor) handleStatusUpdate(update StatusUpdate) {
if update.Err == nil {
s.cfg.Logger.V(1).Info("received status", "update", update)
} else {
s.cfg.Logger.Error(update.Err, "received error status", "update", update)
}
s.latestStatusUpdates[update.ServiceID] = update
s.notifyListeners()
}
func (s *Supervisor) start(ctx context.Context, ss *supervisedService) {
s.latestStatusUpdates[ss.id] = StatusUpdate{
ServiceID: ss.id,
ServiceName: ss.name,
Time: s.cfg.Clock.Now(),
Status: StatusIdle,
}
go func() {
defer func() {
if r := recover(); r != nil {
s.statusUpdateChan <- StatusUpdate{
ServiceID: ss.id,
ServiceName: ss.name,
Time: s.cfg.Clock.Now(),
Status: StatusPanic,
Err: fmt.Errorf("%v: %s", r, string(debug.Stack())),
}
}
}()
s.statusUpdateChan <- StatusUpdate{
ServiceID: ss.id,
ServiceName: ss.name,
Time: s.cfg.Clock.Now(),
Status: StatusRunning,
}
err := ss.service.Run(logr.NewContext(ctx, s.cfg.Logger.WithValues("service", ss.name)))
status := StatusStopped
if err != nil {
status = StatusError
}
s.statusUpdateChan <- StatusUpdate{
ServiceID: ss.id,
ServiceName: ss.name,
Time: s.cfg.Clock.Now(),
Status: status,
Err: err,
}
}()
}
func (s *Supervisor) notifyListeners() {
if len(s.cfg.StatusUpdateListeners) == 0 {
return
}
result := make([]StatusUpdate, len(s.latestStatusUpdates))
copy(result, s.latestStatusUpdates)
for _, listener := range s.cfg.StatusUpdateListeners {
listener(result)
}
}
func isAnyAlive(statusUpdates []StatusUpdate) bool {
for _, statusUpdate := range statusUpdates {
if statusUpdate.Status.IsAlive() {
return true
}
}
return false
}
func serviceName(service Service) string {
if stringer, ok := service.(fmt.Stringer); ok {
return stringer.String()
}
t := reflect.Indirect(reflect.ValueOf(service)).Type()
return fmt.Sprintf("%s.%s", path.Base(t.PkgPath()), t.Name())
}