-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.go
305 lines (245 loc) · 7.16 KB
/
health.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
package health
import (
"context"
"fmt"
"sort"
"sync"
"time"
)
/*
service can be have other component, but in hole we have two type of components
- requered
- optional
each component must implement Health interface
also each component must register to Global Healther
*/
type HealthComponentStatus int
const (
HealthComponentStatusUnknown HealthComponentStatus = iota
// if configuration is OK and component have all dependens for work and base checked will be done
// component will return HealthStatusOn
HealthComponentStatusOn
// if component disable by default or by configuration - component on check return HealthStatusOff
HealthComponentStatusOff
// if component enable on config and something gose wron, return HealthStatusFail and return description
// error can be return by
// - config - value of config is BAD
// - deps - some address not availability or file not exists or something else more
// - condition - if you component have some smoke test running of start
HealthComponentStatusFail
HealthComponentStatusTimeout
)
func (h HealthComponentStatus) MarshalJSON() ([]byte, error) {
return []byte(`"` + h.String() + `"`), nil
}
var healthComponentsStatus = map[HealthComponentStatus]string{
HealthComponentStatusUnknown: `unknown`,
HealthComponentStatusOn: `on`,
HealthComponentStatusOff: `off`,
HealthComponentStatusFail: `fail`,
HealthComponentStatusTimeout: `timeout`,
}
func (h HealthComponentStatus) String() string {
str, ok := healthComponentsStatus[h]
if !ok {
return `unknown`
}
return str
}
type HealthStatus int
const (
HealthUnknown HealthStatus = iota
HealthServing
HealthNotServing
)
var healthStatuses = []string{
"UNKNOWN",
"SERVING",
"NOT_SERVING",
}
func (h HealthStatus) MarshalJSON() ([]byte, error) {
var msg string
if h < 0 || h > 2 {
msg = healthStatuses[0]
} else {
msg = healthStatuses[h]
}
return []byte(`"` + msg + `"`), nil
}
type HealthComponentState struct {
Status HealthComponentStatus `json:"status"`
// description of status
Description string `json:"description"`
Stats map[string]int `json:"stats"`
}
type Health struct {
Status HealthStatus `json:"status"`
// stats by status
Stats map[string]int `json:"stats"`
Components []HealthComponentDescription `json:"components"`
Duration time.Duration `json:"duration"`
}
type ComponentHealther interface {
Check(ctx context.Context) HealthComponentState
}
type componentPresent int
const (
ComponentPresentRequired componentPresent = iota
ComponentPresentOptional
)
type componentOption struct {
Type componentPresent
}
type Option func(*componentOption)
func SetOptional() Option {
return func(o *componentOption) {
o.Type = ComponentPresentOptional
}
}
func (h *healther) Register(componentName string, health ComponentHealther, opts ...Option) error {
h.regLock.Lock()
defer h.regLock.Unlock()
if _, ok := h.healthers[componentName]; ok {
return fmt.Errorf("component %s already registered", componentName)
}
h.healthers[componentName] = health
comOpt := new(componentOption)
for _, opt := range opts {
opt(comOpt)
}
h.componentOptions[componentName] = comOpt
return nil
}
func (h *healther) UnRegister(componentName string) {
h.regLock.Lock()
defer h.regLock.Unlock()
delete(h.healthers, componentName)
delete(h.componentOptions, componentName)
}
type HealthComponentDescription struct {
ComponentName string `json:"component_name"`
Status HealthComponentStatus `json:"status"`
// description of status
Description string `json:"description"`
Stats map[string]int `json:"stats,omitempty"`
// needed time for check finally status
Duration time.Duration `json:"duration"`
}
func wrapHealthCheck(ctx context.Context, start time.Time, name string, healther ComponentHealther) HealthComponentDescription {
state := healther.Check(ctx)
// if status not OK, please repeat and wait
if state.Status == HealthComponentStatusFail {
select {
case <-ctx.Done():
return HealthComponentDescription{
ComponentName: name,
Status: HealthComponentStatusTimeout,
Description: ctx.Err().Error(),
Duration: time.Since(start),
}
default:
// TODO: add optinos and timeout and repeater
return wrapHealthCheck(ctx, start, name, healther)
}
}
return HealthComponentDescription{
ComponentName: name,
Status: state.Status,
Description: state.Description,
Stats: state.Stats,
Duration: time.Since(start),
}
}
func (h *healther) gatheringStateOfHealth(ctx context.Context) <-chan HealthComponentDescription {
var (
start = time.Now().UTC()
out = make(chan HealthComponentDescription, 0)
wg = new(sync.WaitGroup)
)
h.regLock.RLock()
defer h.regLock.RUnlock()
for componentName, check := range h.healthers {
wg.Add(1)
go func(name string, healther ComponentHealther) {
defer wg.Done()
select {
case <-ctx.Done():
out <- HealthComponentDescription{
ComponentName: name,
Status: HealthComponentStatusTimeout,
Description: ctx.Err().Error(),
Duration: time.Since(start),
}
return
case out <- wrapHealthCheck(ctx, start, name, healther):
}
}(componentName, check)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
type Healther interface {
// Check - gathering state of health registred components and summe result
Check(ctx context.Context) Health
Register(componentName string, health ComponentHealther, opts ...Option) error
UnRegister(componentName string)
}
func New() Healther {
return &healther{
regLock: new(sync.RWMutex),
healthers: make(map[string]ComponentHealther, 0),
componentOptions: make(map[string]*componentOption, 0),
}
}
type healther struct {
regLock *sync.RWMutex
healthers map[string]ComponentHealther
componentOptions map[string]*componentOption
}
// Check - gathering state of health registred components and summe result
func (h *healther) Check(ctx context.Context) Health {
var (
start = time.Now().UTC()
result = Health{
Status: HealthUnknown,
Stats: make(map[string]int, 0),
Components: make([]HealthComponentDescription, 0),
}
)
for healthOfComponent := range h.gatheringStateOfHealth(ctx) {
opt := h.componentOptions[healthOfComponent.ComponentName]
result.Stats[healthOfComponent.Status.String()]++
switch healthOfComponent.Status {
case HealthComponentStatusOff,
HealthComponentStatusFail,
HealthComponentStatusTimeout,
HealthComponentStatusUnknown:
if opt.Type == ComponentPresentRequired {
result.Status = HealthNotServing
}
case HealthComponentStatusOn:
if result.Status == HealthUnknown {
result.Status = HealthServing
}
default:
if opt.Type == ComponentPresentRequired {
result.Status = HealthNotServing
}
}
result.Components = append(result.Components, healthOfComponent)
}
result.Duration = time.Since(start)
if result.Status == HealthUnknown {
if _, ok := result.Stats[HealthComponentStatusOn.String()]; !ok {
result.Status = HealthNotServing
}
}
// sort by latency of component states
sort.Slice(result.Components, func(i, j int) bool {
return result.Components[i].Duration < result.Components[j].Duration
})
return result
}