/
routeruleimpl.go
386 lines (293 loc) · 10.3 KB
/
routeruleimpl.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 router
import (
"math/rand"
"regexp"
"strings"
"time"
"sync"
"github.com/alipay/sofa-mosn/pkg/api/v2"
"github.com/alipay/sofa-mosn/pkg/log"
"github.com/alipay/sofa-mosn/pkg/protocol"
httpmosn "github.com/alipay/sofa-mosn/pkg/protocol/http"
"github.com/alipay/sofa-mosn/pkg/types"
multimap "github.com/jwangsadinata/go-multimap/slicemultimap"
)
// NewRouteRuleImplBase
// new routerule implement basement
func NewRouteRuleImplBase(vHost *VirtualHostImpl, route *v2.Router) (RouteRuleImplBase, error) {
routeRuleImplBase := RouteRuleImplBase{
vHost: vHost,
routerMatch: route.Match,
routerAction: route.Route,
clusterName: route.Route.ClusterName,
randInstance: rand.New(rand.NewSource(time.Now().UnixNano())),
configHeaders: getRouterHeaders(route.Match.Headers),
}
routeRuleImplBase.weightedClusters, routeRuleImplBase.totalClusterWeight = getWeightedClusterEntry(route.Route.WeightedClusters)
routeRuleImplBase.policy = &routerPolicy{
retryOn: false,
retryTimeout: 0,
numRetries: 0,
}
// todo add header match to route base
// generate metadata match criteria from router's metadata
if len(route.Route.MetadataMatch) > 0 {
subsetLBMetaData := route.Route.MetadataMatch
routeRuleImplBase.metadataMatchCriteria = NewMetadataMatchCriteriaImpl(subsetLBMetaData)
routeRuleImplBase.metaData = getClusterMosnLBMetaDataMap(route.Route.MetadataMatch)
}
return routeRuleImplBase, nil
}
// Base implementation for all route entries.
type RouteRuleImplBase struct {
caseSensitive bool
prefixRewrite string
hostRewrite string
includeVirtualHostRateLimit bool
corsPolicy types.CorsPolicy //todo
vHost *VirtualHostImpl
autoHostRewrite bool
useWebSocket bool
clusterName string //
clusterHeaderName lowerCaseString
clusterNotFoundResponseCode httpmosn.Code
timeout time.Duration
runtime v2.RuntimeUInt32
hostRedirect string
pathRedirect string
httpsRedirect bool
retryPolicy *retryPolicyImpl
rateLimitPolicy *rateLimitPolicyImpl
routerAction v2.RouteAction
routerMatch v2.RouterMatch
shadowPolicy *shadowPolicyImpl
priority types.ResourcePriority
configHeaders []*types.HeaderData //
configQueryParameters []types.QueryParameterMatcher
weightedClusters map[string]weightedClusterEntry //key is the wcluster's name
totalClusterWeight uint32
hashPolicy hashPolicyImpl
metadataMatchCriteria *MetadataMatchCriteriaImpl
metaData types.RouteMetaData
requestHeadersParser *headerParser
responseHeadersParser *headerParser
opaqueConfig multimap.MultiMap
decorator *types.Decorator
directResponseCode httpmosn.Code
directResponseBody string
policy *routerPolicy
virtualClusters *VirtualClusterEntry
randInstance *rand.Rand
randMutex sync.Mutex
}
// types.RouterInfo
func (rri *RouteRuleImplBase) GetRouterName() string {
return ""
}
// types.Route
func (rri *RouteRuleImplBase) RedirectRule() types.RedirectRule {
return rri.RedirectRule()
}
func (rri *RouteRuleImplBase) RouteRule() types.RouteRule {
return rri
}
func (rri *RouteRuleImplBase) TraceDecorator() types.TraceDecorator {
return nil
}
// types.RouteRule
// Select Cluster for Routing
// if weighted cluster is nil, return clusterName directly, else
// select cluster from weighted-clusters
func (rri *RouteRuleImplBase) ClusterName() string {
if len(rri.weightedClusters) == 0 {
return rri.clusterName
}
// use randInstance to avoid global lock contention
rri.randMutex.Lock()
selectedValue := rri.randInstance.Intn(int(rri.totalClusterWeight))
rri.randMutex.Unlock()
for _, weightCluster := range rri.weightedClusters {
selectedValue = selectedValue - int(weightCluster.clusterWeight)
if selectedValue <= 0 {
return weightCluster.clusterName
}
}
log.DefaultLogger.Errorf("Something wrong when choosing weighted cluster")
return rri.clusterName
}
func (rri *RouteRuleImplBase) GlobalTimeout() time.Duration {
return rri.routerAction.Timeout
}
func (rri *RouteRuleImplBase) Priority() types.Priority {
return 0
}
func (rri *RouteRuleImplBase) VirtualHost() types.VirtualHost {
return rri.vHost
}
func (rri *RouteRuleImplBase) VirtualCluster(headers map[string]string) types.VirtualCluster {
return rri.virtualClusters
}
func (rri *RouteRuleImplBase) Policy() types.Policy {
return rri.policy
}
func (rri *RouteRuleImplBase) Metadata() types.RouteMetaData {
return rri.metaData
}
func (rri *RouteRuleImplBase) MetadataMatchCriteria(clusterName string) types.MetadataMatchCriteria {
// if clusterName belongs to a weighted cluster
if matchCriteria, ok := rri.weightedClusters[clusterName]; ok {
return matchCriteria.clusterMetadataMatchCriteria
}
return rri.metadataMatchCriteria
}
// todo
func (rri *RouteRuleImplBase) finalizePathHeader(headers map[string]string, matchedPath string) {
}
func (rri *RouteRuleImplBase) matchRoute(headers map[string]string, randomValue uint64) bool {
// todo check runtime
// 1. match headers' KV
if !ConfigUtilityInst.MatchHeaders(headers, rri.configHeaders) {
log.DefaultLogger.Errorf("RouteRuleImplBase matchRoute, match headers error")
return false
}
// 2. match query parameters
var queryParams types.QueryParams
if QueryString, ok := headers[protocol.MosnHeaderQueryStringKey]; ok {
queryParams = httpmosn.ParseQueryString(QueryString)
}
if len(queryParams) == 0 {
return true
}
if !ConfigUtilityInst.MatchQueryParams(queryParams, rri.configQueryParameters) {
log.DefaultLogger.Errorf("RouteRuleImplBase matchRoute, match query params error")
return false
}
return true
}
func (rri *RouteRuleImplBase) WeightedCluster() map[string]weightedClusterEntry {
return rri.weightedClusters
}
type SofaRouteRuleImpl struct {
RouteRuleImplBase
matchValue string
}
func (srri *SofaRouteRuleImpl) Matcher() string {
return srri.matchValue
}
func (srri *SofaRouteRuleImpl) MatchType() types.PathMatchType {
return types.SofaHeader
}
func (srri *SofaRouteRuleImpl) Match(headers map[string]string, randomValue uint64) types.Route {
if value, ok := headers[types.SofaRouteMatchKey]; ok {
if value == srri.matchValue || srri.matchValue == ".*" {
log.DefaultLogger.Debugf("Sofa router matches success")
return srri
}
log.DefaultLogger.Warnf(" Sofa router matches failure, service name = %s", value)
}
log.DefaultLogger.Debugf("No service key found in header, sofa router matcher failure")
return nil
}
type PathRouteRuleImpl struct {
RouteRuleImplBase
path string
}
func (prri *PathRouteRuleImpl) Matcher() string {
return prri.path
}
func (prri *PathRouteRuleImpl) MatchType() types.PathMatchType {
return types.Exact
}
// Exact Path Comparing
func (prri *PathRouteRuleImpl) Match(headers map[string]string, randomValue uint64) types.Route {
// match base rule first
log.StartLogger.Debugf("path route rule match invoked")
if prri.matchRoute(headers, randomValue) {
if headerPathValue, ok := headers[strings.ToLower(protocol.MosnHeaderPathKey)]; ok {
if prri.caseSensitive {
if headerPathValue == prri.path {
log.DefaultLogger.Debugf("path route rule match success in caseSensitive scene")
return prri
}
} else if strings.EqualFold(headerPathValue, prri.path) {
log.DefaultLogger.Debugf("path route rule match success with exact matching ")
return prri
}
}
}
log.DefaultLogger.Debugf("path route rule match failed")
return nil
}
// todo
func (prri *PathRouteRuleImpl) FinalizeRequestHeaders(headers map[string]string, requestInfo types.RequestInfo) {
prri.finalizePathHeader(headers, prri.path)
}
type PrefixRouteRuleImpl struct {
RouteRuleImplBase
prefix string
}
func (prei *PrefixRouteRuleImpl) Matcher() string {
return prei.prefix
}
func (prei *PrefixRouteRuleImpl) MatchType() types.PathMatchType {
return types.Prefix
}
// Compare Path's Prefix
func (prei *PrefixRouteRuleImpl) Match(headers map[string]string, randomValue uint64) types.Route {
if prei.matchRoute(headers, randomValue) {
if headerPathValue, ok := headers[strings.ToLower(protocol.MosnHeaderPathKey)]; ok {
if strings.HasPrefix(headerPathValue, prei.prefix) {
log.DefaultLogger.Debugf("prefix route rule match success")
return prei
}
}
}
log.DefaultLogger.Debugf("prefix route rule match failed")
return nil
}
func (prei *PrefixRouteRuleImpl) FinalizeRequestHeaders(headers map[string]string, requestInfo types.RequestInfo) {
prei.finalizePathHeader(headers, prei.prefix)
}
//
type RegexRouteRuleImpl struct {
RouteRuleImplBase
regexStr string
regexPattern regexp.Regexp
}
func (rrei *RegexRouteRuleImpl) Matcher() string {
return rrei.regexStr
}
func (rrei *RegexRouteRuleImpl) MatchType() types.PathMatchType {
return types.Regex
}
func (rrei *RegexRouteRuleImpl) Match(headers map[string]string, randomValue uint64) types.Route {
if rrei.matchRoute(headers, randomValue) {
if headerPathValue, ok := headers[strings.ToLower(protocol.MosnHeaderPathKey)]; ok {
if rrei.regexPattern.MatchString(headerPathValue) {
log.DefaultLogger.Debugf("regex route rule match success")
return rrei
}
}
}
log.DefaultLogger.Debugf("regex route rule match failed")
return nil
}
func (rrei *RegexRouteRuleImpl) FinalizeRequestHeaders(headers map[string]string, requestInfo types.RequestInfo) {
rrei.finalizePathHeader(headers, rrei.regexStr)
}