-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (159 loc) · 4.35 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sync"
"gopkg.in/yaml.v3"
)
type SimpleServer struct {
address string
healthcheck string
proxy *httputil.ReverseProxy
}
type LoadBalancer struct {
port string
roundRobinCount int
servers []Server
activeConnections map[Server]int
mutex sync.Mutex
}
type Server interface {
Address() string
isAlive() bool
HealthCheck() string
Serve(w http.ResponseWriter, r *http.Request)
}
type Config struct {
Servers map[string]ServerConfig `yaml:"servers"`
Algorithm string `yaml:"algorithm"`
Port string `yaml:"port"`
}
type ServerConfig struct {
Address string `yaml:"address"`
Healthcheck string `yaml:"healthcheck"`
}
func newSimpleServer(address string) *SimpleServer {
serverUrl, err := url.Parse(address)
handleError(err)
return &SimpleServer{address: address, proxy: httputil.NewSingleHostReverseProxy(serverUrl)}
}
func NewLoadBalancer(port string, servers []Server) *LoadBalancer {
activeConnections := make(map[Server]int)
for _, server := range servers {
activeConnections[server] = 0
}
return &LoadBalancer{port: port, roundRobinCount: 0, servers: servers, activeConnections: activeConnections}
}
func (lb *LoadBalancer) getNextAvailableServer() Server {
config, _ := readConfigFile()
switch config.Algorithm {
case "round-robin":
server := lb.servers[lb.roundRobinCount%len(lb.servers)]
for !server.isAlive() {
lb.roundRobinCount++
server = lb.servers[lb.roundRobinCount%len(lb.servers)]
}
lb.roundRobinCount++
return server
case "least-connections":
leastConnections := math.MaxInt64
for _, server := range lb.servers {
connections := lb.activeConnections[server]
if connections == 0 && server.isAlive() {
return server
}
if connections < leastConnections && server.isAlive() {
leastConnections = connections
return server
}
}
}
return lb.servers[0]
}
func (lb *LoadBalancer) serveProxy(w http.ResponseWriter, r *http.Request) {
targetServer := lb.getNextAvailableServer()
lb.incrementActiveConnections(targetServer)
log.Printf("Forwading requests to address %s", targetServer.Address())
defer lb.decrementActiveConnections(targetServer)
targetServer.Serve(w, r)
}
func (lb *LoadBalancer) incrementActiveConnections(server Server) {
lb.mutex.Lock()
lb.activeConnections[server]++
lb.mutex.Unlock()
}
func (lb *LoadBalancer) decrementActiveConnections(server Server) {
lb.mutex.Lock()
if lb.activeConnections[server] > 0 {
lb.activeConnections[server]--
}
lb.mutex.Unlock()
}
func readConfigFile() (*Config, error) {
filePath := os.Getenv("YALB_CONFIG")
if filePath == "" {
return nil, errors.New("Set the YALB_CONFIG environment variable")
}
buff, err := os.ReadFile(filePath)
handleError(err)
conf := &Config{}
yamlErr := yaml.Unmarshal(buff, conf)
if yamlErr != nil {
panic("Invalid config format. Refer to docs.")
}
return conf, err
}
func (server *SimpleServer) Address() string { return server.address }
func (server *SimpleServer) HealthCheck() string { return server.healthcheck }
func (server *SimpleServer) isAlive() bool {
resp, err := http.Get(fmt.Sprintf("%s%s", server.address, server.healthcheck))
if err != nil {
return false
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println(err)
}
}(resp.Body)
if resp.StatusCode == http.StatusOK {
return true
}
return false
}
func (server *SimpleServer) Serve(w http.ResponseWriter, r *http.Request) {
server.proxy.ServeHTTP(w, r)
}
func handleError(err error) {
if err != nil {
log.Println(err.Error())
}
}
func main() {
config, confErr := readConfigFile()
if confErr != nil {
panic(confErr.Error())
}
log.Printf("Load Balancing Algo: %s\n", config.Algorithm)
log.Printf("Load Balancer Running Port: %s\n", config.Port)
log.Printf("Servers found: %d\n", len(config.Servers))
var servers []Server
for _, server := range config.Servers {
servers = append(servers, newSimpleServer(server.Address))
}
lb := NewLoadBalancer(config.Port, servers)
handleRedirect := func(w http.ResponseWriter, r *http.Request) {
lb.serveProxy(w, r)
}
http.HandleFunc("/", handleRedirect)
log.Printf("Proxying Requests at port %s\n", lb.port)
err := http.ListenAndServe(":"+lb.port, nil)
handleError(err)
}