forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heartbeat.go
65 lines (58 loc) · 1.43 KB
/
heartbeat.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
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/contentsquare/chproxy/config"
)
type heartBeat struct {
interval time.Duration
timeout time.Duration
request string
response string
user string
password string
}
func newHeartBeat(c config.HeartBeat, firstClusterUser config.ClusterUser) *heartBeat {
newHB := &heartBeat{
interval: time.Duration(c.Interval),
timeout: time.Duration(c.Timeout),
request: c.Request,
response: c.Response,
user: firstClusterUser.Name,
password: firstClusterUser.Password,
}
return newHB
}
func (hb *heartBeat) isHealthy(addr string) error {
req, err := http.NewRequest("GET", addr+hb.request, nil)
if err != nil {
return err
}
if hb.user != "" {
req.SetBasicAuth(hb.user, hb.password)
}
ctx, cancel := context.WithTimeout(context.Background(), hb.timeout)
defer cancel()
req = req.WithContext(ctx)
startTime := time.Now()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("cannot send request in %s: %w", time.Since(startTime), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("non-200 status code: %s", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("cannot read response in %s: %w", time.Since(startTime), err)
}
r := string(body)
if r != hb.response {
return fmt.Errorf("unexpected response: %s", r)
}
return nil
}