-
Notifications
You must be signed in to change notification settings - Fork 947
/
Copy pathhealth_check.go
457 lines (401 loc) · 11.6 KB
/
health_check.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright (c) 2019 The BFE Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// health check for backend
package backend
import (
"crypto/x509"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/baidu/go-lib/log"
"github.com/bfenetworks/bfe/bfe_config/bfe_cluster_conf/cluster_conf"
"github.com/bfenetworks/bfe/bfe_debug"
"github.com/bfenetworks/bfe/bfe_tls"
)
type checkRtn struct {
ok bool
err error
}
func UpdateStatus(backend *BfeBackend, cluster string) bool {
var (
checkConf *cluster_conf.BackendCheck
httpsConf *cluster_conf.BackendHTTPS
)
// get conf of health check, which is separately stored for each cluster
checkConf, httpsConf = getCheckConf(cluster)
if checkConf == nil {
// just ignore if not found health check conf
return false
}
// UpdateStatus update backend status.
// if backend's status become fail, start healthcheck.
// at most start 1 check goroutine for each backend.
if backend.UpdateStatus(*checkConf.FailNum) {
go check(backend, cluster, httpsConf)
return true
}
return false
}
func check(backend *BfeBackend, cluster string, httpsConf *cluster_conf.BackendHTTPS) {
log.Logger.Info("start healthcheck for %s", backend.Name)
// backend close chan
c := backend.CloseChan()
loop:
for {
select {
case <-c: // backend deleted
break loop
default:
}
// get the latest conf to do health check
checkConf, _ := getCheckConf(cluster)
if checkConf == nil {
// never come here
time.Sleep(time.Second)
continue
}
checkInterval := time.Duration(*checkConf.CheckInterval) * time.Millisecond
// health check
if ok, err := CheckConnect(backend, checkConf, httpsConf); !ok {
backend.ResetSuccNum()
if bfe_debug.DebugHealthCheck {
log.Logger.Debug("backend %s still not avail (check failure: %s)", backend.Name, err)
}
time.Sleep(checkInterval)
continue
}
// check whether backend becomes available
backend.AddSuccNum()
if !backend.CheckAvail(*checkConf.SuccNum) {
if bfe_debug.DebugHealthCheck {
log.Logger.Debug("backend %s still not avail (check success, waiting for more checks)", backend.Name)
}
time.Sleep(checkInterval)
continue
}
log.Logger.Info("backend %s back to Normal", backend.Name)
backend.SetRestart(true)
backend.SetAvail(true)
break loop
}
}
func getHealthCheckAddrInfo(backend *BfeBackend, checkConf *cluster_conf.BackendCheck) string {
if checkConf.Host != nil {
// if port for health check is configured, use it instead of backend port
hostInfo := strings.Split(*checkConf.Host, ":")
if len(hostInfo) == 2 {
port := hostInfo[1]
return fmt.Sprintf("%s:%s", backend.GetAddr(), port)
}
}
return backend.GetAddrInfo()
}
func checkTCPConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck) (bool, error) {
addrInfo := getHealthCheckAddrInfo(backend, checkConf)
var conn net.Conn
var err error
if checkConf.CheckTimeout != nil {
conn, err = net.DialTimeout("tcp", addrInfo,
time.Duration(*checkConf.CheckTimeout)*time.Millisecond)
} else {
conn, err = net.Dial("tcp", addrInfo)
}
if err != nil {
return false, err
}
conn.Close()
return true, nil
}
func doHTTPHealthCheck(request *http.Request, timeout time.Duration) (int, error) {
client := &http.Client{
// Note: disable following an HTTP redirect
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
// Note: timeout of zero means no timeout
Timeout: timeout,
}
response, err := client.Do(request)
if err != nil {
return -1, err
}
defer response.Body.Close()
return response.StatusCode, nil
}
// extractIP extract ip address
func extractIP(rsAddr string) string {
if strings.HasPrefix(rsAddr, "[") {
// IPv6
endIndex := strings.LastIndex(rsAddr, "]")
if endIndex == -1 {
return ""
}
ip := rsAddr[:endIndex+1]
if net.ParseIP(ip[1:endIndex]) == nil {
return ""
}
return ip
} else {
// IPv4
ip := strings.Split(rsAddr, ":")[0]
if net.ParseIP(ip) == nil {
return ""
}
return ip
}
}
func getHostByType(host, rsAddr, hostType *string, def string) string {
if hostType == nil {
ht := cluster_conf.HostType_HOST
hostType = &ht
}
switch *hostType {
case cluster_conf.HostType_Instance_IP:
if rsAddr != nil {
return extractIP(*rsAddr)
}
default:
if host != nil {
return *host
}
}
return def
}
func checkHTTPSConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck, httpsConf *cluster_conf.BackendHTTPS) (bool, error) {
var (
err error
conn net.Conn
addrInfo = getHealthCheckAddrInfo(backend, checkConf)
checkTimeout = 30 * time.Second
statusCode = 0
host string
rootCAs *x509.CertPool = nil
certs []bfe_tls.Certificate = nil
cert bfe_tls.Certificate
insecure = false
uri = "/"
checkRtnCh = make(chan checkRtn, 1)
rtn checkRtn
)
var (
getStatusCodeFn = func(statusLine string) (int, error) {
// "HTTP/1.1 200 OK"
re, err := regexp.Compile(`\s(\d{3})\s`)
if err != nil {
return 0, err
}
matches := re.FindStringSubmatch(statusLine)
if len(matches) == 2 {
statusCode := matches[1]
log.Logger.Debug("StatusCode = %s, raw = %s", statusCode, statusLine)
return strconv.Atoi(statusCode)
} else {
return 0, fmt.Errorf("Status code not found: %s", statusLine)
}
}
doCheckFn = func(conn net.Conn) checkRtn {
// Set timeout
timeout := 3 * time.Second
err = conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
return checkRtn{false, err}
}
// TLS Check
if err = conn.(*bfe_tls.Conn).Handshake(); err != nil {
log.Logger.Debug("debug_https err=%s", err.Error())
return checkRtn{false, err}
}
if *checkConf.Schem == "tls" {
return checkRtn{true, nil}
}
// HTTPS Check
if checkConf.Uri != nil && *checkConf.Uri != "" {
uri = *checkConf.Uri
}
request := fmt.Sprintf("GET %s HTTP/1.1\r\n"+
"Host: %s\r\n"+
"User-Agent: BFE-Health-Check\r\n"+
"\r\n", uri, host)
_, err = conn.Write([]byte(request))
if err != nil {
log.Logger.Debug("debug_https err=%s", err.Error())
return checkRtn{false, err}
}
var (
response = ""
ok bool
err error
data = make([]byte, 0)
bufSz = 128
buf = make([]byte, bufSz)
total = 0
)
for {
total, err = conn.Read(buf)
if err != nil {
break
}
data = append(data, buf[:total]...)
if total < bufSz {
break
}
}
if err != nil {
log.Logger.Debug("debug_https err=%s", err.Error())
return checkRtn{false, err}
}
response = string(data)
log.Logger.Debug("<- Request:\n%s", request)
log.Logger.Debug("-> Response:\n%s", response)
if checkConf.StatusCode != nil { // check status code
var (
s string
arr = strings.Split(response, "\n")
)
if len(arr) > 0 {
s = strings.ToUpper(arr[0])
statusCode, err = getStatusCodeFn(s)
if err != nil {
return checkRtn{false, err}
}
if checkConf.StatusCodeRange != nil && *checkConf.StatusCodeRange != "" {
log.Logger.Debug("statusCode=%d, statusCodeRange=%s", statusCode, *checkConf.StatusCodeRange)
ok, err := cluster_conf.MatchStatusCodeRange(fmt.Sprintf("%d", statusCode), *checkConf.StatusCodeRange)
return checkRtn{ok, err}
}
}
ok, err = cluster_conf.MatchStatusCode(statusCode, *checkConf.StatusCode)
}
return checkRtn{ok, err}
}
toStringFn = func(o interface{}) string {
b, err := json.Marshal(o)
if err != nil {
return err.Error()
}
return string(b)
}
)
if checkConf.CheckTimeout != nil {
checkTimeout = time.Duration(*checkConf.CheckTimeout) * time.Millisecond
}
conn, err = net.DialTimeout("tcp", addrInfo, checkTimeout)
if err != nil {
log.Logger.Debug("debug_https err=%v", err)
return false, err
}
defer func() {
if r := recover(); r != nil {
log.Logger.Debug("recover_panic = %v", r)
}
_ = conn.Close()
}()
_, err = url.Parse(fmt.Sprintf("%s://%s%s", "https", addrInfo, *checkConf.Uri))
if err != nil {
log.Logger.Debug("debug_https err=%v", err)
return false, err
}
serverName := ""
if httpsConf.RSHost != nil {
serverName = *httpsConf.RSHost
} else if checkConf.Host != nil {
serverName = *checkConf.Host
}
host = getHostByType(checkConf.Host, &addrInfo, checkConf.HostType, serverName)
rootCAs, err = httpsConf.GetRSCAList()
if cert, err = httpsConf.GetBFECert(); err == nil {
certs = []bfe_tls.Certificate{cert}
}
if httpsConf.RSInsecureSkipVerify != nil {
insecure = *httpsConf.RSInsecureSkipVerify
}
conn = bfe_tls.Client(conn, &bfe_tls.Config{
Certificates: certs,
InsecureSkipVerify: true,
ServerName: host,
RootCAs: rootCAs,
VerifyPeerCertificate: bfe_tls.NewVerifyPeerCertHooks(insecure, host, rootCAs).Ready(),
})
log.Logger.Debug("httpsCheck conf=%s", toStringFn(checkConf))
go func(conn net.Conn, rtnCh chan checkRtn) {
rtnCh <- doCheckFn(conn)
}(conn, checkRtnCh)
if checkTimeout > 0 {
select {
case rtn = <-checkRtnCh:
return rtn.ok, rtn.err
case <-time.Tick(checkTimeout):
return false, fmt.Errorf("https checkTimeout %dms", checkTimeout/time.Millisecond)
}
} else {
rtn = <-checkRtnCh
}
return rtn.ok, rtn.err
}
func checkHTTPConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck) (bool, error) {
// prepare health check request
addrInfo := getHealthCheckAddrInfo(backend, checkConf)
urlStr := fmt.Sprintf("%s://%s%s", "http", addrInfo, *checkConf.Uri)
request, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return false, err
}
// modify http host header if needed
if checkConf.Host != nil {
request.Host = *checkConf.Host
}
// add headers required by downstream servers
request.Header.Set("Accept", "*/*")
// do http health check
checkTimeout := time.Duration(0)
if checkConf.CheckTimeout != nil {
checkTimeout = time.Duration(*checkConf.CheckTimeout) * time.Millisecond
}
statusCode, err := doHTTPHealthCheck(request, checkTimeout)
if err != nil {
return false, err
}
return cluster_conf.MatchStatusCode(statusCode, *checkConf.StatusCode)
}
// CheckConnect checks whether backend server become available.
func CheckConnect(backend *BfeBackend, checkConf *cluster_conf.BackendCheck, httpsConf *cluster_conf.BackendHTTPS) (bool, error) {
switch *checkConf.Schem {
case "http":
return checkHTTPConnect(backend, checkConf)
case "tcp":
return checkTCPConnect(backend, checkConf)
case "https", "tls":
return checkHTTPSConnect(backend, checkConf, httpsConf)
default:
// never come here
return checkHTTPConnect(backend, checkConf)
}
}
// CheckConfFetcher returns current health check conf for cluster.
type CheckConfFetcher func(name string) (*cluster_conf.BackendCheck, *cluster_conf.BackendHTTPS)
var checkConfFetcher CheckConfFetcher
func getCheckConf(cluster string) (*cluster_conf.BackendCheck, *cluster_conf.BackendHTTPS) {
if checkConfFetcher == nil {
return nil, nil
}
return checkConfFetcher(cluster)
}
// SetCheckConfFetcher initializes CheckConfFetcher handler.
func SetCheckConfFetcher(confFetcher CheckConfFetcher) {
checkConfFetcher = confFetcher
}