-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.go
109 lines (91 loc) · 2.53 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
package health
import (
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"runtime"
"github.com/dhawal55/version"
)
// Interface for retrieving health status of various components.
type HealthChecker interface {
IsHealthy() (bool, error, []string)
}
type healthService struct {
healthCheckers []HealthChecker
version string
checksum string
}
type healthCheckResponse struct {
isHealthy bool
OverallHealth string `json:"overallHealth"`
Version string `json:"version"`
Checksum string `json:"checksum"`
Hostname string `json:"hostname"`
GoRoutinesCount int `json:"goRoutinesCount"`
Items []healthCheckItem `json:"items"`
}
type healthCheckItem struct {
Name string `json:"name"`
Status string `json:"status"`
Error string `json:"error"`
Messages []string `json:"messages"`
}
func New(checkers []HealthChecker, v version.Versioner) *http.ServeMux {
service := &healthService{healthCheckers: checkers, version: v.GetVersion(), checksum: version.GetChecksum()}
return service.registerRoute()
}
func (s *healthService) registerRoute() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/health", version.CorsHandler(s))
return mux
}
func (s *healthService) getHealthReport() healthCheckResponse {
var checkItems []healthCheckItem
overall := true
var errmsg string
for _, checker := range s.healthCheckers {
status, err, messages := checker.IsHealthy()
if err != nil {
errmsg = err.Error()
}
item := healthCheckItem{
Name: reflect.TypeOf(checker).String(),
Status: getStatus(status),
Error: errmsg,
Messages: messages,
}
checkItems = append(checkItems, item)
if status == false {
overall = false
fmt.Printf("Service not healthy: %+v\n", item)
}
}
hostname, _ := os.Hostname()
return healthCheckResponse{
Items: checkItems,
isHealthy: overall,
OverallHealth: getStatus(overall),
Version: s.version,
Checksum: s.checksum,
GoRoutinesCount: runtime.NumGoroutine(),
Hostname: hostname,
}
}
func (s *healthService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
report := s.getHealthReport()
statusCode := http.StatusOK
if !report.isHealthy {
statusCode = http.StatusInternalServerError
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(report)
}
func getStatus(status bool) string {
if status {
return "Healthy"
}
return "Unhealthy"
}