-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathping_load_balancer.go
111 lines (95 loc) · 2.04 KB
/
ping_load_balancer.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
package main
import (
"fmt"
"net/http"
"time"
)
const (
INIT_DELAY = 3000
MAX_DELAY = 6000
MAX_RETRY = 4
DELAY_INCREMENT = 5000
)
type Server struct {
Name string
URL string
LastChecked time.Time
Status bool
StatusCode int
Delay int
Retries int
Channel chan bool
}
var Servers []Server
func (s *Server) checkServer(sc chan *Server) {
var previousStatus string
if s.Status == true {
previousStatus = "OK"
} else {
previousStatus = "Down"
}
fmt.Println("Server was " + previousStatus + " on last checked - " + s.LastChecked.String())
fmt.Println("Checking server again:", s.Name)
resp, err := http.Get(s.URL)
if err != nil {
fmt.Println("Error:", err)
s.Status = false
s.StatusCode = 0
} else {
fmt.Println(resp.Status)
s.Status = true
s.StatusCode = resp.StatusCode
}
s.LastChecked = time.Now()
sc <- s
}
func checkServers(sc chan *Server) {
for i := 0; i < len(Servers); i++ {
Servers[i].Channel = make(chan bool)
go Servers[i].checkServer(sc)
go Servers[i].updateDelay(sc)
}
}
func (s *Server) updateDelay(sc chan *Server) {
for {
select {
case d := <-s.Channel:
if d == false {
s.Delay = s.Delay + DELAY_INCREMENT
s.Retries++
if s.Delay >= MAX_DELAY {
s.Delay = INIT_DELAY
}
} else {
s.Delay = INIT_DELAY
}
newDuration := time.Duration(s.Delay)
if s.Retries >= MAX_RETRY {
fmt.Println("Server is not reachable after ", MAX_RETRY, " retries.")
} else {
fmt.Println("Will check `" + s.Name + "` server again.")
time.Sleep(newDuration)
s.checkServer(sc)
}
default:
}
}
}
func main() {
sc := make(chan *Server)
ec := make(chan bool)
Servers = []Server{
{Name: "Google", URL: "http://google.com", Status: true, Delay: INIT_DELAY},
{Name: "Yahoo", URL: "http://yahoo.com", Status: true, Delay: INIT_DELAY},
{Name: "Amazon", URL: "http://amazon.zom", Status: true, Delay: INIT_DELAY},
}
checkServers(sc)
for {
select {
case s := <-sc:
s.Channel <- false
default:
}
}
<-ec
}