-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwork.go
94 lines (76 loc) · 1.9 KB
/
work.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
package main
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"github.com/gojektech/heimdall/httpclient"
)
const unhealthyNodeWeight = 0
const healthyNodeWeight = 100
type pinger struct {
client Client
pingClient *httpclient.Client
pingPath string
workQ chan target
healthCheckType string
}
func (p pinger) start() {
for t := range p.workQ {
log.Printf("pinging target %s", t.URL)
currentWeight := t.Weight
var err error
if p.healthCheckType == "http" {
err = p.httpPingCheck(t)
} else if p.healthCheckType == "tcp" {
err = p.tcpPortCheck(t)
}
if err != nil && currentWeight > 0 {
log.Printf("target %s is down, marking it as unhealthy", t.URL)
err := p.client.setTargetWeightFor(t.UpstreamID, t.URL, unhealthyNodeWeight)
if err != nil {
log.Printf("failed to mark target %s as unhealthy: reason: %s", t.URL, err)
continue
}
continue
}
// Previously marked unhealthy node is healthy
if currentWeight <= 0 && err == nil {
log.Printf("target %s is up, marking it as healthy", t.URL)
err := p.client.setTargetWeightFor(t.UpstreamID, t.URL, healthyNodeWeight)
if err != nil {
log.Printf("failed to mark target %s as healthy: reason: %s", t.URL, err)
continue
}
continue
}
}
}
func (p pinger) tcpPortCheck(t target) error {
tcpAddr, err := net.ResolveTCPAddr("tcp4", t.URL)
if err != nil {
return err
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
return err
}
defer conn.Close()
return nil
}
func (p pinger) httpPingCheck(t target) error {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", t.URL, p.pingPath), nil)
if err != nil {
return err
}
response, err := p.pingClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusInternalServerError {
return errors.New("sever not available")
}
return nil
}