-
Notifications
You must be signed in to change notification settings - Fork 307
/
ratelimit.go
322 lines (283 loc) · 10.4 KB
/
ratelimit.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 Envoy Gateway Authors
// SPDX-License-Identifier: Apache-2.0
// The full text of the Apache license is available in the LICENSE file at
// the root of the repo.
package translator
import (
"bytes"
"strconv"
"time"
cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
ratelimit "github.com/envoyproxy/go-control-plane/envoy/config/ratelimit/v3"
routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
ratelimitfilter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ratelimit/v3"
hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
wkt "github.com/envoyproxy/go-control-plane/pkg/wellknown"
ratelimitserviceconfig "github.com/envoyproxy/ratelimit/src/config"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
goyaml "gopkg.in/yaml.v3" // nolint: depguard
"github.com/envoyproxy/gateway/internal/ir"
)
// patchHCMWithRateLimit builds and appends the Rate Limit Filter to the HTTP connection manager
// if applicable and it does not already exist.
func patchHCMWithRateLimit(mgr *hcm.HttpConnectionManager, irListener *ir.HTTPListener) {
// Return early if rate limits dont exist
if !isRateLimitPresent(irListener) {
return
}
// Return early if filter already exists.
for _, httpFilter := range mgr.HttpFilters {
if httpFilter.Name == wkt.HTTPRateLimit {
return
}
}
rateLimitFilter := buildRateLimitFilter(irListener)
// Make sure the router filter is the terminal filter in the chain.
mgr.HttpFilters = append([]*hcm.HttpFilter{rateLimitFilter}, mgr.HttpFilters...)
}
// isRateLimitPresent returns true if rate limit config exists for the listener.
func isRateLimitPresent(irListener *ir.HTTPListener) bool {
// Return true if rate limit config exists.
for _, route := range irListener.Routes {
if route.RateLimit != nil && route.RateLimit.Global != nil {
return true
}
}
return false
}
func buildRateLimitFilter(irListener *ir.HTTPListener) *hcm.HttpFilter {
rateLimitFilterProto := &ratelimitfilter.RateLimit{
Domain: getRateLimitDomain(irListener),
RateLimitService: &ratelimit.RateLimitServiceConfig{
GrpcService: &core.GrpcService{
TargetSpecifier: &core.GrpcService_EnvoyGrpc_{
EnvoyGrpc: &core.GrpcService_EnvoyGrpc{
ClusterName: getRateLimitServiceClusterName(),
},
},
},
TransportApiVersion: core.ApiVersion_V3,
},
}
rateLimitFilterAny, err := anypb.New(rateLimitFilterProto)
if err != nil {
return nil
}
rateLimitFilter := &hcm.HttpFilter{
Name: wkt.HTTPRateLimit,
ConfigType: &hcm.HttpFilter_TypedConfig{
TypedConfig: rateLimitFilterAny,
},
}
return rateLimitFilter
}
// patchRouteWithRateLimit builds rate limit actions and appends to the route.
func patchRouteWithRateLimit(xdsRouteAction *routev3.RouteAction, irRoute *ir.HTTPRoute) error { //nolint:unparam
// Return early if no rate limit config exists.
if irRoute.RateLimit == nil || irRoute.RateLimit.Global == nil {
return nil
}
rateLimits := buildRouteRateLimits(irRoute.Name, irRoute.RateLimit.Global)
xdsRouteAction.RateLimits = rateLimits
return nil
}
func buildRouteRateLimits(descriptorPrefix string, global *ir.GlobalRateLimit) []*routev3.RateLimit {
rateLimits := []*routev3.RateLimit{}
// Rules are ORed
for rIdx, rule := range global.Rules {
rlActions := []*routev3.RateLimit_Action{}
// Matches are ANDed
for mIdx, match := range rule.HeaderMatches {
// Case for distinct match
if match.Distinct {
// Setup RequestHeader actions
descriptorKey := getRateLimitDescriptorKey(descriptorPrefix, rIdx, mIdx)
action := &routev3.RateLimit_Action{
ActionSpecifier: &routev3.RateLimit_Action_RequestHeaders_{
RequestHeaders: &routev3.RateLimit_Action_RequestHeaders{
HeaderName: match.Name,
DescriptorKey: descriptorKey,
},
},
}
rlActions = append(rlActions, action)
} else {
// Setup HeaderValueMatch actions
descriptorKey := getRateLimitDescriptorKey(descriptorPrefix, rIdx, mIdx)
descriptorVal := getRateLimitDescriptorValue(descriptorPrefix, rIdx, mIdx)
headerMatcher := &routev3.HeaderMatcher{
Name: match.Name,
HeaderMatchSpecifier: &routev3.HeaderMatcher_StringMatch{
StringMatch: buildXdsStringMatcher(match),
},
}
action := &routev3.RateLimit_Action{
ActionSpecifier: &routev3.RateLimit_Action_HeaderValueMatch_{
HeaderValueMatch: &routev3.RateLimit_Action_HeaderValueMatch{
DescriptorKey: descriptorKey,
DescriptorValue: descriptorVal,
ExpectMatch: &wrapperspb.BoolValue{
Value: true,
},
Headers: []*routev3.HeaderMatcher{headerMatcher},
},
},
}
rlActions = append(rlActions, action)
}
}
// Case when header match is not set and the rate limit is applied
// to all traffic.
if len(rule.HeaderMatches) == 0 {
// Setup GenericKey action
action := &routev3.RateLimit_Action{
ActionSpecifier: &routev3.RateLimit_Action_GenericKey_{
GenericKey: &routev3.RateLimit_Action_GenericKey{
DescriptorKey: getRateLimitDescriptorKey(descriptorPrefix, rIdx, -1),
DescriptorValue: getRateLimitDescriptorValue(descriptorPrefix, rIdx, -1),
},
},
}
rlActions = append(rlActions, action)
}
rateLimit := &routev3.RateLimit{Actions: rlActions}
rateLimits = append(rateLimits, rateLimit)
}
return rateLimits
}
// GetRateLimitServiceConfigStr returns the YAML string for the rate limit service configuration.
func GetRateLimitServiceConfigStr(yamlRoot *ratelimitserviceconfig.YamlRoot) (string, error) {
var buf bytes.Buffer
enc := goyaml.NewEncoder(&buf)
enc.SetIndent(2)
err := enc.Encode(*yamlRoot)
return buf.String(), err
}
// BuildRateLimitServiceConfig builds the rate limit service configuration based on
// https://github.com/envoyproxy/ratelimit#the-configuration-format
func BuildRateLimitServiceConfig(irListener *ir.HTTPListener) *ratelimitserviceconfig.YamlRoot {
yamlDescs := make([]ratelimitserviceconfig.YamlDescriptor, 0, 1)
for _, route := range irListener.Routes {
if route.RateLimit != nil && route.RateLimit.Global != nil {
descs := buildRateLimitServiceDescriptors(route.Name, route.RateLimit.Global)
yamlDescs = append(yamlDescs, descs...)
}
}
if len(yamlDescs) == 0 {
return nil
}
return &ratelimitserviceconfig.YamlRoot{
Domain: getRateLimitDomain(irListener),
Descriptors: yamlDescs,
}
}
// buildRateLimitServiceDescriptors creates the rate limit service yaml descriptors based on the global rate limit IR config.
func buildRateLimitServiceDescriptors(descriptorPrefix string, global *ir.GlobalRateLimit) []ratelimitserviceconfig.YamlDescriptor {
yamlDescs := make([]ratelimitserviceconfig.YamlDescriptor, 0, 1)
for rIdx, rule := range global.Rules {
var head, cur *ratelimitserviceconfig.YamlDescriptor
if len(rule.HeaderMatches) == 0 {
yamlDesc := new(ratelimitserviceconfig.YamlDescriptor)
// GenericKey case
yamlDesc.Key = getRateLimitDescriptorKey(descriptorPrefix, rIdx, -1)
yamlDesc.Value = getRateLimitDescriptorValue(descriptorPrefix, rIdx, -1)
rateLimit := ratelimitserviceconfig.YamlRateLimit{
RequestsPerUnit: uint32(rule.Limit.Requests),
Unit: string(rule.Limit.Unit),
}
yamlDesc.RateLimit = &rateLimit
head = yamlDesc
cur = head
}
for mIdx, match := range rule.HeaderMatches {
yamlDesc := new(ratelimitserviceconfig.YamlDescriptor)
// Case for distinct match
if match.Distinct {
// RequestHeader case
yamlDesc.Key = getRateLimitDescriptorKey(descriptorPrefix, rIdx, mIdx)
} else {
// HeaderValueMatch case
yamlDesc.Key = getRateLimitDescriptorKey(descriptorPrefix, rIdx, mIdx)
yamlDesc.Value = getRateLimitDescriptorValue(descriptorPrefix, rIdx, mIdx)
}
// Add the ratelimit values to the last descriptor
if mIdx == len(rule.HeaderMatches)-1 {
rateLimit := ratelimitserviceconfig.YamlRateLimit{
RequestsPerUnit: uint32(rule.Limit.Requests),
Unit: string(rule.Limit.Unit),
}
yamlDesc.RateLimit = &rateLimit
}
if mIdx == 0 {
head = yamlDesc
} else {
cur.Descriptors = []ratelimitserviceconfig.YamlDescriptor{*yamlDesc}
}
cur = yamlDesc
}
yamlDescs = append(yamlDescs, *head)
}
return yamlDescs
}
func buildRateLimitServiceCluster(irListener *ir.HTTPListener) *cluster.Cluster {
// Return early if rate limits dont exist.
if !isRateLimitPresent(irListener) {
return nil
}
clusterName := getRateLimitServiceClusterName()
host, port := getRateLimitServiceGrpcHostPort()
rateLimitServerCluster := &cluster.Cluster{
Name: clusterName,
ClusterDiscoveryType: &cluster.Cluster_Type{Type: cluster.Cluster_STRICT_DNS},
ConnectTimeout: durationpb.New(10 * time.Second),
LbPolicy: cluster.Cluster_RANDOM,
LoadAssignment: &endpoint.ClusterLoadAssignment{
ClusterName: clusterName,
Endpoints: []*endpoint.LocalityLbEndpoints{
{
LbEndpoints: []*endpoint.LbEndpoint{
{
HostIdentifier: &endpoint.LbEndpoint_Endpoint{
Endpoint: &endpoint.Endpoint{
Address: &core.Address{
Address: &core.Address_SocketAddress{
SocketAddress: &core.SocketAddress{
Address: host,
PortSpecifier: &core.SocketAddress_PortValue{PortValue: uint32(port)},
},
},
},
},
},
},
},
},
},
},
Http2ProtocolOptions: &core.Http2ProtocolOptions{},
DnsRefreshRate: durationpb.New(30 * time.Second),
RespectDnsTtl: true,
DnsLookupFamily: cluster.Cluster_V4_ONLY,
}
return rateLimitServerCluster
}
func getRateLimitDescriptorKey(prefix string, ruleIndex, matchIndex int) string {
return prefix + "-key-rule-" + strconv.Itoa(ruleIndex) + "-match-" + strconv.Itoa(matchIndex)
}
func getRateLimitDescriptorValue(prefix string, ruleIndex, matchIndex int) string {
return prefix + "-value-rule-" + strconv.Itoa(ruleIndex) + "-match-" + strconv.Itoa(matchIndex)
}
func getRateLimitServiceClusterName() string {
return "ratelimit_cluster"
}
func getRateLimitDomain(irListener *ir.HTTPListener) string {
// Use IR listener name as domain
return irListener.Name
}
func getRateLimitServiceGrpcHostPort() (string, int) {
return "TODO", 0
}