forked from smallnest/rpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselector.go
320 lines (270 loc) ยท 7 KB
/
selector.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
package client
import (
"container/ring"
"context"
"math"
"math/rand"
"net/url"
"sort"
"strconv"
"time"
"github.com/edwingeng/doublejump"
"github.com/valyala/fastrand"
)
type SelectFunc func(ctx context.Context, servicePath, serviceMethod string, args interface{}) string
// Selector defines selector that selects one service from candidates.
type Selector interface {
Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string // SelectFunc
UpdateServer(servers map[string]string)
}
func newSelector(selectMode SelectMode, servers map[string]string) Selector {
switch selectMode {
case RandomSelect:
return newRandomSelector(servers)
case RoundRobin:
return newRoundRobinSelector(servers)
case WeightedRoundRobin:
return newWeightedRoundRobinSelector(servers)
case WeightedICMP:
return newWeightedICMPSelector(servers)
case ConsistentHash:
return newConsistentHashSelector(servers)
case SelectByUser:
return nil
default:
return newRandomSelector(servers)
}
}
// randomSelector selects randomly.
type randomSelector struct {
servers []string
}
func newRandomSelector(servers map[string]string) Selector {
ss := make([]string, 0, len(servers))
for k := range servers {
ss = append(ss, k)
}
return &randomSelector{servers: ss}
}
func (s *randomSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
ss := s.servers
if len(ss) == 0 {
return ""
}
i := fastrand.Uint32n(uint32(len(ss)))
return ss[i]
}
func (s *randomSelector) UpdateServer(servers map[string]string) {
ss := make([]string, 0, len(servers))
for k := range servers {
ss = append(ss, k)
}
s.servers = ss
}
// roundRobinSelector selects servers with roundrobin.
type roundRobinSelector struct {
servers []string
i int
}
func newRoundRobinSelector(servers map[string]string) Selector {
ss := make([]string, 0, len(servers))
for k := range servers {
ss = append(ss, k)
}
return &roundRobinSelector{servers: ss}
}
func (s *roundRobinSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
ss := s.servers
if len(ss) == 0 {
return ""
}
i := s.i
i = i % len(ss)
s.i = i + 1
return ss[i]
}
func (s *roundRobinSelector) UpdateServer(servers map[string]string) {
ss := make([]string, 0, len(servers))
for k := range servers {
ss = append(ss, k)
}
s.servers = ss
}
// weightedRoundRobinSelector selects servers with weighted.
type weightedRoundRobinSelector struct {
servers []*Weighted
totalWeight int
rr *ring.Ring
}
func newWeightedRoundRobinSelector(servers map[string]string) Selector {
ss := createWeighted(servers)
s := &weightedRoundRobinSelector{servers: ss}
s.buildRing()
return s
}
func (s *weightedRoundRobinSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
ss := s.servers
if len(ss) == 0 {
return ""
}
val := s.rr.Value
s.rr = s.rr.Next()
return val.(*Weighted).Server
}
func (s *weightedRoundRobinSelector) UpdateServer(servers map[string]string) {
ss := createWeighted(servers)
s.buildRing()
s.servers = ss
}
func (s *weightedRoundRobinSelector) buildRing() {
s.totalWeight = 0
for _, w := range s.servers {
s.totalWeight += w.Weight
}
s.rr = ring.New(s.totalWeight)
for i := 0; i < s.totalWeight; i++ {
n := s.next()
s.rr.Value = n
s.rr = s.rr.Next()
}
}
func (s *weightedRoundRobinSelector) next() *Weighted {
if len(s.servers) == 0 {
return nil
}
n := len(s.servers)
if n == 0 {
return nil
}
if n == 1 {
return s.servers[0]
}
flag := 0
m := 0
for i := 0; i < n; i++ {
s.servers[i].CurrentWeight += s.servers[i].Weight
if s.servers[i].CurrentWeight > m {
m = s.servers[i].CurrentWeight
flag = i
}
}
s.servers[flag].CurrentWeight -= s.totalWeight
return s.servers[flag]
}
func createWeighted(servers map[string]string) []*Weighted {
ss := make([]*Weighted, 0, len(servers))
for k, metadata := range servers {
w := &Weighted{Server: k, Weight: 1}
if v, err := url.ParseQuery(metadata); err == nil {
ww := v.Get("weight")
if ww != "" {
if weight, err := strconv.Atoi(ww); err == nil {
w.Weight = weight
}
}
}
ss = append(ss, w)
}
return ss
}
type geoServer struct {
Server string
Latitude float64
Longitude float64
}
// geoSelector selects servers based on location.
type geoSelector struct {
servers []*geoServer
Latitude float64
Longitude float64
r *rand.Rand
}
func newGeoSelector(servers map[string]string, latitude, longitude float64) Selector {
ss := createGeoServer(servers)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return &geoSelector{servers: ss, Latitude: latitude, Longitude: longitude, r: r}
}
func (s *geoSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
if len(s.servers) == 0 {
return ""
}
var server []string
minNum := math.MaxFloat64
for _, gs := range s.servers {
d := getDistanceFrom(s.Latitude, s.Longitude, gs.Latitude, gs.Longitude)
if d < minNum {
server = []string{gs.Server}
minNum = d
} else if d == minNum {
server = append(server, gs.Server)
}
}
if len(server) == 1 {
return server[0]
}
return server[s.r.Intn(len(server))]
}
func (s *geoSelector) UpdateServer(servers map[string]string) {
ss := createGeoServer(servers)
s.servers = ss
}
func createGeoServer(servers map[string]string) []*geoServer {
geoServers := make([]*geoServer, 0, len(servers))
for s, metadata := range servers {
if v, err := url.ParseQuery(metadata); err == nil {
latStr := v.Get("latitude")
lonStr := v.Get("longitude")
if latStr == "" || lonStr == "" {
continue
}
lat, err := strconv.ParseFloat(latStr, 64)
if err != nil {
continue
}
lon, err := strconv.ParseFloat(lonStr, 64)
if err != nil {
continue
}
geoServers = append(geoServers, &geoServer{Server: s, Latitude: lat, Longitude: lon})
}
}
return geoServers
}
// consistentHashSelector selects based on JumpConsistentHash.
type consistentHashSelector struct {
h *doublejump.Hash
servers []string
}
func newConsistentHashSelector(servers map[string]string) Selector {
h := doublejump.NewHash()
ss := make([]string, 0, len(servers))
for k := range servers {
ss = append(ss, k)
h.Add(k)
}
sort.Slice(ss, func(i, j int) bool { return ss[i] < ss[j] })
return &consistentHashSelector{servers: ss, h: h}
}
func (s *consistentHashSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
ss := s.servers
if len(ss) == 0 {
return ""
}
key := genKey(servicePath, serviceMethod, args)
selected, _ := s.h.Get(key).(string)
return selected
}
func (s *consistentHashSelector) UpdateServer(servers map[string]string) {
ss := make([]string, 0, len(servers))
for k := range servers {
s.h.Add(k)
ss = append(ss, k)
}
sort.Slice(ss, func(i, j int) bool { return ss[i] < ss[j] })
for _, k := range s.servers {
if _, exist := servers[k]; !exist { // remove
s.h.Remove(k)
}
}
s.servers = ss
}