-
Notifications
You must be signed in to change notification settings - Fork 36
/
http.go
76 lines (62 loc) · 1.8 KB
/
http.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
package probe
import (
"io"
"net/http"
"sync/atomic"
"github.com/bnb-chain/greenfield-storage-provider/pkg/log"
)
type check func() bool
// HTTPProbe represents health and readiness status of given component, and provides HTTP integration.
type HTTPProbe struct {
ready atomic.Uint32
healthy atomic.Uint32
}
// NewHTTPProbe returns HTTPProbe representing readiness and liveness of given component.
func NewHTTPProbe() *HTTPProbe {
return &HTTPProbe{}
}
// HealthyHandler returns an HTTP Handler which responds health checks.
func (p *HTTPProbe) HealthyHandler() http.HandlerFunc {
return p.handler(p.IsHealthy)
}
// ReadyHandler returns an HTTP handler which responds readiness checks.
func (p *HTTPProbe) ReadyHandler() http.HandlerFunc {
return p.handler(p.IsReady)
}
func (p *HTTPProbe) handler(c check) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
if !c() {
http.Error(w, "NOT OK", http.StatusServiceUnavailable)
return
}
if _, err := io.WriteString(w, "OK"); err != nil {
log.Errorw("failed to write probe response", "error", err)
}
}
}
// IsReady returns true if component is ready.
func (p *HTTPProbe) IsReady() bool {
value := p.ready.Load()
return value > 0
}
// IsHealthy returns true if component is healthy.
func (p *HTTPProbe) IsHealthy() bool {
value := p.healthy.Load()
return value > 0
}
// Ready sets components status to ready.
func (p *HTTPProbe) Ready() {
p.ready.Swap(1)
}
// Unready sets components status to unready with given error as a cause.
func (p *HTTPProbe) Unready(err error) {
p.ready.Swap(0)
}
// Healthy sets components status to healthy.
func (p *HTTPProbe) Healthy() {
p.healthy.Swap(1)
}
// Unhealthy sets components status to unhealthy with given error as a cause.
func (p *HTTPProbe) Unhealthy(err error) {
p.healthy.Swap(0)
}