-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolb.go
89 lines (78 loc) · 2.41 KB
/
golb.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
package golb
import (
"log"
"net/http"
"sync"
"time"
)
// LoadBalancer represents a simple round-robin load balancer with active cleaning and passive recovery.
type LoadBalancer struct {
port string
roundRobinCount int
servers []server
mu sync.Mutex
}
// NewLoadBalancer initializes a LoadBalancer with the specified port and servers.
func NewLoadBalancer(port string, servers []server) *LoadBalancer {
lb := &LoadBalancer{
port: port,
roundRobinCount: 0,
servers: servers,
}
go lb.recoverUnhealthyServers(10 * time.Second)
return lb
}
// getNextAvailableServer returns the next available server in a round-robin fashion.
func (lb *LoadBalancer) getNextAvailableServer() server {
lb.mu.Lock()
defer lb.mu.Unlock()
for i := 0; i < len(lb.servers); i++ {
server := lb.servers[lb.roundRobinCount%len(lb.servers)]
if server.IsAlive() {
lb.roundRobinCount++
return server
}
lb.roundRobinCount++
}
log.Println("No healthy servers available")
return nil
}
// serveProxy forwards the request to the selected server.
func (lb *LoadBalancer) serveProxy(rw http.ResponseWriter, r *http.Request) {
server := lb.getNextAvailableServer()
if server == nil {
http.Error(rw, "Service Unavailable", http.StatusServiceUnavailable)
return
}
log.Printf("Forwarding request to address %q\n", server.Address())
server.Serve(rw, r)
}
// recoverUnhealthyServers periodically checks and recovers unhealthy servers.
func (lb *LoadBalancer) recoverUnhealthyServers(interval time.Duration) {
for {
time.Sleep(interval)
lb.mu.Lock()
for _, server := range lb.servers {
if !server.IsAlive() {
log.Printf("Attempting to recover server at %s", server.Address())
server.StartHealthCheck(2 * time.Second) // Start health check on the server
}
}
lb.mu.Unlock()
}
}
// Start initializes servers, sets up the load balancer, and starts listening on the specified port.
func Start(serverAddresses []string, port string) {
var servers []server
for _, addr := range serverAddresses {
server := newSimpleServer(addr)
server.StartHealthCheck(2 * time.Second) // Regular health check
servers = append(servers, server)
}
lb := NewLoadBalancer(port, servers)
http.HandleFunc("/", lb.serveProxy)
log.Printf("Load balancer listening on port %s\n", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}