forked from mailgun/gubernator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgubernator.go
322 lines (269 loc) · 8.61 KB
/
gubernator.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
/*
Copyright 2018-2019 Mailgun Technologies Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gubernator
import (
"context"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"strings"
"sync"
"github.com/mailgun/holster"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
maxBatchSize = 1000
Healthy = "healthy"
UnHealthy = "unhealthy"
)
var log *logrus.Entry
type Instance struct {
wg holster.WaitGroup
health HealthCheckResp
global *globalManager
peerMutex sync.RWMutex
conf Config
}
func New(conf Config) (*Instance, error) {
if conf.GRPCServer == nil {
return nil, errors.New("GRPCServer instance is required")
}
log = logrus.WithField("category", "gubernator")
if err := conf.SetDefaults(); err != nil {
return nil, err
}
s := Instance{
conf: conf,
}
s.global = newGlobalManager(conf.Behaviors, &s)
// Register our server with GRPC
RegisterV1Server(conf.GRPCServer, &s)
RegisterPeersV1Server(conf.GRPCServer, &s)
return &s, nil
}
// GetRateLimits is the public interface used by clients to request rate limits from the system. If the
// rate limit `Name` and `UniqueKey` is not owned by this instance then we forward the request to the
// peer that does.
func (s *Instance) GetRateLimits(ctx context.Context, r *GetRateLimitsReq) (*GetRateLimitsResp, error) {
var resp GetRateLimitsResp
if len(r.Requests) > maxBatchSize {
return nil, status.Errorf(codes.OutOfRange,
"Requests.RateLimits list too large; max size is '%d'", maxBatchSize)
}
type InOut struct {
In *RateLimitReq
Idx int
Out *RateLimitResp
}
// Asynchronously fetch rate limits
out := make(chan InOut)
go func() {
fan := holster.NewFanOut(1000)
// For each item in the request body
for i, item := range r.Requests {
fan.Run(func(data interface{}) error {
inOut := data.(InOut)
globalKey := inOut.In.Name + "_" + inOut.In.UniqueKey
var peer *PeerClient
var err error
if len(inOut.In.UniqueKey) == 0 {
inOut.Out = &RateLimitResp{Error: "field 'unique_key' cannot be empty"}
out <- inOut
return nil
}
if len(inOut.In.Name) == 0 {
inOut.Out = &RateLimitResp{Error: "field 'namespace' cannot be empty"}
out <- inOut
return nil
}
peer, err = s.GetPeer(globalKey)
if err != nil {
inOut.Out = &RateLimitResp{
Error: fmt.Sprintf("while finding peer that owns rate limit '%s' - '%s'", globalKey, err),
}
out <- inOut
return nil
}
// If our server instance is the owner of this rate limit
if peer.isOwner {
// Apply our rate limit algorithm to the request
inOut.Out, err = s.getRateLimit(inOut.In)
if err != nil {
inOut.Out = &RateLimitResp{
Error: fmt.Sprintf("while applying rate limit for '%s' - '%s'", globalKey, err),
}
}
} else {
if inOut.In.Behavior == Behavior_GLOBAL {
inOut.Out, err = s.getGlobalRateLimit(inOut.In)
if err != nil {
inOut.Out = &RateLimitResp{Error: err.Error()}
}
out <- inOut
return nil
}
// Make an RPC call to the peer that owns this rate limit
inOut.Out, err = peer.GetPeerRateLimit(ctx, inOut.In)
if err != nil {
inOut.Out = &RateLimitResp{
Error: fmt.Sprintf("while fetching rate limit '%s' from peer - '%s'", globalKey, err),
}
}
// Inform the client of the owner key of the key
inOut.Out.Metadata = map[string]string{"owner": peer.host}
}
out <- inOut
return nil
}, InOut{In: item, Idx: i})
}
fan.Wait()
close(out)
}()
resp.Responses = make([]*RateLimitResp, len(r.Requests))
// Collect the async responses as they return
for i := range out {
resp.Responses[i.Idx] = i.Out
}
return &resp, nil
}
// getGlobalRateLimit handles rate limits that are marked as `Behavior = GLOBAL`. Rate limit responses
// are returned from the local cache and the hits are queued to be sent to the owning peer.
func (s *Instance) getGlobalRateLimit(req *RateLimitReq) (*RateLimitResp, error) {
// Queue the hit for async update
s.global.QueueHit(req)
s.conf.Cache.Lock()
item, ok := s.conf.Cache.Get(req.HashKey())
s.conf.Cache.Unlock()
if ok {
rl, ok := item.(*RateLimitResp)
if !ok {
// Perhaps the rate limit algorithm was changed by the user.
s.conf.Cache.Remove(req.HashKey())
return s.getGlobalRateLimit(req)
}
return rl, nil
} else {
cpy := *req
cpy.Behavior = Behavior_NO_BATCHING
// Process the rate limit like we own it since we have no data on the rate limit
resp, err := s.getRateLimit(&cpy)
return resp, err
}
}
// UpdatePeerGlobals updates the local cache with a list of global rate limits. This method should only
// be called by a peer who is the owner of a global rate limit.
func (s *Instance) UpdatePeerGlobals(ctx context.Context, r *UpdatePeerGlobalsReq) (*UpdatePeerGlobalsResp, error) {
s.conf.Cache.Lock()
defer s.conf.Cache.Unlock()
for _, g := range r.Globals {
s.conf.Cache.Add(g.Key, g.Status, g.Status.ResetTime)
}
return &UpdatePeerGlobalsResp{}, nil
}
// GetPeerRateLimits is called by other peers to get the rate limits owned by this peer.
func (s *Instance) GetPeerRateLimits(ctx context.Context, r *GetPeerRateLimitsReq) (*GetPeerRateLimitsResp, error) {
var resp GetPeerRateLimitsResp
if len(r.Requests) > maxBatchSize {
return nil, status.Errorf(codes.OutOfRange,
"'PeerRequest.rate_limits' list too large; max size is '%d'", maxBatchSize)
}
for _, req := range r.Requests {
rl, err := s.getRateLimit(req)
if err != nil {
// Return the error for this request
rl = &RateLimitResp{Error: err.Error()}
}
resp.RateLimits = append(resp.RateLimits, rl)
}
return &resp, nil
}
// HealthCheck Returns the health of our instance.
func (s *Instance) HealthCheck(ctx context.Context, r *HealthCheckReq) (*HealthCheckResp, error) {
s.peerMutex.RLock()
defer s.peerMutex.RUnlock()
return &s.health, nil
}
func (s *Instance) getRateLimit(r *RateLimitReq) (*RateLimitResp, error) {
s.conf.Cache.Lock()
defer s.conf.Cache.Unlock()
if r.Behavior == Behavior_GLOBAL {
s.global.QueueUpdate(r)
}
switch r.Algorithm {
case Algorithm_TOKEN_BUCKET:
return tokenBucket(s.conf.Cache, r)
case Algorithm_LEAKY_BUCKET:
return leakyBucket(s.conf.Cache, r)
}
return nil, errors.Errorf("invalid rate limit algorithm '%d'", r.Algorithm)
}
// SetPeers is called when the pool of peers changes
func (s *Instance) SetPeers(peers []PeerInfo) {
picker := s.conf.Picker.New()
var errs []string
for _, peer := range peers {
peerInfo, err := NewPeerClient(s.conf.Behaviors, peer.Address)
if err != nil {
errs = append(errs,
fmt.Sprintf("failed to connect to peer '%s'; consistent hash is incomplete", peer.Address))
continue
}
if info := s.conf.Picker.GetPeerByHost(peer.Address); info != nil {
peerInfo = info
}
// If this peer refers to this server instance
peerInfo.isOwner = peer.IsOwner
picker.Add(peerInfo)
}
// TODO: schedule a disconnect for old PeerClients once they are no longer in flight
s.peerMutex.Lock()
defer s.peerMutex.Unlock()
// Replace our current picker
s.conf.Picker = picker
// Update our health status
s.health.Status = Healthy
if len(errs) != 0 {
s.health.Status = UnHealthy
s.health.Message = strings.Join(errs, "|")
}
s.health.PeerCount = int32(picker.Size())
log.WithField("peers", peers).Info("Peers updated")
}
// GetPeers returns a peer client for the hash key provided
func (s *Instance) GetPeer(key string) (*PeerClient, error) {
s.peerMutex.RLock()
peer, err := s.conf.Picker.Get(key)
if err != nil {
s.peerMutex.RUnlock()
return nil, err
}
s.peerMutex.RUnlock()
return peer, nil
}
func (s *Instance) GetPeerList() []*PeerClient {
s.peerMutex.RLock()
defer s.peerMutex.RUnlock()
return s.conf.Picker.Peers()
}
// Describe fetches prometheus metrics to be registered
func (s *Instance) Describe(ch chan<- *prometheus.Desc) {
ch <- s.global.asyncMetrics.Desc()
ch <- s.global.broadcastMetrics.Desc()
}
// Collect fetches metrics from the server for use by prometheus
func (s *Instance) Collect(ch chan<- prometheus.Metric) {
ch <- s.global.asyncMetrics
ch <- s.global.broadcastMetrics
}