forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributed_rate_limiter.go
97 lines (81 loc) · 1.92 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
package main
import (
"encoding/json"
"github.com/TykTechnologies/logrus"
"github.com/TykTechnologies/drl"
"time"
)
var DRLManager drl.DRL
func SetupDRL() {
thisDRLManager := drl.DRL{}
thisDRLManager.Init()
thisDRLManager.ThisServerID = NodeID + "|" + HostDetails.Hostname
log.Debug("DRL: Setting node ID: ", thisDRLManager.ThisServerID)
DRLManager = thisDRLManager
}
func StartRateLimitNotifications() {
notificationFreq := config.DRLNotificationFrequency
if notificationFreq == 0 {
notificationFreq = 2
}
go func() {
log.Info("Starting gateway rate imiter 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(config.DBAppConfOptions.Tags) {
th += tag
}
return th
}
func NotifyCurrentServerStatus() {
if DRLManager.Ready == false {
return
}
rate := GlobalRate.Rate()
if rate == 0 {
rate = 1
}
thisServer := drl.Server{
HostName: HostDetails.Hostname,
ID: NodeID,
LoadPerSec: rate,
TagHash: getTagHash(),
}
asJson, jsErr := json.Marshal(thisServer)
if jsErr != nil {
log.Error("Failed to encode payload: ", jsErr)
return
}
n := Notification{
Command: NoticeGatewayDRLNotification,
Payload: string(asJson),
}
MainNotifier.Notify(n)
}
func OnServerStatusReceivedHandler(payload string) {
thisServerData := drl.Server{}
jsErr := json.Unmarshal([]byte(payload), &thisServerData)
if jsErr != nil {
log.WithFields(logrus.Fields{
"prefix": "pub-sub",
}).Error("Failed unmarshal server data: ", jsErr)
return
}
log.Debug("Received DRL data: ", thisServerData)
if DRLManager.Ready {
DRLManager.AddOrUpdateServer(thisServerData)
log.Debug(DRLManager.Report())
} else {
log.Warning("DRL not ready, skipping this notification")
}
}