-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathratelimit.go
198 lines (171 loc) · 5.98 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
/**
* Tencent is pleased to support the open source community by making Polaris available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 grpcpolaris
import (
"context"
"fmt"
"strings"
"time"
"github.com/polarismesh/polaris-go/api"
"github.com/polarismesh/polaris-go/pkg/flow/data"
"github.com/polarismesh/polaris-go/pkg/model"
"github.com/polarismesh/specification/source/go/api/v1/traffic_manage"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// RateLimitInterceptor is a gRPC interceptor that implements rate limiting.
type RateLimitInterceptor struct {
namespace string
svcName string
limitAPI api.LimitAPI
}
// NewRateLimitInterceptor creates a new RateLimitInterceptor.
func NewRateLimitInterceptor() *RateLimitInterceptor {
polarisCtx, _ := PolarisContext()
return &RateLimitInterceptor{limitAPI: api.NewLimitAPIByContext(polarisCtx)}
}
// NewRateLimitInterceptor creates a new RateLimitInterceptor.
func newRateLimitInterceptor(sdkCtx api.SDKContext) *RateLimitInterceptor {
return &RateLimitInterceptor{limitAPI: api.NewLimitAPIByContext(sdkCtx)}
}
// WithNamespace sets the namespace of the service.
func (p *RateLimitInterceptor) WithNamespace(namespace string) *RateLimitInterceptor {
p.namespace = namespace
return p
}
// WithServiceName sets the service name.
func (p *RateLimitInterceptor) WithServiceName(svcName string) *RateLimitInterceptor {
p.svcName = svcName
return p
}
func (p *RateLimitInterceptor) StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, ss)
}
// UnaryInterceptor returns a unary interceptor for rate limiting.
func (p *RateLimitInterceptor) UnaryInterceptor(ctx context.Context, req interface{},
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
quotaReq := p.buildQuotaRequest(ctx, req, info.FullMethod)
if quotaReq == nil {
return handler(ctx, req)
}
future, err := p.limitAPI.GetQuota(quotaReq)
if nil != err {
GetLogger().Error("[Polaris][RateLimit] fail to get quota %#v: %v", quotaReq, err)
return handler(ctx, req)
}
if rsp := future.Get(); rsp.Code == api.QuotaResultLimited {
return nil, status.Error(codes.ResourceExhausted, rsp.Info)
}
return handler(ctx, req)
}
func (p *RateLimitInterceptor) buildQuotaRequest(ctx context.Context, req interface{}, method string) api.QuotaRequest {
fullMethodName := method
tokens := strings.Split(fullMethodName, "/")
if len(tokens) != 3 {
return nil
}
namespace := DefaultNamespace
if len(p.namespace) > 0 {
namespace = p.namespace
}
quotaReq := api.NewQuotaRequest()
quotaReq.SetNamespace(namespace)
quotaReq.SetService(extractBareServiceName(fullMethodName))
quotaReq.SetMethod(extractBareMethodName(fullMethodName))
if len(p.svcName) > 0 {
quotaReq.SetService(p.svcName)
quotaReq.SetMethod(fullMethodName)
}
matchs, ok := p.fetchArguments(quotaReq.(*model.QuotaRequestImpl))
if !ok {
return quotaReq
}
header, ok := metadata.FromIncomingContext(ctx)
if !ok {
header = metadata.MD{}
}
for i := range matchs {
item := matchs[i]
switch item.GetType() {
case traffic_manage.MatchArgument_CALLER_SERVICE:
serviceValues := header.Get(polarisCallerServiceKey)
namespaceValues := header.Get(polarisCallerNamespaceKey)
if len(serviceValues) > 0 && len(namespaceValues) > 0 {
quotaReq.AddArgument(model.BuildCallerServiceArgument(namespaceValues[0], serviceValues[0]))
}
case traffic_manage.MatchArgument_HEADER:
values := header.Get(item.GetKey())
if len(values) > 0 {
quotaReq.AddArgument(model.BuildHeaderArgument(item.GetKey(), fmt.Sprintf("%+v", values[0])))
}
case traffic_manage.MatchArgument_CALLER_IP:
if pr, ok := peer.FromContext(ctx); ok && pr.Addr != nil {
address := pr.Addr.String()
addrSlice := strings.Split(address, ":")
if len(addrSlice) == 2 {
clientIP := addrSlice[0]
quotaReq.AddArgument(model.BuildCallerIPArgument(clientIP))
}
}
}
}
return quotaReq
}
func (p *RateLimitInterceptor) fetchArguments(req *model.QuotaRequestImpl) ([]*traffic_manage.MatchArgument, bool) {
engine := p.limitAPI.SDKContext().GetEngine()
getRuleReq := &data.CommonRateLimitRequest{
DstService: model.ServiceKey{
Namespace: req.GetNamespace(),
Service: req.GetService(),
},
Trigger: model.NotifyTrigger{
EnableDstRateLimit: true,
},
ControlParam: model.ControlParam{
Timeout: time.Millisecond * 500,
},
}
if err := engine.SyncGetResources(getRuleReq); err != nil {
GetLogger().Error("[Polaris][RateLimit] ns:%s svc:%s get RateLimit Rule fail : %+v",
req.GetNamespace(), req.GetService(), err)
return nil, false
}
svcRule := getRuleReq.RateLimitRule
if svcRule == nil || svcRule.GetValue() == nil {
GetLogger().Warn("[Polaris][RateLimit] ns:%s svc:%s get RateLimit Rule is nil",
req.GetNamespace(), req.GetService())
return nil, false
}
rules, ok := svcRule.GetValue().(*traffic_manage.RateLimit)
if !ok {
GetLogger().Error("[Polaris][RateLimit] ns:%s svc:%s get RateLimit Rule invalid",
req.GetNamespace(), req.GetService())
return nil, false
}
ret := make([]*traffic_manage.MatchArgument, 0, 4)
for i := range rules.GetRules() {
rule := rules.GetRules()[i]
if len(rule.GetArguments()) == 0 {
continue
}
ret = append(ret, rule.Arguments...)
}
return ret, true
}