forked from goodrain/rainbond
/
tcp_probe.go
57 lines (52 loc) · 1.24 KB
/
tcp_probe.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
package probe
import (
"context"
"net"
"time"
"github.com/goodrain/rainbond/node/nodem/client"
"github.com/goodrain/rainbond/node/nodem/service"
)
type TcpProbe struct {
Name string
Address string
ResultsChan chan *service.HealthStatus
Ctx context.Context
Cancel context.CancelFunc
TimeInterval int
HostNode *client.HostNode
MaxErrorsNum int
}
func (h *TcpProbe) Check() {
go h.TcpCheck()
}
func (h *TcpProbe) Stop() {
h.Cancel()
}
func (h *TcpProbe) TcpCheck() {
timer := time.NewTimer(time.Second * time.Duration(h.TimeInterval))
defer timer.Stop()
for {
HealthMap := GetTcpHealth(h.Address)
result := &service.HealthStatus{
Name: h.Name,
Status: HealthMap["status"],
Info: HealthMap["info"],
}
h.ResultsChan <- result
timer.Reset(time.Second * time.Duration(h.TimeInterval))
select {
case <-h.Ctx.Done():
return
case <-timer.C:
}
}
}
//GetTcpHealth get tcp health
func GetTcpHealth(address string) map[string]string {
conn, err := net.Dial("tcp", address)
if err != nil {
return map[string]string{"status": service.Stat_death, "info": "Tcp connection error"}
}
defer conn.Close()
return map[string]string{"status": service.Stat_healthy, "info": "service health"}
}