forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributed_rate_limiter.go
98 lines (80 loc) · 1.87 KB
/
distributed_rate_limiter.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
package main
import (
"encoding/json"
"time"
"github.com/Sirupsen/logrus"
"github.com/TykTechnologies/drl"
)
var DRLManager = &drl.DRL{}
func setupDRL() {
drlManager := &drl.DRL{}
drlManager.Init()
drlManager.ThisServerID = NodeID + "|" + HostDetails.Hostname
log.Debug("DRL: Setting node ID: ", drlManager.ThisServerID)
DRLManager = drlManager
}
func startRateLimitNotifications() {
notificationFreq := globalConf.DRLNotificationFrequency
if notificationFreq == 0 {
notificationFreq = 2
}
go func() {
log.Info("Starting gateway rate limiter notifications...")
for {
if NodeID != "" {
NotifyCurrentServerStatus()
} else {
log.Warning("Node not registered yet, skipping DRL Notification")
}
time.Sleep(time.Duration(notificationFreq) * time.Second)
}
}()
}
func getTagHash() string {
th := ""
for _, tag := range globalConf.DBAppConfOptions.Tags {
th += tag
}
return th
}
func NotifyCurrentServerStatus() {
if !DRLManager.Ready {
return
}
rate := GlobalRate.Rate()
if rate == 0 {
rate = 1
}
server := drl.Server{
HostName: HostDetails.Hostname,
ID: NodeID,
LoadPerSec: rate,
TagHash: getTagHash(),
}
asJson, err := json.Marshal(server)
if err != nil {
log.Error("Failed to encode payload: ", err)
return
}
n := Notification{
Command: NoticeGatewayDRLNotification,
Payload: string(asJson),
}
MainNotifier.Notify(n)
}
func onServerStatusReceivedHandler(payload string) {
serverData := drl.Server{}
if err := json.Unmarshal([]byte(payload), &serverData); err != nil {
log.WithFields(logrus.Fields{
"prefix": "pub-sub",
}).Error("Failed unmarshal server data: ", err)
return
}
log.Debug("Received DRL data: ", serverData)
if DRLManager.Ready {
DRLManager.AddOrUpdateServer(serverData)
log.Debug(DRLManager.Report())
} else {
log.Warning("DRL not ready, skipping this notification")
}
}