-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
96 lines (74 loc) · 1.86 KB
/
Copy pathmain.go
File metadata and controls
96 lines (74 loc) · 1.86 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
package main
import (
config "lb-go/config"
"lb-go/infra"
"lb-go/l4"
"log"
"net"
"net/http"
_ "net/http/pprof"
"sync"
"time"
)
func main() {
InitLogger()
quit := GracefulShutdownChan()
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal(err)
}
lb := &l4.LoadBalancer{
Quit: quit,
Listener: net.Listener(nil),
ConnWG: sync.WaitGroup{},
}
configManager := config.NewConfigManager(cfg, func(cfg *config.Config) {
lb.Reload(cfg)
go lb.ResolveAllBackends()
go lb.HealthCheck()
})
rl := infra.NewRateLimiter(configManager.Get().RateLimit)
runtime := config.NewRuntime(cfg)
lb.RateLimiter.Store(rl)
lb.Runtime.Store(runtime)
go configManager.Watch()
pingTicker := time.NewTicker(time.Duration(configManager.Get().HealthCheck.IntervalMs) * time.Millisecond)
rateLimitCleanupTicker := time.NewTicker(time.Duration(time.Hour * 6))
connectionsLogTicker := time.NewTicker(time.Duration(time.Second * 3))
go rl.Cleanup(rateLimitCleanupTicker)
defer pingTicker.Stop()
//for keeping track of goroutines
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
lb.ResolveAllBackends()
lb.StartDNSResolver(time.Duration(configManager.Get().DNSRefreshIntervalMs) * time.Millisecond)
lb.HealthCheck()
go func() {
if err := lb.ListenReusePort(":8080"); err != nil {
log.Fatal(err)
}
}()
for {
select {
case <-quit:
{
lb.Shutdown()
return
}
case <-pingTicker.C:
{
go lb.HealthCheck()
newInterval := time.Duration(configManager.Get().HealthCheck.IntervalMs) * time.Millisecond
pingTicker.Reset(newInterval)
}
case <-connectionsLogTicker.C:
{
for i := range lb.Runtime.Load().BackendPool.Backends {
backend := &lb.Runtime.Load().BackendPool.Backends[i]
log.Printf("Backend %s has %d connections", *backend.Address.Load(), backend.Connections.Load())
}
}
}
}
}