-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
211 lines (178 loc) · 4.79 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
Attempts int = iota
Retry
)
type Backend struct {
URL *url.URL
Alive bool
mux sync.RWMutex
ReverseProxy *httputil.ReverseProxy
}
func (backend *Backend) SetAlive(alive bool) {
backend.mux.Lock()
backend.Alive = alive
backend.mux.Unlock()
}
func (backend *Backend) IsAlive() (alive bool) {
backend.mux.RLock()
alive = backend.Alive
backend.mux.RUnlock()
return
}
type ServerPool struct {
backends []*Backend
current uint64
}
func (serverPool *ServerPool) AddBackend(backend *Backend) {
serverPool.backends = append(serverPool.backends, backend)
}
func (serverPool *ServerPool) NextIndex() int {
return int(atomic.AddUint64(&serverPool.current, uint64(1)) % uint64(len(serverPool.backends)))
}
func (serverPool *ServerPool) MarkBackendStatus(backendUrl *url.URL, alive bool) {
for _, backend := range serverPool.backends {
if backend.URL.String() == backendUrl.String() {
backend.SetAlive(alive)
break
}
}
}
func (serverPool *ServerPool) GetNextPeer() *Backend {
next := serverPool.NextIndex()
amountBackends := len(serverPool.backends)
length := amountBackends + next
for i := next; i < length; i++ {
index := i % amountBackends
if serverPool.backends[index].IsAlive() {
if i != next {
atomic.StoreUint64(&serverPool.current, uint64(index))
}
return serverPool.backends[index]
}
}
return nil
}
func (serverPool *ServerPool) HealthCheck() {
for _, backend := range serverPool.backends {
status := "up"
alive := isBackendAlive(backend.URL)
backend.SetAlive(alive)
if !alive {
status = "down"
}
log.Printf("%s [%s]\n", backend.URL, status)
}
}
func GetAttemptsFromContext(request *http.Request) int {
if attempts, ok := request.Context().Value(Attempts).(int); ok {
return attempts
}
return 1
}
func GetRetryFromContext(request *http.Request) int {
if retry, ok := request.Context().Value(Retry).(int); ok {
return retry
}
return 0
}
func loadBalancer(responseWritter http.ResponseWriter, request *http.Request) {
attempts := GetAttemptsFromContext(request)
if attempts > 3 {
log.Printf("%s(%s) Max attempts reached, terminating\n", request.RemoteAddr, request.URL.Path)
http.Error(responseWritter, "Service not available", http.StatusServiceUnavailable)
return
}
peer := serverPool.GetNextPeer()
if peer != nil {
peer.ReverseProxy.ServeHTTP(responseWritter, request)
return
}
http.Error(responseWritter, "Service not available", http.StatusServiceUnavailable)
}
func isBackendAlive(urlBackend *url.URL) bool {
timeout := 2 * time.Second
connection, err := net.DialTimeout("tcp", urlBackend.Host, timeout)
if err != nil {
log.Println("Site unreachable, error: ", err)
return false
}
_ = connection.Close()
return true
}
func healthCheck() {
timer := time.NewTicker(time.Minute * 2)
for {
select {
case <- timer.C:
log.Println("Starting health check...")
serverPool.HealthCheck()
log.Println("Health check completed")
}
}
}
var serverPool ServerPool
func main() {
var serverList string
var port int
flag.StringVar(&serverList, "backends", "", "Load balanced backends, use commas to separate")
flag.IntVar(&port, "port", 3030, "Port to serve")
flag.Parse()
if len(serverList) == 0 {
log.Fatal("Please provide one or more backends to load balance")
}
tokens := strings.Split(serverList, ",")
for _, token := range tokens {
serverUrl, err := url.Parse(token)
if err != nil {
log.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(serverUrl)
proxy.ErrorHandler = func(responseWriter http.ResponseWriter, request *http.Request, err error) {
log.Printf("[%s] %s\n", serverUrl.Host, err.Error())
retries := GetRetryFromContext(request)
if retries < 3 {
select {
case <-time.After(10 * time.Millisecond):
theContext := context.WithValue(request.Context(), Retry, retries + 1)
proxy.ServeHTTP(responseWriter, request.WithContext(theContext))
}
return
}
serverPool.MarkBackendStatus(serverUrl, false)
attempts := GetAttemptsFromContext(request)
log.Printf("%s(%s) Attempting retry %d\n", request.RemoteAddr, request.URL.Path, attempts)
theContext := context.WithValue(request.Context(), Attempts, attempts + 1)
loadBalancer(responseWriter, request.WithContext(theContext))
}
serverPool.AddBackend(&Backend{
URL: serverUrl,
Alive: true,
ReverseProxy: proxy,
})
log.Printf("Configured server: %s\n", serverUrl)
}
server := http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.HandlerFunc(loadBalancer),
}
go healthCheck()
log.Printf("Load Balancer started at :%d\n", port)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}