forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLbPolicyConfiguration.java
More file actions
475 lines (416 loc) · 16.2 KB
/
LbPolicyConfiguration.java
File metadata and controls
475 lines (416 loc) · 16.2 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
* 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.rls;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import io.grpc.ChannelLogger.ChannelLogLevel;
import io.grpc.ConnectivityState;
import io.grpc.LoadBalancer;
import io.grpc.LoadBalancer.Helper;
import io.grpc.LoadBalancer.Subchannel;
import io.grpc.LoadBalancer.SubchannelPicker;
import io.grpc.LoadBalancerProvider;
import io.grpc.LoadBalancerRegistry;
import io.grpc.NameResolver.ConfigOrError;
import io.grpc.Status;
import io.grpc.internal.ObjectPool;
import io.grpc.rls.ChildLoadBalancerHelper.ChildLoadBalancerHelperProvider;
import io.grpc.rls.RlsProtoData.RouteLookupConfig;
import io.grpc.util.ForwardingLoadBalancerHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
/** Configuration for RLS load balancing policy. */
final class LbPolicyConfiguration {
private final RouteLookupConfig routeLookupConfig;
@Nullable
private final Map<String, ?> routeLookupChannelServiceConfig;
private final ChildLoadBalancingPolicy policy;
LbPolicyConfiguration(
RouteLookupConfig routeLookupConfig, @Nullable Map<String, ?> routeLookupChannelServiceConfig,
ChildLoadBalancingPolicy policy) {
this.routeLookupConfig = checkNotNull(routeLookupConfig, "routeLookupConfig");
this.routeLookupChannelServiceConfig = routeLookupChannelServiceConfig;
this.policy = checkNotNull(policy, "policy");
}
RouteLookupConfig getRouteLookupConfig() {
return routeLookupConfig;
}
@Nullable
Map<String, ?> getRouteLookupChannelServiceConfig() {
return routeLookupChannelServiceConfig;
}
ChildLoadBalancingPolicy getLoadBalancingPolicy() {
return policy;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LbPolicyConfiguration that = (LbPolicyConfiguration) o;
return Objects.equals(routeLookupConfig, that.routeLookupConfig)
&& Objects.equals(routeLookupChannelServiceConfig, that.routeLookupChannelServiceConfig)
&& Objects.equals(policy, that.policy);
}
@Override
public int hashCode() {
return Objects.hash(routeLookupConfig, routeLookupChannelServiceConfig, policy);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("routeLookupConfig", routeLookupConfig)
.add("routeLookupChannelServiceConfig", routeLookupChannelServiceConfig)
.add("policy", policy)
.toString();
}
/** ChildLoadBalancingPolicy is an elected child policy to delegate requests. */
static final class ChildLoadBalancingPolicy {
private final Map<String, Object> effectiveRawChildPolicy;
private final LoadBalancerProvider effectiveLbProvider;
private final String targetFieldName;
@VisibleForTesting
ChildLoadBalancingPolicy(
String targetFieldName,
Map<String, Object> effectiveRawChildPolicy,
LoadBalancerProvider effectiveLbProvider) {
checkArgument(
targetFieldName != null && !targetFieldName.isEmpty(),
"targetFieldName cannot be empty or null");
this.targetFieldName = targetFieldName;
this.effectiveRawChildPolicy =
checkNotNull(effectiveRawChildPolicy, "effectiveRawChildPolicy");
this.effectiveLbProvider = checkNotNull(effectiveLbProvider, "effectiveLbProvider");
}
/** Creates ChildLoadBalancingPolicy. */
@SuppressWarnings("unchecked")
static ChildLoadBalancingPolicy create(
String childPolicyConfigTargetFieldName, List<Map<String, ?>> childPolicies)
throws InvalidChildPolicyConfigException {
Map<String, Object> effectiveChildPolicy = null;
LoadBalancerProvider effectiveLbProvider = null;
List<String> policyTried = new ArrayList<>();
LoadBalancerRegistry lbRegistry = LoadBalancerRegistry.getDefaultRegistry();
for (Map<String, ?> childPolicy : childPolicies) {
if (childPolicy.isEmpty()) {
continue;
}
if (childPolicy.size() != 1) {
throw
new InvalidChildPolicyConfigException(
"childPolicy should have exactly one loadbalancing policy");
}
String policyName = childPolicy.keySet().iterator().next();
LoadBalancerProvider provider = lbRegistry.getProvider(policyName);
if (provider != null) {
effectiveLbProvider = provider;
effectiveChildPolicy = Collections.unmodifiableMap(childPolicy);
break;
}
policyTried.add(policyName);
}
if (effectiveChildPolicy == null) {
throw
new InvalidChildPolicyConfigException(
String.format("no valid childPolicy found, policy tried: %s", policyTried));
}
return
new ChildLoadBalancingPolicy(
childPolicyConfigTargetFieldName,
(Map<String, Object>) effectiveChildPolicy.values().iterator().next(),
effectiveLbProvider);
}
/** Creates a child load balancer config for given target from elected raw child policy. */
Map<String, ?> getEffectiveChildPolicy(String target) {
Map<String, Object> childPolicy = new HashMap<>(effectiveRawChildPolicy);
childPolicy.put(targetFieldName, target);
return childPolicy;
}
/** Returns the elected child {@link LoadBalancerProvider}. */
LoadBalancerProvider getEffectiveLbProvider() {
return effectiveLbProvider;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ChildLoadBalancingPolicy that = (ChildLoadBalancingPolicy) o;
return Objects.equals(effectiveRawChildPolicy, that.effectiveRawChildPolicy)
&& Objects.equals(effectiveLbProvider, that.effectiveLbProvider)
&& Objects.equals(targetFieldName, that.targetFieldName);
}
@Override
public int hashCode() {
return Objects.hash(effectiveRawChildPolicy, effectiveLbProvider, targetFieldName);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("effectiveRawChildPolicy", effectiveRawChildPolicy)
.add("effectiveLbProvider", effectiveLbProvider)
.add("childPolicyConfigTargetFieldName", targetFieldName)
.toString();
}
}
/** Factory for {@link ChildPolicyWrapper}. Not thread-safe. */
static final class RefCountedChildPolicyWrapperFactory {
@VisibleForTesting
final Map<String /* target */, RefCountedChildPolicyWrapper> childPolicyMap =
new HashMap<>();
private final ChildLoadBalancerHelperProvider childLbHelperProvider;
private final ChildLoadBalancingPolicy childPolicy;
private ResolvedAddressFactory childLbResolvedAddressFactory;
public RefCountedChildPolicyWrapperFactory(
ChildLoadBalancingPolicy childPolicy,
ResolvedAddressFactory childLbResolvedAddressFactory,
ChildLoadBalancerHelperProvider childLbHelperProvider) {
this.childPolicy = checkNotNull(childPolicy, "childPolicy");
this.childLbResolvedAddressFactory =
checkNotNull(childLbResolvedAddressFactory, "childLbResolvedAddressFactory");
this.childLbHelperProvider = checkNotNull(childLbHelperProvider, "childLbHelperProvider");
}
void init() {
childLbHelperProvider.init();
}
Status acceptResolvedAddressFactory(ResolvedAddressFactory childLbResolvedAddressFactory) {
this.childLbResolvedAddressFactory = childLbResolvedAddressFactory;
Status status = Status.OK;
for (RefCountedChildPolicyWrapper wrapper : childPolicyMap.values()) {
Status newStatus =
wrapper.childPolicyWrapper.acceptResolvedAddressFactory(childLbResolvedAddressFactory);
if (!newStatus.isOk()) {
status = newStatus;
}
}
return status;
}
ChildPolicyWrapper createOrGet(String target) {
// TODO(creamsoup) check if the target is valid or not
RefCountedChildPolicyWrapper pooledChildPolicyWrapper = childPolicyMap.get(target);
if (pooledChildPolicyWrapper == null) {
ChildPolicyWrapper childPolicyWrapper = new ChildPolicyWrapper(
target, childPolicy, childLbHelperProvider);
pooledChildPolicyWrapper = RefCountedChildPolicyWrapper.of(childPolicyWrapper);
childPolicyMap.put(target, pooledChildPolicyWrapper);
childPolicyWrapper.start(childLbResolvedAddressFactory);
return pooledChildPolicyWrapper.getObject();
} else {
ChildPolicyWrapper childPolicyWrapper = pooledChildPolicyWrapper.getObject();
if (childPolicyWrapper.getPicker() != null) {
childPolicyWrapper.refreshState();
}
return childPolicyWrapper;
}
}
List<ChildPolicyWrapper> createOrGet(List<String> targets) {
List<ChildPolicyWrapper> retVal = new ArrayList<>();
for (String target : targets) {
retVal.add(createOrGet(target));
}
return retVal;
}
void release(ChildPolicyWrapper childPolicyWrapper) {
checkNotNull(childPolicyWrapper, "childPolicyWrapper");
String target = childPolicyWrapper.getTarget();
RefCountedChildPolicyWrapper existing = childPolicyMap.get(target);
checkState(existing != null, "Cannot access already released object");
existing.returnObject(childPolicyWrapper);
if (existing.isReleased()) {
childPolicyMap.remove(target);
}
}
}
/**
* ChildPolicyWrapper is a wrapper class for child load balancing policy with associated helper /
* utility classes to manage the child policy.
*/
static final class ChildPolicyWrapper {
private final String target;
private final ChildPolicyReportingHelper helper;
private final LoadBalancer lb;
private final Object childLbConfig;
private volatile SubchannelPicker picker;
private ConnectivityState state;
public ChildPolicyWrapper(
String target,
ChildLoadBalancingPolicy childPolicy,
ChildLoadBalancerHelperProvider childLbHelperProvider) {
this.target = target;
this.helper = new ChildPolicyReportingHelper(childLbHelperProvider);
LoadBalancerProvider lbProvider = childPolicy.getEffectiveLbProvider();
final ConfigOrError lbConfig =
lbProvider
.parseLoadBalancingPolicyConfig(
childPolicy.getEffectiveChildPolicy(target));
this.lb = lbProvider.newLoadBalancer(helper);
this.childLbConfig = lbConfig.getConfig();
helper.getChannelLogger().log(
ChannelLogLevel.DEBUG, "RLS child lb created. config: {0}", childLbConfig);
}
void start(ResolvedAddressFactory childLbResolvedAddressFactory) {
helper.getSynchronizationContext().execute(
new Runnable() {
@Override
public void run() {
if (!acceptResolvedAddressFactory(childLbResolvedAddressFactory).isOk()) {
helper.refreshNameResolution();
}
lb.requestConnection();
}
});
}
Status acceptResolvedAddressFactory(ResolvedAddressFactory childLbResolvedAddressFactory) {
helper.getSynchronizationContext().throwIfNotInThisSynchronizationContext();
return lb.acceptResolvedAddresses(childLbResolvedAddressFactory.create(childLbConfig));
}
String getTarget() {
return target;
}
SubchannelPicker getPicker() {
return picker;
}
ChildPolicyReportingHelper getHelper() {
return helper;
}
public ConnectivityState getState() {
return state;
}
void refreshState() {
helper.getSynchronizationContext().execute(
new Runnable() {
@Override
public void run() {
helper.updateBalancingState(state, picker);
}
}
);
}
void shutdown() {
helper.getSynchronizationContext().execute(
new Runnable() {
@Override
public void run() {
lb.shutdown();
}
}
);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("target", target)
.add("picker", picker)
.add("state", state)
.toString();
}
/**
* A delegating {@link io.grpc.LoadBalancer.Helper} maintains status of {@link
* ChildPolicyWrapper} when {@link Subchannel} status changed. This helper is used between child
* policy and parent load-balancer where each picker in child policy is governed by a governing
* picker (RlsPicker). The governing picker will be reported back to the parent load-balancer.
*/
final class ChildPolicyReportingHelper extends ForwardingLoadBalancerHelper {
private final ChildLoadBalancerHelper delegate;
ChildPolicyReportingHelper(
ChildLoadBalancerHelperProvider childHelperProvider) {
checkNotNull(childHelperProvider, "childHelperProvider");
this.delegate = childHelperProvider.forTarget(getTarget());
}
@Override
protected Helper delegate() {
return delegate;
}
@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
picker = newPicker;
state = newState;
super.updateBalancingState(newState, newPicker);
}
}
}
private static final class RefCountedChildPolicyWrapper
implements ObjectPool<ChildPolicyWrapper> {
private long refCnt;
@Nullable
private ChildPolicyWrapper childPolicyWrapper;
private RefCountedChildPolicyWrapper(ChildPolicyWrapper childPolicyWrapper) {
this.childPolicyWrapper = checkNotNull(childPolicyWrapper, "childPolicyWrapper");
}
@Override
public ChildPolicyWrapper getObject() {
checkState(!isReleased(), "ChildPolicyWrapper is already released");
refCnt++;
return childPolicyWrapper;
}
@Override
@Nullable
public ChildPolicyWrapper returnObject(Object object) {
checkState(
!isReleased(),
"cannot return already released ChildPolicyWrapper, this is possibly a bug.");
checkState(
childPolicyWrapper == object,
"returned object doesn't match the pooled childPolicyWrapper");
long newCnt = --refCnt;
checkState(newCnt != -1, "Cannot return never pooled childPolicyWrapper");
if (newCnt == 0) {
childPolicyWrapper.shutdown();
childPolicyWrapper = null;
}
return null;
}
boolean isReleased() {
return childPolicyWrapper == null;
}
static RefCountedChildPolicyWrapper of(ChildPolicyWrapper childPolicyWrapper) {
return new RefCountedChildPolicyWrapper(childPolicyWrapper);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("object", childPolicyWrapper)
.add("refCnt", refCnt)
.toString();
}
}
/** Exception thrown when attempting to parse child policy encountered parsing issue. */
static final class InvalidChildPolicyConfigException extends Exception {
private static final long serialVersionUID = 0L;
InvalidChildPolicyConfigException(String message) {
super(message);
}
@Override
public synchronized Throwable fillInStackTrace() {
// no stack trace above this point
return this;
}
}
}