-
Notifications
You must be signed in to change notification settings - Fork 0
/
healthcheck.go
47 lines (39 loc) · 873 Bytes
/
healthcheck.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
package mybalancer
import (
"log"
"net"
"net/url"
"time"
)
// checks if the backend is alive.
func isBackendAlive(url *url.URL) bool {
conn, err := net.DialTimeout("tcp", url.Host, time.Minute*1)
if err != nil {
log.Printf("Unreachable to %v, error: %v", url.Host, err.Error())
return false
}
defer conn.Close()
return true
}
// healthCheck is a function for healthchecking all the backends
func healthCheck(cfg Config) {
t := time.NewTicker(time.Minute * 1)
for {
select {
case <-t.C:
for i := range cfg.Backends {
pingURL, err := url.Parse(cfg.Backends[i].URL)
if err != nil {
log.Fatal(err.Error())
}
isAlive := isBackendAlive(pingURL)
cfg.Backends[i].SetDead(!isAlive)
msg := "ok"
if !isAlive {
msg = "dead"
}
log.Printf("%v checked %v by healthcheck", cfg.Backends[i].URL, msg)
}
}
}
}