-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpylon.go
More file actions
558 lines (493 loc) · 13.1 KB
/
pylon.go
File metadata and controls
558 lines (493 loc) · 13.1 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/*
A simple reverse proxy and load balancer
supported balancing strategies:
- Round Robin
- Random
- Least Connected
Example of a json config:
{
"servers": [
{
"name": "server1",
"port": 7777,
"services": [
{
"route_prefix": "/microservice/",
"instances": [
{
"host": "127.0.0.1:1111",
"weight": 3
},
{
"host": "127.0.0.1:2222"
},
{
"host": "127.0.0.1:3333"
}
],
"balancing_strategy": "round_robin",
"max_connections": 300,
"health_check": {
"enabled": true,
"interval": 30
}
}
]
}
]
}
*/
package pylon
import (
"net/http"
"regexp"
"strconv"
"sync"
"math/rand"
"net"
"time"
"strings"
"html/template"
)
var (
proxyPool *ProxyPool
)
type RouteType int8
const (
maxFloat32 = float32(^uint(0))
blacklisted = true
Regex RouteType = iota
Prefix RouteType = iota
defaultMaxCon = 100000
defaultHealthCheckInterval = 20
defaultProxyPoolCapacity = defaultMaxCon
flushInterval = time.Second * 1
defaultDialerTimeout = time.Second * 3
)
type Pylon struct {
Services []*MicroService
}
type Route interface {
Type() RouteType
Data() interface{}
}
type MicroService struct {
Name string
Route Route
Instances []*Instance
Strategy Strategy
LastUsedIdx SharedInt
BlackList map[int]bool
ReqCount chan int
// Caching the weight sum for faster retrieval
WeightSum float32
Mutex *sync.RWMutex
HealthCheck HealthCheck
}
type RegexRoute struct {
Regex *regexp.Regexp
}
type PrefixRoute struct {
Prefix string
}
func (r RegexRoute) Type() RouteType {
return Regex
}
func (r RegexRoute) Data() interface{} {
return r.Regex
}
func (p PrefixRoute) Type() RouteType {
return Prefix
}
func (p PrefixRoute) Data() interface{} {
return p.Prefix
}
// ListenAndServe tries to parse the config at the given path and serve it
func ListenAndServe(p string) error {
jsonParser := JSONConfigParser{}
c, err := jsonParser.ParseFromPath(p)
if err != nil {
return err
}
return ListenAndServeConfig(c)
}
// ListenAndServeConfig converts a given config to an exploitable
// structure (MicroService) and serves them
func ListenAndServeConfig(c *Config) error {
wg := sync.WaitGroup{}
// Initializing the pool before hand in case one server
// Gets a request as soon as it's served
poolSize := 0
for _, s := range c.Servers {
for _, ser := range s.Services {
if ser.MaxCon == 0 {
poolSize += defaultProxyPoolCapacity
} else {
poolSize += ser.MaxCon
}
}
}
logDebug("Pool size is", poolSize)
proxyPool = NewProxyPool(poolSize)
wg.Add(len(c.Servers))
for _, s := range c.Servers {
p, err := NewPylon(&s)
if err != nil {
return err
}
healthRoute := defaultHealthRoute
if s.HealthRoute != "" {
healthRoute = s.HealthRoute
}
go func() {
defer wg.Done()
serve(p, s.Port, healthRoute)
}()
}
wg.Wait()
return nil
}
// NewPylon returns a new Pylon object given a Server
func NewPylon(s *Server) (*Pylon, error) {
p := &Pylon{}
for _, ser := range s.Services {
m, err := NewMicroService(&ser)
if err != nil {
return nil, err
}
p.Services = append(p.Services, m)
}
return p, nil
}
// NewMicroService returns a new MicroService object given a Service
func NewMicroService(s *Service) (*MicroService, error) {
m := &MicroService{}
if s.Pattern != "" {
reg, err := regexp.Compile(s.Pattern)
if err != nil {
return nil, err
}
m.Route = RegexRoute{
Regex: reg,
}
} else if s.Prefix != "" {
m.Route = PrefixRoute{
Prefix: s.Prefix,
}
} else {
return nil, ErrServiceNoRoute
}
maxCon := defaultMaxCon
if s.MaxCon > 0 {
maxCon = s.MaxCon
}
var weightSum float32 = 0.0
for _, inst := range s.Instances {
var weight float32 = 1
if inst.Weight > 0 {
weight = inst.Weight
}
weightSum += weight
m.Instances = append(m.Instances, &Instance{
inst.Host,
weight,
make(chan int, maxCon),
NewSharedInt(0),
})
}
m.Name = s.Name
m.Strategy = s.Strategy
m.Mutex = &sync.RWMutex{}
m.BlackList = make(map[int]bool, len(s.Instances))
m.LastUsedIdx = NewSharedInt(0)
m.ReqCount = make(chan int, maxCon)
m.WeightSum = weightSum
m.HealthCheck = s.HealthCheck
if m.HealthCheck.Interval == 0 {
m.HealthCheck.Interval = defaultHealthCheckInterval
}
return m, nil
}
// serve serves a Pylon with all of its MicroServices given
// a port to listen to and a route that will be used to access
// some stats about this very Pylon
func serve(p *Pylon, port int, healthRoute string) {
mux := http.NewServeMux()
mux.Handle("/", NewPylonHandler(p))
mux.Handle(healthRoute, NewPylonHealthHandler(p))
server := &http.Server{
Addr: ":" + strconv.Itoa(port),
Handler: mux,
ReadTimeout: 20 * time.Second,
WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1 << 20,
}
for _, s := range p.Services {
logDebug("Starting initial health check of service: " + s.Name)
d := &net.Dialer{
Timeout: defaultDialerTimeout,
}
if s.HealthCheck.DialTO != 0 {
d.Timeout = time.Second * time.Duration(s.HealthCheck.DialTO)
}
// Do an initial health check
go handleHealthCheck(s, d)
if s.HealthCheck.Enabled {
go startPeriodicHealthCheck(s, time.Second * time.Duration(s.HealthCheck.Interval), d)
logDebug("Periodic Health checks started for service: " + s.Name)
}
}
logInfo("Serving on " + strconv.Itoa(port))
server.ListenAndServe()
}
// startPeriodicHealthCheck starts a timer that will check
// the health of the given MicroService given an interval and
// a dialer which is used to ping the instances/endpoints
func startPeriodicHealthCheck(m *MicroService, interval time.Duration, d *net.Dialer) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for t := range ticker.C {
logVerbose("Checking health of Service:", m.Route, " ---tick:", t)
handleHealthCheck(m, d)
}
}
// handleHealthCheck checks whether every instance of the given
// MicroService is UP or DOWN. Performed by the given Dialer
func handleHealthCheck(m *MicroService, d *net.Dialer) bool {
change := false
for i, inst := range m.Instances {
_, err := d.Dial("tcp", inst.Host)
if err != nil {
if !m.isBlacklisted(i) {
m.blackList(i, true)
logInfo("Instance: " + inst.Host + " is now marked as DOWN")
change = true
}
} else {
if m.isBlacklisted(i) {
m.blackList(i, false)
logInfo("Instance: " + inst.Host + " is now marked as UP")
change = true
}
}
}
return change
}
// NewPylonHandler returns a func(w http.ResponseWriter, r *http.Request)
// that will handle incoming requests to the given Pylon
func NewPylonHandler(p *Pylon) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//route, err := p.getRoute(r.URL.Path)
//if err != nil {
// logError(err)
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
//}
m, err := p.getMicroServiceFromRoute(r.URL.Path)
if err != nil || m == nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
inst, _, err := m.getLoadBalancedInstance()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
m.ReqCount <- 1
inst.ReqCount <- 1
logVerbose("Serving " + r.URL.Path + r.URL.RawQuery + ", current request count: " + strconv.Itoa(len(m.ReqCount)))
logVerbose("Instance is " + inst.Host)
proxy := proxyPool.Get()
setUpProxy(proxy, m, inst.Host)
proxy.ServeHTTP(w, r)
proxyPool.Put(proxy)
<-inst.ReqCount
<-m.ReqCount
logVerbose("Request served, count: " + strconv.Itoa(len(m.ReqCount)))
}
}
// NewPylonHealthHandler returns a func(w http.ResponseWriter, r *http.Request)
// that will collect and render some stats about the given Pylon:
// (Name / Strategy / Current request count)
// For every instance: (UP or DOWN / Host / Weight / Current request count)
func NewPylonHealthHandler(p *Pylon) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
t, err := template.New("PylonHealthTemplate").Parse(pylonTemplate)
if err != nil {
logError(err.Error())
}
if err := t.Execute(w, getRenders(p)); err != nil {
logError("Could not render the HTML template")
}
logDebug("Served heath page HTML")
}
}
// getMicroServiceFromRoute returns the first MicroService
// that matches the given route (nil and an error if no
// MicroService could match that route)
func (p *Pylon) getMicroServiceFromRoute(path string) (*MicroService, error) {
for _, ser := range p.Services {
switch ser.Route.Type() {
case Regex:
reg := ser.Route.Data().(*regexp.Regexp)
if reg.Match([]byte(path)) {
return ser, nil
}
case Prefix:
pref := ser.Route.Data().(string)
if strings.HasPrefix(path, pref) {
return ser, nil
}
default:
return nil, ErrInvalidRouteType
}
}
return nil, NewError(ErrRouteNoRouteCode, "No route available for path " + path)
}
// getLoadBalancedInstance will return a load balanced Instance
// according to the MicroService strategy and current state
func (m *MicroService) getLoadBalancedInstance() (*Instance, int, error) {
instCount := len(m.Instances)
if instCount == 0 {
return nil, -1, ErrServiceNoInstance
}
if len(m.BlackList) == instCount {
return nil, -1, ErrAllInstancesDown
}
instances := make([]*Instance, instCount)
copy(instances, m.Instances)
var idx int
var err error
for {
switch m.Strategy {
case RoundRobin:
idx, err = getRoundRobinInstIdx(instances, m.LastUsedIdx.Get())
case LeastConnected:
idx = getLeastConInstIdx(instances)
case Random:
idx = getRandomInstIdx(instances)
default:
return nil, -1, NewError(ErrInvalidStrategyCode, "Unexpected strategy " + string(m.Strategy))
}
if err != nil {
return nil, -1, err
}
if m.isBlacklisted(idx) {
instances[idx] = nil
} else {
m.LastUsedIdx.Set(idx)
return instances[idx], idx, nil
}
}
}
// getRoundRobinInstIdx returns the index of the Instance that should be
// picked according to round robin rules and a given slice of Instance
func getRoundRobinInstIdx(instances []*Instance, idx int) (int, error) {
tryCount := 1
instCount := len(instances)
lastNonNil := -1
for {
inst := instances[idx]
if inst != nil {
if inst.isRoundRobinPicked() {
break
}
lastNonNil = idx
}
idx++
tryCount++
if tryCount > instCount {
if lastNonNil != -1 {
return lastNonNil, nil
}
return -1, ErrFailedRoundRobin
}
if idx >= instCount {
idx = 0
}
}
return idx, nil
}
// getLeastConInstIdx returns the index of the Instance that should be
// picked according to the least connected rules and a given slice of Instance
// Least Connected returns the least loaded instance, which is
// computed by the current request count divided by the weight of the instance
func getLeastConInstIdx(instances []*Instance) int {
minLoad := maxFloat32
idx := 0
for i, inst := range instances {
if inst == nil {
continue
}
load := float32(len(inst.ReqCount)) / inst.Weight
if load < minLoad {
minLoad = load
idx = i
}
}
return idx
}
// getRandomInstIdx returns the index of an Instance that is picked
// Randomly from the given slice of Instance. Weights of Instances
// are taken into account
func getRandomInstIdx(instances []*Instance) int {
var weightSum float32 = 0.0
for _, inst := range instances {
if inst == nil {
continue
}
weightSum += inst.Weight
}
r := rand.Float32() * weightSum
for i, inst := range instances {
if inst == nil {
continue
}
r -= inst.Weight
if r < 0 {
return i
}
}
return 0
}
// blackList blacklists the Instance of the MicroService
// identified by the given index
func (m *MicroService) blackList(idx int, blacklist bool) {
m.Mutex.Lock()
if blacklist {
m.BlackList[idx] = blacklisted
} else {
delete(m.BlackList, idx)
}
m.Mutex.Unlock()
}
// blackList blacklists the Instance of the MicroService
// identified by the given Host
func (m *MicroService) blackListHost(host string, blacklist bool) {
for idx, inst := range m.Instances {
if inst.Host == host {
m.blackList(idx, blacklist)
}
}
}
// isBlacklisted returns whether the Instance identified
// by the given index is black listed
func (m *MicroService) isBlacklisted(idx int) bool {
blackListed := false
m.Mutex.RLock()
blackListed = m.BlackList[idx]
m.Mutex.RUnlock()
return blackListed
}
// Returns whether the Instance should still be picked
// according to the round robin rules and internal state
func (i *Instance) isRoundRobinPicked() bool {
i.RRPos.Lock()
defer i.RRPos.Unlock()
i.RRPos.value++
if i.RRPos.value > int(i.Weight) {
i.RRPos.value = 0
return false
}
return true
}