/
health.go
157 lines (134 loc) · 3.38 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
package sohop
import (
"crypto/tls"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
)
var healthClient = createHealthClient()
const certWarning = 72 * time.Hour
func createHealthClient() *http.Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: tr,
Timeout: 5 * time.Second,
}
return client
}
type healthStatus struct {
Response string `json:"response"`
LatencyMS time.Duration `json:"latency_ms"`
}
type healthReport struct {
sync.RWMutex
response []byte
allOk bool
}
func (s Server) performCheck() {
s.health.Lock()
defer s.health.Unlock()
allOk := true
responses := make(map[string]healthStatus)
var lock sync.Mutex // responses
var wg sync.WaitGroup
for k, v := range s.Config.Upstreams {
k := k
v := v
wg.Add(1)
go func() {
defer wg.Done()
healthCheck := v.HealthCheck
if healthCheck == "" {
healthCheck = v.URL
}
start := time.Now()
resp, err := healthClient.Get(healthCheck)
elapsed := time.Since(start) / time.Millisecond
lock.Lock()
defer lock.Unlock()
if err == nil {
responses[k] = healthStatus{Response: resp.Status, LatencyMS: elapsed}
if resp.StatusCode != 200 {
allOk = false
}
} else {
responses[k] = healthStatus{Response: err.Error(), LatencyMS: elapsed}
allOk = false
}
}()
}
var certResponse map[string]interface{}
if s.Config.TLS.CertFile != "" {
certResponse = make(map[string]interface{}, 5)
wg.Add(1)
go func() {
defer wg.Done()
data, err := ioutil.ReadFile(s.Config.TLS.CertFile)
if err != nil {
certResponse["ok"] = false
certResponse["error"] = err.Error()
return
}
notBefore, notAfter, err := certValidity(data)
if err != nil {
certResponse["ok"] = false
certResponse["error"] = err.Error()
return
}
certResponse["expires_at"] = notAfter
now := time.Now()
if !notBefore.Before(now) {
certResponse["error"] = "not yet valid"
certResponse["valid_at"] = notBefore
certResponse["ok"] = false
} else if !notAfter.After(now) {
certResponse["error"] = "expired"
certResponse["ok"] = false
} else if !notAfter.Add(-1 * certWarning).After(now) {
certResponse["expires_in"] = notAfter.Sub(now).String()
certResponse["error"] = "expires soon"
certResponse["ok"] = false
} else {
certResponse["ok"] = true
}
}()
}
wg.Wait()
if certResponse != nil {
allOk = allOk && certResponse["ok"].(bool)
}
res, err := json.MarshalIndent(struct {
Upstreams map[string]healthStatus `json:"upstreams"`
Cert map[string]interface{} `json:"cert,omitempty"`
}{
Upstreams: responses,
Cert: certResponse,
}, "", " ")
if err != nil {
s.health.response = []byte("internal server error")
s.health.allOk = false
log.Print(err)
return
}
s.health.allOk = allOk
s.health.response = res
}
// HealthHandler checks each upstream and considers them healthy if they return
// a 200 response. Also, the health check will fail if the TLS certificate will
// expire within 72 hours.
func (s Server) HealthHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.health.RLock()
defer s.health.RUnlock()
w.Header().Add("Content-Type", "application/json; charset=UTF-8")
if !s.health.allOk {
w.WriteHeader(503)
}
w.Write(s.health.response)
})
}