This repository has been archived by the owner on Apr 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
267 lines (225 loc) · 6.17 KB
/
monitor.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
package monitor
import (
"errors"
"fmt"
"sync"
"time"
)
// Monitor contains internal go-health internal structures.
type Monitor struct {
// StatusListener will report failures and recoveries
StatusListener StatusListener
// RandomStartTimeMillis returns a random delay to wait before starting the checks (one for each check)
RandomStartTimeMillis func() int
configs []*Config
states map[string]State
statesLock sync.Mutex
runnersLock sync.Mutex
runners map[string]chan struct{} // contains map of active runners w/ a stop channel
started bool
}
// New returns a new instance of the Monitor struct.
func New() *Monitor {
return &Monitor{
configs: make([]*Config, 0),
states: make(map[string]State, 0),
runners: make(map[string]chan struct{}, 0),
statesLock: sync.Mutex{},
runnersLock: sync.Mutex{},
RandomStartTimeMillis: func() int {
return 0
},
}
}
// AddCheck is used for adding a single check definition to the current health instance.
func (h *Monitor) AddCheck(cfg ...*Config) error {
for _, existing := range h.configs {
for _, c := range cfg {
if c.Name == existing.Name {
return fmt.Errorf("config with name %s already exists", c.Name)
}
}
}
h.configs = append(h.configs, cfg...)
return nil
}
func (h *Monitor) RemoveCheck(cfg *Config) error {
for idx, existing := range h.configs {
if cfg.Name == existing.Name {
if h.started {
if err := h.StopCheck(cfg.Name); err != nil {
return err
}
fmt.Printf("stopped check %s\n", cfg.Name)
}
h.configs = append(h.configs[:idx], h.configs[idx+1:]...)
fmt.Printf("removed check %s\n", cfg.Name)
return nil
}
}
return fmt.Errorf("no check found with name %s", cfg.Name)
}
// Start will start all of the defined health checks. Each of the checks run in
// their own goroutines (as "time.Ticker").
func (h *Monitor) Start() error {
if h.started {
return errors.New("monitor already started")
}
h.started = true
for _, c := range h.configs {
h.startRunnerForConfig(c)
}
return nil
}
func (h *Monitor) startRunnerForConfig(c *Config) {
stop := make(chan struct{})
h.startRunner(c, stop)
h.runnersLock.Lock()
defer h.runnersLock.Unlock()
h.runners[c.Name] = stop
fmt.Printf("started check %s\n", c.Name)
}
func (h *Monitor) StopCheck(name string) error {
h.runnersLock.Lock()
defer h.runnersLock.Unlock()
if stop := h.runners[name]; stop != nil {
fmt.Printf("stopping check %s\n", name)
close(stop)
delete(h.runners, name)
} else {
return fmt.Errorf("failed to find check with name %s", name)
}
// Reset state
h.statesLock.Lock()
defer h.statesLock.Unlock()
delete(h.states, name)
return nil
}
func (h *Monitor) StartCheck(name string) error {
var found *Config
for _, existing := range h.configs {
if name == existing.Name {
found = existing
}
}
if found == nil {
return fmt.Errorf("failed to find check with name %s", name)
}
if stop := h.runners[name]; stop != nil {
return fmt.Errorf("check already running")
} else {
h.startRunnerForConfig(found)
}
return nil
}
// Stop will cause all of the running health checks to be stopped. Additionally,
// all existing check states will be reset.
func (h *Monitor) Stop() error {
for name, stop := range h.runners {
fmt.Printf("Stopping check %s\n", name)
close(stop)
}
time.Sleep(time.Second)
// Reset runner map
h.runners = make(map[string]chan struct{}, 0)
// Reset states
h.safeResetStates()
h.started = false
return nil
}
func (h *Monitor) State() (map[string]State, error) {
return h.safeGetStates(), nil
}
func (h *Monitor) startRunner(cfg *Config,
stop <-chan struct{}) {
checkFunc := func() {
data, err := cfg.Checker.Status()
stateEntry := &State{
Name: cfg.Name,
Status: "ok",
Details: data,
CheckTime: time.Now(),
}
if err != nil {
fmt.Printf("check %s has failed with error %v\n", cfg.Name, err)
stateEntry.Err = err.Error()
stateEntry.Status = "failed"
}
h.safeUpdateState(stateEntry)
if cfg.OnComplete != nil {
go cfg.OnComplete(stateEntry)
}
}
go func() {
time.Sleep(time.Duration(h.RandomStartTimeMillis()) * time.Millisecond)
fmt.Printf("%s Starting check %s\n", time.Now(), cfg.Name)
ticker := time.NewTicker(cfg.Interval)
defer ticker.Stop()
checkFunc()
RunLoop:
for {
select {
case <-ticker.C:
checkFunc()
case <-stop:
break RunLoop
}
}
}()
}
// resets the states in a concurrency-safe manner
func (h *Monitor) safeResetStates() {
h.statesLock.Lock()
defer h.statesLock.Unlock()
h.states = make(map[string]State, 0)
}
// updates the check state in a concurrency-safe manner
func (h *Monitor) safeUpdateState(stateEntry *State) {
// dispatch any status listeners
h.handleStatusListener(stateEntry)
// update states here
h.statesLock.Lock()
defer h.statesLock.Unlock()
h.states[stateEntry.Name] = *stateEntry
}
// get all states in a concurrency-safe manner
func (h *Monitor) safeGetStates() map[string]State {
h.statesLock.Lock()
defer h.statesLock.Unlock()
// deep copy h.states to avoid race
statesCopy := make(map[string]State, 0)
for k, v := range h.states {
statesCopy[k] = v
}
return statesCopy
}
// if a status listener is attached
func (h *Monitor) handleStatusListener(stateEntry *State) {
// get the previous state
h.statesLock.Lock()
prevState := h.states[stateEntry.Name]
h.statesLock.Unlock()
// state is failure
if stateEntry.isFailure() {
if !prevState.isFailure() {
// new failure: previous state was ok
if h.StatusListener != nil {
go h.StatusListener.CheckFailed(stateEntry)
}
stateEntry.TimeOfFirstFailure = time.Now()
} else {
// carry the time of first failure from the previous state
stateEntry.TimeOfFirstFailure = prevState.TimeOfFirstFailure
if h.StatusListener != nil {
go h.StatusListener.StillFailing(stateEntry, prevState.ContiguousFailures)
}
}
stateEntry.ContiguousFailures = prevState.ContiguousFailures + 1
} else if prevState.isFailure() {
// recovery, previous state was failure
failureSeconds := time.Now().Sub(prevState.TimeOfFirstFailure).Seconds()
if h.StatusListener != nil {
go h.StatusListener.CheckRecovered(stateEntry, prevState.ContiguousFailures, failureSeconds)
}
}
}