-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
344 lines (281 loc) · 8 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package pool
import (
"bufio"
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/dgraph-io/ristretto"
"github.com/CoderCookE/goaround/internal/connection"
"github.com/CoderCookE/goaround/internal/healthcheck"
"github.com/CoderCookE/goaround/internal/stats"
)
type attempts int
const (
attemptsKey attempts = iota
)
type pool struct {
sync.RWMutex
connections chan *connection.Connection
healthChecks map[string]*healthcheck.HealthChecker
client *http.Client
connsPerBackend int
cache *ristretto.Cache
maxRetries int
}
//Exported method for creation of a connection-pool takes []string
//ex: ['http://localhost:9000','http://localhost:9000']
func New(c *Config) *pool {
backends := c.Backends
connsPerBackend := c.NumConns
cacheEnabled := c.EnableCache
maxRetries := c.MaxRetries
backendCount := int(math.Max(float64(len(backends)), float64(1)))
maxRequests := connsPerBackend * backendCount * 2
tr := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 10 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
}
client := &http.Client{
Timeout: 30 * time.Second,
Transport: tr,
}
cache, err := buildCache(cacheEnabled)
if err != nil {
log.Printf("Error creating cache: %v", err)
}
connectionPool := &pool{
connections: make(chan *connection.Connection, maxRequests),
healthChecks: make(map[string]*healthcheck.HealthChecker),
client: client,
connsPerBackend: connsPerBackend,
cache: cache,
maxRetries: maxRetries,
}
poolConnections := []*connection.Connection{}
startup := &sync.WaitGroup{}
for _, backend := range backends {
startup.Add(1)
poolConnections = connectionPool.addBackend(poolConnections, backend, startup)
}
shuffle(poolConnections, connectionPool.connections)
go connectionPool.ListenForBackendChanges(startup)
return connectionPool
}
func shuffle(conns []*connection.Connection, ch chan *connection.Connection) {
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(conns), func(i, j int) {
conns[i], conns[j] = conns[j], conns[i]
})
for _, conn := range conns {
stats.AvailableConnectionsGauge.WithLabelValues("available").Add(1)
ch <- conn
}
}
func buildCache(cacheEnabled bool) (*ristretto.Cache, error) {
if !cacheEnabled {
return nil, nil
}
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: 1 << 30, // maximum cost of cache (1GB).
BufferItems: 64, // number of keys per Get buffer.
})
return cache, err
}
//Exported method for passing a request to a connection from the pool
//Returns a 503 status code if request is unsuccessful
func (p *pool) Fetch(w http.ResponseWriter, r *http.Request) {
start := time.Now()
conn := <-p.connections
ctxAttempt := r.Context().Value(attemptsKey)
var attempt int
if ctxAttempt != nil {
attempt = ctxAttempt.(int) + 1
}
if attempt > p.maxRetries {
return
}
duration := time.Since(start).Seconds()
stats.Durations.WithLabelValues("get_connection").Observe(duration)
stats.AvailableConnectionsGauge.WithLabelValues("in_use").Add(1)
defer func() {
stats.AvailableConnectionsGauge.WithLabelValues("in_use").Sub(1)
stats.Attempts.WithLabelValues().Observe(float64(attempt))
duration = time.Since(start).Seconds()
stats.Durations.WithLabelValues("return_connection").Observe(duration)
if !conn.Shut {
p.connections <- conn
}
}()
if p.cache != nil && r.Method == "GET" {
value, found := p.cache.Get(r.URL.Path)
if found {
stats.CacheCounter.WithLabelValues(r.URL.Path, "hit").Add(1)
res := value.(string)
_, err := w.Write([]byte(res))
if err != nil {
log.Printf("Error writing: %s", err.Error())
}
return
}
stats.CacheCounter.WithLabelValues(r.URL.Path, "miss").Add(1)
}
usableProxy, err := conn.Get()
ctx := context.WithValue(r.Context(), attemptsKey, attempt)
if err != nil {
log.Printf("retrying err with request: %s", err.Error())
p.Fetch(w, r.WithContext(ctx))
} else {
usableProxy.ServeHTTP(w, r)
}
}
func (p *pool) Shutdown() {
p.RLock()
for _, hc := range p.healthChecks {
hc.Shutdown()
}
p.RUnlock()
}
func (p *pool) ListenForBackendChanges(startup *sync.WaitGroup) {
const SockAddr = "/tmp/goaround.sock"
if err := os.RemoveAll(SockAddr); err != nil {
log.Fatal(err)
}
l, err := net.Listen("unix", SockAddr)
if err != nil {
log.Fatal("listen error:", err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal("accept error:", err)
}
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
updated := strings.Split(scanner.Text(), ",")
p.Lock()
var currentBackends []string
for k := range p.healthChecks {
currentBackends = append(currentBackends, k)
}
added, removed := difference(currentBackends, updated)
log.Printf("Adding: %s", added)
log.Printf("Removing: %s", removed)
for _, removedBackend := range removed {
if len(added) > 0 {
var new string
new, added = added[0], added[1:]
endpoint, err := url.ParseRequestURI(new)
if err != nil {
log.Printf("Error adding backend, %s", new)
} else {
proxy := httputil.NewSingleHostReverseProxy(endpoint)
proxy.Transport = p.client.Transport
proxy.ErrorHandler = p.errorHandler
p.setupCache(proxy)
newHC := p.healthChecks[removedBackend].Reuse(new, proxy)
p.healthChecks[new] = newHC
}
} else {
p.healthChecks[removedBackend].Shutdown()
}
delete(p.healthChecks, removedBackend)
}
poolConnections := []*connection.Connection{}
wg := &sync.WaitGroup{}
for _, addedBackend := range added {
wg.Add(1)
poolConnections = p.addBackend(poolConnections, addedBackend, wg)
}
shuffle(poolConnections, p.connections)
p.Unlock()
}
}
}
func difference(original []string, updated []string) (added []string, removed []string) {
oldBackends := make(map[string]bool)
for _, i := range original {
oldBackends[i] = true
}
newBackends := make(map[string]bool)
for _, i := range updated {
newBackends[i] = true
}
for _, i := range updated {
if _, ok := oldBackends[i]; !ok {
added = append(added, i)
}
}
for _, i := range original {
if _, ok := newBackends[i]; !ok {
removed = append(removed, i)
}
}
return
}
func (p *pool) addBackend(connections []*connection.Connection, backend string, startup *sync.WaitGroup) []*connection.Connection {
endpoint, err := url.ParseRequestURI(backend)
if err != nil {
log.Printf("error parsing backend url: %s", backend)
} else {
proxy := httputil.NewSingleHostReverseProxy(endpoint)
proxy.ErrorHandler = p.errorHandler
proxy.Transport = p.client.Transport
p.setupCache(proxy)
backendConnections := make([]chan connection.Message, p.connsPerBackend)
for i := 0; i < p.connsPerBackend; i++ {
startup.Add(1)
configuredConn := connection.NewConnection(proxy, backend, startup)
connections = append(connections, configuredConn)
backendConnections[i] = configuredConn.Messages
}
hc := healthcheck.New(
p.client,
backendConnections,
backend,
false,
)
p.healthChecks[backend] = hc
go hc.Start(startup)
}
startup.Wait()
return connections
}
func (p *pool) errorHandler(w http.ResponseWriter, r *http.Request, e error) {
host := fmt.Sprintf("%s:%s", r.URL.Hostname(), r.URL.Port())
stats.RequestCounter.WithLabelValues(host, "backend_error").Add(1)
p.Fetch(w, r)
}
func (p *pool) setupCache(proxy *httputil.ReverseProxy) {
if p.cache != nil {
cacheResponse := func(r *http.Response) error {
body, err := ioutil.ReadAll(r.Body)
cacheable := string(body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
path := r.Request.URL.Path
if err == nil {
p.cache.Set(path, cacheable, 1)
}
return nil
}
proxy.ModifyResponse = cacheResponse
}
}