-
Notifications
You must be signed in to change notification settings - Fork 0
/
balance.go
91 lines (73 loc) · 1.75 KB
/
balance.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
package srad
import (
"errors"
"strconv"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/balancer/base"
)
const (
smoothWeightedRoundRobin = "smooth_weighted_round_robin"
)
var (
_ base.PickerBuilder = (*wrrPickerBuilder)(nil)
_ balancer.Picker = (*wrrPicker)(nil)
ErrNoPickerResult = errors.New("picker: no result")
)
func init() {
balancer.Register(newSmoothWRRBuilder())
}
func newSmoothWRRBuilder() balancer.Builder {
return base.NewBalancerBuilder(smoothWeightedRoundRobin, new(wrrPickerBuilder), base.Config{HealthCheck: true})
}
type wrrPickerBuilder struct{}
func (w *wrrPickerBuilder) Build(info base.PickerBuildInfo) balancer.Picker {
if len(info.ReadySCs) == 0 {
return base.NewErrPicker(balancer.ErrNoSubConnAvailable)
}
scs := make([]*connInfo, 0, len(info.ReadySCs))
var totalWeight, weight int64 = 0, 0
var err error
for sc, sci := range info.ReadySCs {
weightStr := sci.Address.BalancerAttributes.Value("weight").(string)
if weightStr == "" {
weight = 1
} else {
weight, err = strconv.ParseInt(weightStr, 10, 64)
if err != nil {
return base.NewErrPicker(err)
}
}
totalWeight += weight
ci := connInfo{
sc: sc,
weight: weight,
}
scs = append(scs, &ci)
}
return &wrrPicker{
connInfos: scs,
weight: totalWeight,
}
}
type connInfo struct {
sc balancer.SubConn
weight int64
current int64
}
type wrrPicker struct {
connInfos []*connInfo
weight int64
}
func (w *wrrPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
var bigest *connInfo
for _, v := range w.connInfos {
v.current += v.weight
if bigest == nil || v.current > bigest.current {
bigest = v
}
}
bigest.current -= w.weight
return balancer.PickResult{
SubConn: bigest.sc,
}, nil
}