-
Notifications
You must be signed in to change notification settings - Fork 472
/
loadbalance_handler.go
executable file
·181 lines (163 loc) · 4.7 KB
/
loadbalance_handler.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
package handler
import (
"errors"
"fmt"
"strings"
"github.com/cenkalti/backoff"
"github.com/go-chassis/go-chassis/client/rest"
"github.com/go-chassis/go-chassis/control"
"github.com/go-chassis/go-chassis/core/archaius"
"github.com/go-chassis/go-chassis/core/common"
"github.com/go-chassis/go-chassis/core/invocation"
"github.com/go-chassis/go-chassis/core/lager"
"github.com/go-chassis/go-chassis/core/loadbalancer"
backoffUtil "github.com/go-chassis/go-chassis/pkg/backoff"
"github.com/go-chassis/go-chassis/session"
)
// LBHandler loadbalancer handler struct
type LBHandler struct{}
func (lb *LBHandler) getEndpoint(i *invocation.Invocation, lbConfig control.LoadBalancingConfig) (string, error) {
var strategyFun func() loadbalancer.Strategy
var err error
if i.Strategy == "" {
i.Strategy = lbConfig.Strategy
strategyFun, err = loadbalancer.GetStrategyPlugin(i.Strategy)
if err != nil {
lager.Logger.Errorf(err, loadbalancer.LBError{
Message: "Get strategy [" + i.Strategy + "] failed."}.Error())
}
} else {
strategyFun, err = loadbalancer.GetStrategyPlugin(i.Strategy)
if err != nil {
lager.Logger.Errorf(err, loadbalancer.LBError{
Message: "Get strategy [" + i.Strategy + "] failed."}.Error())
}
}
if len(i.Filters) == 0 {
i.Filters = lbConfig.Filters
}
var sessionID string
if i.Strategy == loadbalancer.StrategySessionStickiness {
sessionID = getSessionID(i)
}
s, err := loadbalancer.BuildStrategy(i.SourceServiceID, i.MicroServiceName, i.Protocol,
sessionID, i.Filters, strategyFun(), i.RouteTags)
if err != nil {
return "", err
}
ins, err := s.Pick()
if err != nil {
lbErr := loadbalancer.LBError{Message: err.Error()}
return "", lbErr
}
var ep string
if i.Protocol == "" {
i.Protocol = archaius.GetString("cse.references."+i.MicroServiceName+".transport", ins.DefaultProtocol)
}
if i.Protocol == "" {
for k := range ins.EndpointsMap {
i.Protocol = k
break
}
}
ep, ok := ins.EndpointsMap[i.Protocol]
if !ok {
errStr := fmt.Sprintf("No available instance support ["+i.Protocol+"] protocol,"+
" msName: "+i.MicroServiceName+" %v", ins.EndpointsMap)
lbErr := loadbalancer.LBError{Message: errStr}
lager.Logger.Errorf(nil, lbErr.Error())
return "", lbErr
}
return ep, nil
}
// Handle to handle the load balancing
func (lb *LBHandler) Handle(chain *Chain, i *invocation.Invocation, cb invocation.ResponseCallBack) {
lbConfig := control.DefaultPanel.GetLoadBalancing(*i)
if !lbConfig.RetryEnabled {
lb.handleWithNoRetry(chain, i, lbConfig, cb)
} else {
lb.handleWithRetry(chain, i, lbConfig, cb)
}
}
func (lb *LBHandler) handleWithNoRetry(chain *Chain, i *invocation.Invocation, lbConfig control.LoadBalancingConfig, cb invocation.ResponseCallBack) {
ep, err := lb.getEndpoint(i, lbConfig)
if err != nil {
writeErr(err, cb)
return
}
i.Endpoint = ep
chain.Next(i, cb)
}
func (lb *LBHandler) handleWithRetry(chain *Chain, i *invocation.Invocation, lbConfig control.LoadBalancingConfig, cb invocation.ResponseCallBack) {
retryOnSame := lbConfig.RetryOnSame
retryOnNext := lbConfig.RetryOnNext
handlerIndex := chain.HandlerIndex
var invResp *invocation.Response
for j := 0; j < retryOnNext+1; j++ {
// exchange and retry on the next server
ep, err := lb.getEndpoint(i, lbConfig)
if err != nil {
// if get endpoint failed, no need to retry
writeErr(err, cb)
return
}
// retry on the same server
lbBackoff := backoffUtil.GetBackOff(lbConfig.BackOffKind, lbConfig.BackOffMin, lbConfig.BackOffMax)
callTimes := 0
operation := func() error {
if callTimes == retryOnSame+1 {
return backoff.Permanent(errors.New("retry times expires"))
}
callTimes++
i.Endpoint = ep
var respErr error
chain.HandlerIndex = handlerIndex
chain.Next(i, func(r *invocation.Response) error {
if r != nil {
invResp = r
respErr = invResp.Err
return invResp.Err
}
return nil
})
return respErr
}
if err = backoff.Retry(operation, lbBackoff); err == nil {
break
}
}
if invResp == nil {
invResp = &invocation.Response{}
}
cb(invResp)
}
// Name returns loadbalancer string
func (lb *LBHandler) Name() string {
return "loadbalancer"
}
func newLBHandler() Handler {
return &LBHandler{}
}
func getSessionID(i *invocation.Invocation) string {
var metadata interface{}
switch i.Args.(type) {
case *rest.Request:
req := i.Args.(*rest.Request)
value := req.GetCookie(common.LBSessionID)
if value != "" {
metadata = value
}
default:
value := session.GetContextMetadata(i.Ctx, common.LBSessionID)
if value != "" {
cookieKey := strings.Split(string(value), "=")
if len(cookieKey) > 1 {
metadata = cookieKey[1]
}
}
}
if metadata == nil {
metadata = ""
}
return metadata.(string)
}