-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
201 lines (153 loc) · 3.64 KB
/
main.go
File metadata and controls
201 lines (153 loc) · 3.64 KB
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
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"sync/atomic"
"time"
)
const (
Attempts int = iota
Retry
)
type Backend struct {
URL *url.URL
Alive bool
mux sync.RWMutex
ReverseProxy *httputil.ReverseProxy
}
func (b *Backend) SetAlive(alive bool) {
b.mux.Lock()
b.Alive = alive
b.mux.Unlock()
}
func (b *Backend) IsAlive() (alive bool) {
b.mux.RLock()
alive = b.Alive
b.mux.RUnlock()
return
}
type ServerPool struct {
backends []*Backend
current uint64
}
func (s *ServerPool) NextIndex() int {
return int(atomic.AddUint64(&s.current, uint64(1)) % uint64(len(s.backends)))
}
func (s *ServerPool) GetNextPeer() *Backend {
next := s.NextIndex()
l := len(s.backends) + next
for i := next; i < l; i++ {
index := i % len(s.backends)
if s.backends[index].IsAlive() {
if i != next {
atomic.StoreUint64(&s.current, uint64(index))
}
return s.backends[index]
}
}
return nil
}
func (s *ServerPool) HealthCheck() {
for _, backend := range s.backends {
status := "up"
isAlive := isBackendAlive(backend.URL)
backend.SetAlive(isAlive)
if !isAlive {
status = "down"
}
log.Printf("%s [%s]\n", backend.URL, status)
}
}
func (s *ServerPool) MarkBackendStatus(backendUrl *url.URL, alive bool) {
for _, backend := range s.backends {
if backend.URL.String() == backendUrl.String() {
backend.SetAlive(alive)
break
}
}
}
func isBackendAlive(u *url.URL) bool {
timeout := 2 * time.Second
conn, err := net.DialTimeout("tcp", u.Host, timeout)
if err != nil {
log.Printf("Site unreachable, error: ", err)
return false
}
_ = conn.Close()
return true
}
func GetAttemptsFromContext(r *http.Request) int {
if attempts, ok := r.Context().Value(Attempts).(int); ok {
return attempts
}
return 1
}
func GetRetryFromContext(r *http.Request) int {
if retry, ok := r.Context().Value(Retry).(int); ok {
return retry
}
return 0
}
func loadBalance(w http.ResponseWriter, r *http.Request) {
attempts := GetAttemptsFromContext(r)
if attempts > 3 {
log.Printf("%s(%s) Max attempts reached, terminating\n", r.RemoteAddr, r.URL.Path)
http.Error(w, "Service not available", http.StatusServiceUnavailable)
return
}
peer := serverPool.GetNextPeer()
if peer != nil {
peer.ReverseProxy.ServeHTTP(w, r)
return
}
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable)
}
func healthCheck() {
t := time.NewTicker(time.Second * 20)
for {
select {
case <-t.C:
log.Printf("Starting health check\n")
serverPool.HealthCheck()
log.Printf("Health check completed\n")
}
}
}
var serverPool ServerPool
func main() {
var port int
serverUrl, _ := url.Parse("http://localhost:8181")
proxy := httputil.NewSingleHostReverseProxy(serverUrl)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("[%s] %s\n", serverUrl.Host, err.Error)
retries := GetRetryFromContext(r)
if retries < 3 {
select {
case <-time.After(time.Millisecond * 10):
ctx := context.WithValue(r.Context(), Retry, retries+1)
proxy.ServeHTTP(w, r.WithContext(ctx))
}
return
}
serverPool.MarkBackendStatus(serverUrl, false)
attempts := GetAttemptsFromContext(r)
log.Printf("%s(%s) Attempting retry %d\n", r.RemoteAddr, r.URL.Path, attempts)
ctx := context.WithValue(r.Context(), Attempts, attempts+1)
loadBalance(w, r.WithContext(ctx))
}
server := http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.HandlerFunc(loadBalance),
}
go healthCheck()
log.Printf("Load Balancer started at :%d\n", port)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}