-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
ClusterImplLoadBalancer.java
341 lines (314 loc) · 12.8 KB
/
ClusterImplLoadBalancer.java
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
/*
* Copyright 2020 The 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 io.grpc.xds;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.xds.XdsSubchannelPickers.BUFFER_PICKER;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Attributes;
import io.grpc.ClientStreamTracer;
import io.grpc.ClientStreamTracer.StreamInfo;
import io.grpc.ConnectivityState;
import io.grpc.EquivalentAddressGroup;
import io.grpc.InternalLogId;
import io.grpc.LoadBalancer;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.internal.ObjectPool;
import io.grpc.util.ForwardingClientStreamTracer;
import io.grpc.util.ForwardingLoadBalancerHelper;
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
import io.grpc.xds.EnvoyProtoData.DropOverload;
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
import io.grpc.xds.LoadStatsManager.LoadStatsStore;
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
import io.grpc.xds.XdsLogger.XdsLogLevel;
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
import io.grpc.xds.XdsSubchannelPickers.ErrorPicker;
import io.grpc.xds.internal.sds.SslContextProviderSupplier;
import io.grpc.xds.internal.sds.TlsContextManager;
import io.grpc.xds.internal.sds.TlsContextManagerImpl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
/**
* Load balancer for cluster_impl_experimental LB policy. This LB policy is the child LB policy of
* the priority_experimental LB policy and the parent LB policy of the weighted_target_experimental
* LB policy in the xDS load balancing hierarchy. This LB policy applies cluster-level
* configurations to requests sent to the corresponding cluster, such as drop policies, circuit
* breakers.
*/
final class ClusterImplLoadBalancer extends LoadBalancer {
@VisibleForTesting
static final long DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS = 1024L;
@VisibleForTesting
static boolean enableCircuitBreaking =
Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"));
@VisibleForTesting
static boolean enableSecurity =
Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT"));
private final XdsLogger logger;
private final Helper helper;
private final ThreadSafeRandom random;
private final TlsContextManager tlsContextManager;
// The following fields are effectively final.
private String cluster;
@Nullable
private String edsServiceName;
private ObjectPool<XdsClient> xdsClientPool;
private XdsClient xdsClient;
private CallCounterProvider callCounterProvider;
private LoadStatsStore loadStatsStore;
private ClusterImplLbHelper childLbHelper;
private LoadBalancer childLb;
ClusterImplLoadBalancer(Helper helper) {
this(helper, ThreadSafeRandomImpl.instance, TlsContextManagerImpl.getInstance());
}
ClusterImplLoadBalancer(Helper helper, ThreadSafeRandom random,
TlsContextManager tlsContextManager) {
this.helper = checkNotNull(helper, "helper");
this.random = checkNotNull(random, "random");
this.tlsContextManager = checkNotNull(tlsContextManager, "tlsContextManager");
InternalLogId logId = InternalLogId.allocate("cluster-impl-lb", helper.getAuthority());
logger = XdsLogger.withLogId(logId);
logger.log(XdsLogLevel.INFO, "Created");
}
@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
Attributes attributes = resolvedAddresses.getAttributes();
if (xdsClientPool == null) {
xdsClientPool = attributes.get(InternalXdsAttributes.XDS_CLIENT_POOL);
xdsClient = xdsClientPool.getObject();
}
if (callCounterProvider == null) {
callCounterProvider = attributes.get(InternalXdsAttributes.CALL_COUNTER_PROVIDER);
}
ClusterImplConfig config =
(ClusterImplConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
if (cluster == null) {
cluster = config.cluster;
edsServiceName = config.edsServiceName;
childLbHelper = new ClusterImplLbHelper(
callCounterProvider.getOrCreate(config.cluster, config.edsServiceName));
childLb = config.childPolicy.getProvider().newLoadBalancer(childLbHelper);
// Assume load report server does not change throughout cluster lifetime.
if (config.lrsServerName != null) {
if (config.lrsServerName.isEmpty()) {
loadStatsStore = xdsClient.addClientStats(cluster, edsServiceName);
} else {
logger.log(XdsLogLevel.WARNING, "Can only report load to the same management server");
}
}
}
childLbHelper.updateDropPolicies(config.dropCategories);
childLbHelper.updateMaxConcurrentRequests(config.maxConcurrentRequests);
childLbHelper.updateSslContextProviderSupplier(config.tlsContext);
if (loadStatsStore != null) {
attributes = attributes.toBuilder()
.set(InternalXdsAttributes.ATTR_CLUSTER_SERVICE_LOAD_STATS_STORE, loadStatsStore).build();
}
childLb.handleResolvedAddresses(
resolvedAddresses.toBuilder()
.setAttributes(attributes)
.setLoadBalancingPolicyConfig(config.childPolicy.getConfig())
.build());
}
@Override
public void handleNameResolutionError(Status error) {
if (childLb != null) {
childLb.handleNameResolutionError(error);
} else {
helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new ErrorPicker(error));
}
}
@Override
public void shutdown() {
if (loadStatsStore != null) {
xdsClient.removeClientStats(cluster, edsServiceName);
}
if (childLb != null) {
childLb.shutdown();
childLbHelper = null;
}
if (xdsClient != null) {
xdsClient = xdsClientPool.returnObject(xdsClient);
}
}
@Override
public boolean canHandleEmptyAddressListFromNameResolution() {
return true;
}
/**
* A decorated {@link LoadBalancer.Helper} that applies configurations for connections
* or requests to endpoints in the cluster.
*/
private final class ClusterImplLbHelper extends ForwardingLoadBalancerHelper {
private final AtomicLong requestCount;
private ConnectivityState currentState = ConnectivityState.IDLE;
private SubchannelPicker currentPicker = BUFFER_PICKER;
private List<DropOverload> dropPolicies = Collections.emptyList();
private long maxConcurrentRequests = DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
@Nullable
private SslContextProviderSupplier sslContextProviderSupplier;
private ClusterImplLbHelper(AtomicLong requestCount) {
this.requestCount = requestCount;
}
@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
currentState = newState;
currentPicker = newPicker;
SubchannelPicker picker =
new RequestLimitingSubchannelPicker(newPicker, dropPolicies, maxConcurrentRequests);
delegate().updateBalancingState(newState, picker);
}
@Override
public Subchannel createSubchannel(CreateSubchannelArgs args) {
if (enableSecurity && sslContextProviderSupplier != null) {
List<EquivalentAddressGroup> addresses = new ArrayList<>();
for (EquivalentAddressGroup eag : args.getAddresses()) {
Attributes attributes =
eag.getAttributes().toBuilder()
.set(InternalXdsAttributes.ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER,
sslContextProviderSupplier)
.build();
addresses.add(new EquivalentAddressGroup(eag.getAddresses(), attributes));
}
args = args.toBuilder().setAddresses(addresses).build();
}
return delegate().createSubchannel(args);
}
@Override
protected Helper delegate() {
return helper;
}
private void updateDropPolicies(List<DropOverload> dropOverloads) {
if (!dropPolicies.equals(dropOverloads)) {
dropPolicies = dropOverloads;
updateBalancingState(currentState, currentPicker);
}
}
private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
return;
}
this.maxConcurrentRequests =
maxConcurrentRequests != null
? maxConcurrentRequests
: DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
updateBalancingState(currentState, currentPicker);
}
private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
UpstreamTlsContext currentTlsContext =
sslContextProviderSupplier != null
? sslContextProviderSupplier.getUpstreamTlsContext()
: null;
if (Objects.equals(currentTlsContext, tlsContext)) {
return;
}
if (sslContextProviderSupplier != null) {
sslContextProviderSupplier.close();
}
sslContextProviderSupplier =
tlsContext != null
? new SslContextProviderSupplier(tlsContext, tlsContextManager)
: null;
}
private class RequestLimitingSubchannelPicker extends SubchannelPicker {
private final SubchannelPicker delegate;
private final List<DropOverload> dropPolicies;
private final long maxConcurrentRequests;
private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
List<DropOverload> dropPolicies, long maxConcurrentRequests) {
this.delegate = delegate;
this.dropPolicies = dropPolicies;
this.maxConcurrentRequests = maxConcurrentRequests;
}
@Override
public PickResult pickSubchannel(PickSubchannelArgs args) {
for (DropOverload dropOverload : dropPolicies) {
int rand = random.nextInt(1_000_000);
if (rand < dropOverload.getDropsPerMillion()) {
logger.log(XdsLogLevel.INFO, "Drop request with category: {0}",
dropOverload.getCategory());
if (loadStatsStore != null) {
loadStatsStore.recordDroppedRequest(dropOverload.getCategory());
}
return PickResult.withDrop(
Status.UNAVAILABLE.withDescription("Dropped: " + dropOverload.getCategory()));
}
}
PickResult result = delegate.pickSubchannel(args);
if (enableCircuitBreaking) {
if (result.getStatus().isOk() && result.getSubchannel() != null) {
if (requestCount.get() >= maxConcurrentRequests) {
if (loadStatsStore != null) {
loadStatsStore.recordDroppedRequest();
}
return PickResult.withDrop(Status.UNAVAILABLE.withDescription(
"Cluster max concurrent requests limit exceeded"));
} else {
ClientStreamTracer.Factory tracerFactory = new RequestCountingStreamTracerFactory(
result.getStreamTracerFactory(), requestCount);
return PickResult.withSubchannel(result.getSubchannel(), tracerFactory);
}
}
}
return result;
}
}
}
/**
* Counts the number of outstanding requests.
*/
private static final class RequestCountingStreamTracerFactory
extends ClientStreamTracer.Factory {
@Nullable
private final ClientStreamTracer.Factory delegate;
private final AtomicLong counter;
private RequestCountingStreamTracerFactory(@Nullable ClientStreamTracer.Factory delegate,
AtomicLong counter) {
this.delegate = delegate;
this.counter = counter;
}
@Override
public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
counter.incrementAndGet();
if (delegate == null) {
return new ClientStreamTracer() {
@Override
public void streamClosed(Status status) {
counter.decrementAndGet();
}
};
}
final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
return new ForwardingClientStreamTracer() {
@Override
protected ClientStreamTracer delegate() {
return delegatedTracer;
}
@Override
public void streamClosed(Status status) {
counter.decrementAndGet();
delegate().streamClosed(status);
}
};
}
}
}