-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.go
74 lines (64 loc) · 1.6 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
package miso
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
const (
ServiceStatusUp = "UP"
ServiceStatusDown = "DOWN"
)
// Indicator of health status
type HealthIndicator struct {
Name string // name of the indicator
CheckHealth func(rail Rail) bool // Check health
}
type HealthStatus struct {
Name string
Healthy bool
}
type aggregatedHealthIndicator struct {
sync.RWMutex
indicators []HealthIndicator
}
var (
aggIndi = aggregatedHealthIndicator{indicators: make([]HealthIndicator, 0, 10)}
)
// Add health indicator.
func AddHealthIndicator(hi HealthIndicator) {
aggIndi.Lock()
defer aggIndi.Unlock()
aggIndi.indicators = append(aggIndi.indicators, hi)
}
// Check health status.
func CheckHealth(rail Rail) []HealthStatus {
aggIndi.RLock()
defer aggIndi.RUnlock()
hs := make([]HealthStatus, 0, len(aggIndi.indicators))
for i := range aggIndi.indicators {
indi := aggIndi.indicators[i]
start := time.Now()
hs = append(hs, HealthStatus{
Healthy: indi.CheckHealth(rail),
Name: indi.Name,
})
rail.Debugf("HealthIndicator %v took %v", indi.Name, time.Since(start))
}
return hs
}
// Create a default health check endpoint that simply doesn't nothing except returing 200
func DefaultHealthCheck(ctx *gin.Context) {
rail := EmptyRail()
hs := CheckHealth(rail)
for i := range hs {
s := hs[i]
if !s.Healthy {
rail.Warnf("Component %s is down, healthcheck failed", s.Name)
ctx.String(http.StatusServiceUnavailable, ServiceStatusDown)
return
}
}
rail.Debugf("Service healthcheck pass")
ctx.String(http.StatusOK, ServiceStatusUp)
}