-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhealth.go
More file actions
75 lines (65 loc) · 2 KB
/
Copy pathhealth.go
File metadata and controls
75 lines (65 loc) · 2 KB
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
// Package health provides HTTP health-check endpoints for the Mantle API server.
package health
import (
"database/sql"
"encoding/json"
"net/http"
)
type response struct {
Status string `json:"status"`
Details map[string]string `json:"details,omitempty"`
}
// LivenessChecker reports whether a component is alive.
type LivenessChecker interface {
IsAlive() bool
Name() string
}
// HealthzHandler returns an HTTP handler that always responds 200 OK, used as
// a liveness probe.
func HealthzHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response{Status: "ok"})
}
}
// ReadyzHandler returns an HTTP handler used as a readiness probe. It pings
// the database and checks each LivenessChecker; it responds 503 if any check
// fails.
func ReadyzHandler(database *sql.DB, checkers ...LivenessChecker) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if database == nil {
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(response{Status: "unavailable"})
return
}
if err := database.PingContext(r.Context()); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(response{Status: "unavailable"})
return
}
// Check liveness of registered components.
details := make(map[string]string)
allAlive := true
for _, c := range checkers {
if c.IsAlive() {
details[c.Name()] = "ok"
} else {
details[c.Name()] = "degraded"
allAlive = false
}
}
if !allAlive {
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(response{Status: "degraded", Details: details})
return
}
w.WriteHeader(http.StatusOK)
if len(details) > 0 {
json.NewEncoder(w).Encode(response{Status: "ok", Details: details})
} else {
json.NewEncoder(w).Encode(response{Status: "ok"})
}
}
}