-
Notifications
You must be signed in to change notification settings - Fork 60
/
health.go
272 lines (222 loc) · 6.21 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
package health
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime"
"sync"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// Status type represents health status
type Status string
// Possible health statuses
const (
StatusOK Status = "OK"
StatusPartiallyAvailable Status = "Partially Available"
StatusUnavailable Status = "Unavailable"
StatusTimeout Status = "Timeout during health check"
)
type (
// CheckFunc is the func which executes the check.
CheckFunc func(context.Context) error
// Config carries the parameters to run the check.
Config struct {
// Name is the name of the resource to be checked.
Name string
// Timeout is the timeout defined for every check.
Timeout time.Duration
// SkipOnErr if set to true, it will retrieve StatusOK providing the error message from the failed resource.
SkipOnErr bool
// Check is the func which executes the check.
Check CheckFunc
}
// Check represents the health check response.
Check struct {
// Status is the check status.
Status Status `json:"status"`
// Timestamp is the time in which the check occurred.
Timestamp time.Time `json:"timestamp"`
// Failures holds the failed checks along with their messages.
Failures map[string]string `json:"failures,omitempty"`
// System holds information of the go process.
*System `json:"system,omitempty"`
// Component holds information on the component for which checks are made
Component `json:"component"`
}
// System runtime variables about the go process.
System struct {
// Version is the go version.
Version string `json:"version"`
// GoroutinesCount is the number of the current goroutines.
GoroutinesCount int `json:"goroutines_count"`
// TotalAllocBytes is the total bytes allocated.
TotalAllocBytes int `json:"total_alloc_bytes"`
// HeapObjectsCount is the number of objects in the go heap.
HeapObjectsCount int `json:"heap_objects_count"`
// TotalAllocBytes is the bytes allocated and not yet freed.
AllocBytes int `json:"alloc_bytes"`
}
// Component descriptive values about the component for which checks are made
Component struct {
// Name is the name of the component.
Name string `json:"name"`
// Version is the component version.
Version string `json:"version"`
}
// Health is the health-checks container
Health struct {
mu sync.Mutex
checks map[string]Config
maxConcurrent int
tp trace.TracerProvider
instrumentationName string
component Component
systemInfoEnabled bool
}
)
// New instantiates and build new health check container
func New(opts ...Option) (*Health, error) {
h := &Health{
checks: make(map[string]Config),
tp: trace.NewNoopTracerProvider(),
maxConcurrent: runtime.NumCPU(),
}
for _, o := range opts {
if err := o(h); err != nil {
return nil, err
}
}
return h, nil
}
// Register registers a check config to be performed.
func (h *Health) Register(c Config) error {
if c.Timeout == 0 {
c.Timeout = time.Second * 2
}
if c.Name == "" {
return errors.New("health check must have a name to be registered")
}
h.mu.Lock()
defer h.mu.Unlock()
if _, ok := h.checks[c.Name]; ok {
return fmt.Errorf("health check %q is already registered", c.Name)
}
h.checks[c.Name] = c
return nil
}
// Handler returns an HTTP handler (http.HandlerFunc).
func (h *Health) Handler() http.Handler {
return http.HandlerFunc(h.HandlerFunc)
}
// HandlerFunc is the HTTP handler function.
func (h *Health) HandlerFunc(w http.ResponseWriter, r *http.Request) {
c := h.Measure(r.Context())
w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(c)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
code := http.StatusOK
if c.Status == StatusUnavailable {
code = http.StatusServiceUnavailable
}
w.WriteHeader(code)
w.Write(data)
}
// Measure runs all the registered health checks and returns summary status
func (h *Health) Measure(ctx context.Context) Check {
h.mu.Lock()
defer h.mu.Unlock()
tracer := h.tp.Tracer(h.instrumentationName)
ctx, span := tracer.Start(
ctx,
"health.Measure",
trace.WithAttributes(attribute.Int("checks", len(h.checks))),
)
defer span.End()
status := StatusOK
failures := make(map[string]string)
limiterCh := make(chan bool, h.maxConcurrent)
defer close(limiterCh)
var (
wg sync.WaitGroup
mu sync.Mutex
)
for _, c := range h.checks {
limiterCh <- true
wg.Add(1)
go func(c Config) {
ctx, span := tracer.Start(ctx, c.Name)
defer func() {
span.End()
<-limiterCh
wg.Done()
}()
resCh := make(chan error)
go func() {
resCh <- c.Check(ctx)
defer close(resCh)
}()
timeout := time.NewTimer(c.Timeout)
select {
case <-timeout.C:
mu.Lock()
defer mu.Unlock()
span.SetStatus(codes.Error, string(StatusTimeout))
failures[c.Name] = string(StatusTimeout)
status = getAvailability(status, c.SkipOnErr)
case res := <-resCh:
if !timeout.Stop() {
<-timeout.C
}
mu.Lock()
defer mu.Unlock()
if res != nil {
span.RecordError(res)
failures[c.Name] = res.Error()
status = getAvailability(status, c.SkipOnErr)
}
}
}(c)
}
wg.Wait()
span.SetAttributes(attribute.String("status", string(status)))
var systemMetrics *System
if h.systemInfoEnabled {
systemMetrics = newSystemMetrics()
}
return newCheck(h.component, status, systemMetrics, failures)
}
func newCheck(c Component, s Status, system *System, failures map[string]string) Check {
return Check{
Status: s,
Timestamp: time.Now(),
Failures: failures,
System: system,
Component: c,
}
}
func newSystemMetrics() *System {
s := runtime.MemStats{}
runtime.ReadMemStats(&s)
return &System{
Version: runtime.Version(),
GoroutinesCount: runtime.NumGoroutine(),
TotalAllocBytes: int(s.TotalAlloc),
HeapObjectsCount: int(s.HeapObjects),
AllocBytes: int(s.Alloc),
}
}
func getAvailability(s Status, skipOnErr bool) Status {
if skipOnErr && s != StatusUnavailable {
return StatusPartiallyAvailable
}
return StatusUnavailable
}