forked from grpc/grpc-go
/
clusterimpl.go
418 lines (369 loc) · 12.9 KB
/
clusterimpl.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
*
* Copyright 2020 gRPC authors.
*
* Licensed 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 clusterimpl implements the xds_cluster_impl balancing policy. It
// handles the cluster features (e.g. circuit_breaking, RPC dropping).
//
// Note that it doesn't handle name resolution, which is done by policy
// xds_cluster_resolver.
package clusterimpl
import (
"encoding/json"
"fmt"
"sync"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/internal"
"google.golang.org/grpc/internal/buffer"
"google.golang.org/grpc/internal/grpclog"
"google.golang.org/grpc/internal/grpcsync"
"google.golang.org/grpc/internal/pretty"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/serviceconfig"
"google.golang.org/grpc/xds/internal/balancer/loadstore"
xdsclient "google.golang.org/grpc/xds/internal/client"
"google.golang.org/grpc/xds/internal/client/load"
)
const (
// Name is the name of the cluster_impl balancer.
Name = "xds_cluster_impl_experimental"
defaultRequestCountMax = 1024
)
func init() {
balancer.Register(clusterImplBB{})
}
var newXDSClient func() (xdsClientInterface, error)
type clusterImplBB struct{}
func (clusterImplBB) Build(cc balancer.ClientConn, bOpts balancer.BuildOptions) balancer.Balancer {
b := &clusterImplBalancer{
ClientConn: cc,
bOpts: bOpts,
closed: grpcsync.NewEvent(),
done: grpcsync.NewEvent(),
loadWrapper: loadstore.NewWrapper(),
pickerUpdateCh: buffer.NewUnbounded(),
requestCountMax: defaultRequestCountMax,
}
b.logger = prefixLogger(b)
if newXDSClient != nil {
// For tests
client, err := newXDSClient()
if err != nil {
b.logger.Errorf("failed to create xds-client: %v", err)
return nil
}
b.xdsC = client
}
go b.run()
b.logger.Infof("Created")
return b
}
func (clusterImplBB) Name() string {
return Name
}
func (clusterImplBB) ParseConfig(c json.RawMessage) (serviceconfig.LoadBalancingConfig, error) {
return parseConfig(c)
}
// xdsClientInterface contains only the xds_client methods needed by LRS
// balancer. It's defined so we can override xdsclient in tests.
type xdsClientInterface interface {
ReportLoad(server string) (*load.Store, func())
Close()
}
type clusterImplBalancer struct {
balancer.ClientConn
// mu guarantees mutual exclusion between Close() and handling of picker
// update to the parent ClientConn in run(). It's to make sure that the
// run() goroutine doesn't send picker update to parent after the balancer
// is closed.
//
// It's only used by the run() goroutine, but not the other exported
// functions. Because the exported functions are guaranteed to be
// synchronized with Close().
mu sync.Mutex
closed *grpcsync.Event
done *grpcsync.Event
bOpts balancer.BuildOptions
logger *grpclog.PrefixLogger
xdsC xdsClientInterface
config *LBConfig
childLB balancer.Balancer
cancelLoadReport func()
edsServiceName string
lrsServerName string
loadWrapper *loadstore.Wrapper
clusterNameMu sync.Mutex
clusterName string
// childState/drops/requestCounter can only be accessed in run(). And run()
// is the only goroutine that sends picker to the parent ClientConn. All
// requests to update picker need to be sent to pickerUpdateCh.
childState balancer.State
drops []*dropper
requestCounter *xdsclient.ServiceRequestsCounter
requestCountMax uint32
pickerUpdateCh *buffer.Unbounded
}
// updateLoadStore checks the config for load store, and decides whether it
// needs to restart the load reporting stream.
func (cib *clusterImplBalancer) updateLoadStore(newConfig *LBConfig) error {
var updateLoadClusterAndService bool
// ClusterName is different, restart. ClusterName is from ClusterName and
// EDSServiceName.
clusterName := cib.getClusterName()
if clusterName != newConfig.Cluster {
updateLoadClusterAndService = true
cib.setClusterName(newConfig.Cluster)
clusterName = newConfig.Cluster
}
if cib.edsServiceName != newConfig.EDSServiceName {
updateLoadClusterAndService = true
cib.edsServiceName = newConfig.EDSServiceName
}
if updateLoadClusterAndService {
// This updates the clusterName and serviceName that will be reported
// for the loads. The update here is too early, the perfect timing is
// when the picker is updated with the new connection. But from this
// balancer's point of view, it's impossible to tell.
//
// On the other hand, this will almost never happen. Each LRS policy
// shouldn't get updated config. The parent should do a graceful switch
// when the clusterName or serviceName is changed.
cib.loadWrapper.UpdateClusterAndService(clusterName, cib.edsServiceName)
}
// Check if it's necessary to restart load report.
var newLRSServerName string
if newConfig.LoadReportingServerName != nil {
newLRSServerName = *newConfig.LoadReportingServerName
}
if cib.lrsServerName != newLRSServerName {
// LoadReportingServerName is different, load should be report to a
// different server, restart.
cib.lrsServerName = newLRSServerName
if cib.cancelLoadReport != nil {
cib.cancelLoadReport()
cib.cancelLoadReport = nil
}
var loadStore *load.Store
if cib.xdsC != nil {
loadStore, cib.cancelLoadReport = cib.xdsC.ReportLoad(cib.lrsServerName)
}
cib.loadWrapper.UpdateLoadStore(loadStore)
}
return nil
}
func (cib *clusterImplBalancer) UpdateClientConnState(s balancer.ClientConnState) error {
if cib.closed.HasFired() {
cib.logger.Warningf("xds: received ClientConnState {%+v} after clusterImplBalancer was closed", s)
return nil
}
cib.logger.Infof("Received update from resolver, balancer config: %+v", pretty.ToJSON(s.BalancerConfig))
newConfig, ok := s.BalancerConfig.(*LBConfig)
if !ok {
return fmt.Errorf("unexpected balancer config with type: %T", s.BalancerConfig)
}
// Need to check for potential errors at the beginning of this function, so
// that on errors, we reject the whole config, instead of applying part of
// it.
bb := balancer.Get(newConfig.ChildPolicy.Name)
if bb == nil {
return fmt.Errorf("balancer %q not registered", newConfig.ChildPolicy.Name)
}
if cib.xdsC == nil {
c := xdsclient.FromResolverState(s.ResolverState)
if c == nil {
return balancer.ErrBadResolverState
}
cib.xdsC = c
}
// Update load reporting config. This needs to be done before updating the
// child policy because we need the loadStore from the updated client to be
// passed to the ccWrapper, so that the next picker from the child policy
// will pick up the new loadStore.
if err := cib.updateLoadStore(newConfig); err != nil {
return err
}
// Compare new drop config. And update picker if it's changed.
var updatePicker bool
if cib.config == nil || !equalDropCategories(cib.config.DropCategories, newConfig.DropCategories) {
cib.drops = make([]*dropper, 0, len(newConfig.DropCategories))
for _, c := range newConfig.DropCategories {
cib.drops = append(cib.drops, newDropper(c))
}
updatePicker = true
}
// Compare cluster name. And update picker if it's changed, because circuit
// breaking's stream counter will be different.
if cib.config == nil || cib.config.Cluster != newConfig.Cluster {
cib.requestCounter = xdsclient.GetServiceRequestsCounter(newConfig.Cluster)
updatePicker = true
}
// Compare upper bound of stream count. And update picker if it's changed.
// This is also for circuit breaking.
var newRequestCountMax uint32 = 1024
if newConfig.MaxConcurrentRequests != nil {
newRequestCountMax = *newConfig.MaxConcurrentRequests
}
if cib.requestCountMax != newRequestCountMax {
cib.requestCountMax = newRequestCountMax
updatePicker = true
}
if updatePicker {
cib.pickerUpdateCh.Put(&dropConfigs{
drops: cib.drops,
requestCounter: cib.requestCounter,
requestCountMax: cib.requestCountMax,
})
}
// If child policy is a different type, recreate the sub-balancer.
if cib.config == nil || cib.config.ChildPolicy.Name != newConfig.ChildPolicy.Name {
if cib.childLB != nil {
cib.childLB.Close()
}
cib.childLB = bb.Build(cib, cib.bOpts)
}
cib.config = newConfig
if cib.childLB == nil {
// This is not an expected situation, and should be super rare in
// practice.
//
// When this happens, we already applied all the other configurations
// (drop/circuit breaking), but there's no child policy. This balancer
// will be stuck, and we report the error to the parent.
return fmt.Errorf("child policy is nil, this means balancer %q's Build() returned nil", newConfig.ChildPolicy.Name)
}
// Addresses and sub-balancer config are sent to sub-balancer.
return cib.childLB.UpdateClientConnState(balancer.ClientConnState{
ResolverState: s.ResolverState,
BalancerConfig: cib.config.ChildPolicy.Config,
})
}
func (cib *clusterImplBalancer) ResolverError(err error) {
if cib.closed.HasFired() {
cib.logger.Warningf("xds: received resolver error {%+v} after clusterImplBalancer was closed", err)
return
}
if cib.childLB != nil {
cib.childLB.ResolverError(err)
}
}
func (cib *clusterImplBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.SubConnState) {
if cib.closed.HasFired() {
cib.logger.Warningf("xds: received subconn state change {%+v, %+v} after clusterImplBalancer was closed", sc, s)
return
}
// Trigger re-resolution when a SubConn turns transient failure. This is
// necessary for the LogicalDNS in cluster_resolver policy to re-resolve.
//
// Note that this happens not only for the addresses from DNS, but also for
// EDS (cluster_impl doesn't know if it's DNS or EDS, only the parent
// knows). The parent priority policy is configured to ignore re-resolution
// signal from the EDS children.
if s.ConnectivityState == connectivity.TransientFailure {
cib.ClientConn.ResolveNow(resolver.ResolveNowOptions{})
}
if cib.childLB != nil {
cib.childLB.UpdateSubConnState(sc, s)
}
}
func (cib *clusterImplBalancer) Close() {
cib.mu.Lock()
cib.closed.Fire()
cib.mu.Unlock()
if cib.childLB != nil {
cib.childLB.Close()
cib.childLB = nil
}
if newXDSClient != nil {
cib.xdsC.Close()
}
<-cib.done.Done()
cib.logger.Infof("Shutdown")
}
// Override methods to accept updates from the child LB.
func (cib *clusterImplBalancer) UpdateState(state balancer.State) {
// Instead of updating parent ClientConn inline, send state to run().
cib.pickerUpdateCh.Put(state)
}
func (cib *clusterImplBalancer) setClusterName(n string) {
cib.clusterNameMu.Lock()
defer cib.clusterNameMu.Unlock()
cib.clusterName = n
}
func (cib *clusterImplBalancer) getClusterName() string {
cib.clusterNameMu.Lock()
defer cib.clusterNameMu.Unlock()
return cib.clusterName
}
func (cib *clusterImplBalancer) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
clusterName := cib.getClusterName()
newAddrs := make([]resolver.Address, len(addrs))
for i, addr := range addrs {
newAddrs[i] = internal.SetXDSHandshakeClusterName(addr, clusterName)
}
return cib.ClientConn.NewSubConn(newAddrs, opts)
}
func (cib *clusterImplBalancer) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) {
clusterName := cib.getClusterName()
newAddrs := make([]resolver.Address, len(addrs))
for i, addr := range addrs {
newAddrs[i] = internal.SetXDSHandshakeClusterName(addr, clusterName)
}
cib.ClientConn.UpdateAddresses(sc, newAddrs)
}
type dropConfigs struct {
drops []*dropper
requestCounter *xdsclient.ServiceRequestsCounter
requestCountMax uint32
}
func (cib *clusterImplBalancer) run() {
defer cib.done.Fire()
for {
select {
case update := <-cib.pickerUpdateCh.Get():
cib.pickerUpdateCh.Load()
cib.mu.Lock()
if cib.closed.HasFired() {
cib.mu.Unlock()
return
}
switch u := update.(type) {
case balancer.State:
cib.childState = u
cib.ClientConn.UpdateState(balancer.State{
ConnectivityState: cib.childState.ConnectivityState,
Picker: newDropPicker(cib.childState, &dropConfigs{
drops: cib.drops,
requestCounter: cib.requestCounter,
requestCountMax: cib.requestCountMax,
}, cib.loadWrapper),
})
case *dropConfigs:
cib.drops = u.drops
cib.requestCounter = u.requestCounter
if cib.childState.Picker != nil {
cib.ClientConn.UpdateState(balancer.State{
ConnectivityState: cib.childState.ConnectivityState,
Picker: newDropPicker(cib.childState, u, cib.loadWrapper),
})
}
}
cib.mu.Unlock()
case <-cib.closed.Done():
return
}
}
}