Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xds: implement WeightedTargetLoadBalancer #6731

Merged
merged 11 commits into from
Mar 11, 2020
23 changes: 2 additions & 21 deletions xds/src/main/java/io/grpc/xds/LocalityStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,12 @@
import io.grpc.xds.EnvoyProtoData.LbEndpoint;
import io.grpc.xds.EnvoyProtoData.Locality;
import io.grpc.xds.EnvoyProtoData.LocalityLbEndpoints;
import io.grpc.xds.InterLocalityPicker.WeightedChildPicker;
import io.grpc.xds.OrcaOobUtil.OrcaReportingConfig;
import io.grpc.xds.OrcaOobUtil.OrcaReportingHelperWrapper;
import io.grpc.xds.WeightedRandomPicker.WeightedChildPicker;
import io.grpc.xds.XdsLogger.XdsLogLevel;
import io.grpc.xds.XdsSubchannelPickers.ErrorPicker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -109,7 +108,6 @@ final class LocalityStoreImpl implements LocalityStore {

private final XdsLogger logger;
private final Helper helper;
private final PickerFactory pickerFactory;
private final LoadBalancerProvider loadBalancerProvider;
private final ThreadSafeRandom random;
private final LoadStatsStore loadStatsStore;
Expand All @@ -130,7 +128,6 @@ final class LocalityStoreImpl implements LocalityStore {
this(
logId,
helper,
pickerFactoryImpl,
lbRegistry,
ThreadSafeRandom.ThreadSafeRandomImpl.instance,
loadStatsStore,
Expand All @@ -142,14 +139,12 @@ final class LocalityStoreImpl implements LocalityStore {
LocalityStoreImpl(
InternalLogId logId,
Helper helper,
PickerFactory pickerFactory,
LoadBalancerRegistry lbRegistry,
ThreadSafeRandom random,
LoadStatsStore loadStatsStore,
OrcaPerRequestUtil orcaPerRequestUtil,
OrcaOobUtil orcaOobUtil) {
this.helper = checkNotNull(helper, "helper");
this.pickerFactory = checkNotNull(pickerFactory, "pickerFactory");
loadBalancerProvider = checkNotNull(
lbRegistry.getProvider(ROUND_ROBIN),
"Unable to find '%s' LoadBalancer", ROUND_ROBIN);
Expand All @@ -160,11 +155,6 @@ final class LocalityStoreImpl implements LocalityStore {
logger = XdsLogger.withLogId(checkNotNull(logId, "logId"));
}

@VisibleForTesting // Introduced for testing only.
interface PickerFactory {
SubchannelPicker picker(List<WeightedChildPicker> childPickers);
}

private final class DroppablePicker extends SubchannelPicker {

final List<DropOverload> dropOverloads;
Expand Down Expand Up @@ -206,14 +196,6 @@ public String toString() {
}
}

private static final PickerFactory pickerFactoryImpl =
new PickerFactory() {
@Override
public SubchannelPicker picker(List<WeightedChildPicker> childPickers) {
return new InterLocalityPicker(childPickers);
}
};

@Override
public void reset() {
for (Locality locality : localityMap.keySet()) {
Expand Down Expand Up @@ -335,7 +317,6 @@ private static ConnectivityState aggregateState(

private void updatePicker(
@Nullable ConnectivityState state, List<WeightedChildPicker> childPickers) {
childPickers = Collections.unmodifiableList(childPickers);
SubchannelPicker picker;
if (childPickers.isEmpty()) {
if (state == TRANSIENT_FAILURE) {
Expand All @@ -344,7 +325,7 @@ private void updatePicker(
picker = XdsSubchannelPickers.BUFFER_PICKER;
}
} else {
picker = pickerFactory.picker(childPickers);
picker = new WeightedRandomPicker(childPickers);
}

if (!dropOverloads.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,24 @@

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import io.grpc.LoadBalancer.PickResult;
import io.grpc.LoadBalancer.PickSubchannelArgs;
import io.grpc.LoadBalancer.SubchannelPicker;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

final class InterLocalityPicker extends SubchannelPicker {
final class WeightedRandomPicker extends SubchannelPicker {

@VisibleForTesting
final List<WeightedChildPicker> weightedChildPickers;

private final List<WeightedChildPicker> weightedChildPickers;
private final ThreadSafeRandom random;
private final int totalWeight;

static final class WeightedChildPicker {
final int weight;
final SubchannelPicker childPicker;
private final int weight;
private final SubchannelPicker childPicker;

WeightedChildPicker(int weight, SubchannelPicker childPicker) {
checkArgument(weight >= 0, "weight is negative");
Expand All @@ -53,6 +56,23 @@ SubchannelPicker getPicker() {
return childPicker;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WeightedChildPicker that = (WeightedChildPicker) o;
return weight == that.weight && Objects.equals(childPicker, that.childPicker);
}

@Override
public int hashCode() {
return Objects.hash(weight, childPicker);
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
Expand All @@ -62,16 +82,16 @@ public String toString() {
}
}

InterLocalityPicker(List<WeightedChildPicker> weightedChildPickers) {
WeightedRandomPicker(List<WeightedChildPicker> weightedChildPickers) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class structure does not help with testing at all, as in order to provide your own random number generator in test, you have to implement a fake WeightedPickerFactory instance whose picker(...) method creates a fake SubchannelPicker. So everything about picking is fake. This tests nothing.

Instead, a better strategy is to not have this constructor at all. You implementation code should always call the constructor with injectable random number generator. In that way, your test code is still executing the real WeightedRandomPicker but only with the random number generator being faked out.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WeightedPickerFactory does not claim to test anything that WeightedRandomPicker does. What WeightedRandomPicker does is well-tested in its own test with a fake random. Using WeightedPickerFactory in LocalityStoreTest/WeightedTargetLoadBalancerTest is to avoid re-testing WeightedRandomPicker. Passing a fake random instead of the factory toLocalityStore/WeightedTargetLoadBalancer in test, you need recalculate the relation between the weights and the fake random number, that's basically following the implementation details of WeightedRandomPicker.

We have argued about this a lot of times. When class A uses class B where B is well-tested with its own BTest. Then ATest will just use BFactory. BFactory does not claim to test anything of B. ATest does not claim to test any implementation detail encapsulated in B Using B's constructor arg instead of BFactory in ATest, you are retesting B again.

Now I revised the class not to use a factory, but I'm still not going to retest the well-encapsulated and well-tested class before EdsLoadBalancer is refactored to use WeightedTargetLoadBalancer.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test strategy is poor. It should be used only when the subcomponent B is heavy (i.e., small interface with large implementation). WeightedRandomPicker is completely an internal implementation of WeightedTargetLoadBalancer/LocalityStore, even though you write it as a modularized subcomponent. It's better even if WeightedRandomPicker is inlined in WeightedTargetLoadBalancer/LocalityStore. But in terms of code reuse, put it into a modularized class. Its implementation is not complex (even somewhat trivial), it's just using a random number generator to choose something in an input list. It is more like a utility. We are not keenly interested in testing the isolated behaviors of this sub-component. Instead, we are more interested in the real output of WeigtedTargetLoadBalancer/LocalityStore, which is the content of picker that eventually propagated to Channel (i.e., helper.updateBalancingState(State, Picker)).

The above is just my opinion. I am not going to block you on tests, as long as the class structure is obviously inappropriate. But really, existing tests test barely little real things...

this(weightedChildPickers, ThreadSafeRandom.ThreadSafeRandomImpl.instance);
}

@VisibleForTesting
InterLocalityPicker(List<WeightedChildPicker> weightedChildPickers, ThreadSafeRandom random) {
WeightedRandomPicker(List<WeightedChildPicker> weightedChildPickers, ThreadSafeRandom random) {
checkNotNull(weightedChildPickers, "weightedChildPickers in null");
checkArgument(!weightedChildPickers.isEmpty(), "weightedChildPickers is empty");

this.weightedChildPickers = ImmutableList.copyOf(weightedChildPickers);
this.weightedChildPickers = Collections.unmodifiableList(weightedChildPickers);

int totalWeight = 0;
for (WeightedChildPicker weightedChildPicker : weightedChildPickers) {
Expand Down
193 changes: 193 additions & 0 deletions xds/src/main/java/io/grpc/xds/WeightedTargetLoadBalancer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* 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.ConnectivityState.CONNECTING;
import static io.grpc.ConnectivityState.IDLE;
import static io.grpc.ConnectivityState.READY;
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
import static io.grpc.xds.XdsSubchannelPickers.BUFFER_PICKER;

import com.google.common.collect.ImmutableMap;
import io.grpc.ConnectivityState;
import io.grpc.InternalLogId;
import io.grpc.LoadBalancer;
import io.grpc.Status;
import io.grpc.util.ForwardingLoadBalancerHelper;
import io.grpc.util.GracefulSwitchLoadBalancer;
import io.grpc.xds.WeightedRandomPicker.WeightedChildPicker;
import io.grpc.xds.WeightedTargetLoadBalancerProvider.WeightedPolicySelection;
import io.grpc.xds.WeightedTargetLoadBalancerProvider.WeightedTargetConfig;
import io.grpc.xds.XdsLogger.XdsLogLevel;
import io.grpc.xds.XdsSubchannelPickers.ErrorPicker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/** Load balancer for weighted_target policy. */
final class WeightedTargetLoadBalancer extends LoadBalancer {

private final XdsLogger logger;
private final Map<String, GracefulSwitchLoadBalancer> childBalancers = new HashMap<>();
private final Map<String, ChildHelper> childHelpers = new HashMap<>();
private final Helper helper;

private Map<String, WeightedPolicySelection> targets = ImmutableMap.of();

WeightedTargetLoadBalancer(Helper helper) {
this.helper = helper;
logger = XdsLogger.withLogId(
InternalLogId.allocate("weighted-target-lb", helper.getAuthority()));
logger.log(XdsLogLevel.INFO, "Created");
}

@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
Object lbConfig = resolvedAddresses.getLoadBalancingPolicyConfig();
checkNotNull(lbConfig, "missing weighted_target lb config");

WeightedTargetConfig weightedTargetConfig = (WeightedTargetConfig) lbConfig;
Map<String, WeightedPolicySelection> newTargets = weightedTargetConfig.targets;

for (String targetName : newTargets.keySet()) {
WeightedPolicySelection weightedChildLbConfig = newTargets.get(targetName);
if (!targets.containsKey(targetName)) {
ChildHelper childHelper = new ChildHelper();
GracefulSwitchLoadBalancer childBalancer = new GracefulSwitchLoadBalancer(childHelper);
childBalancer.switchTo(weightedChildLbConfig.policySelection.getProvider());
childHelpers.put(targetName, childHelper);
childBalancers.put(targetName, childBalancer);
} else if (!weightedChildLbConfig.policySelection.getProvider().equals(
targets.get(targetName).policySelection.getProvider())) {
childBalancers.get(targetName)
.switchTo(weightedChildLbConfig.policySelection.getProvider());
}
}

targets = newTargets;

for (String targetName : targets.keySet()) {
childBalancers.get(targetName).handleResolvedAddresses(
resolvedAddresses.toBuilder()
.setLoadBalancingPolicyConfig(targets.get(targetName).policySelection.getConfig())
.build());
}

// Cleanup removed targets.
// TODO(zdapeng): cache removed target for 15 minutes.
for (String targetName : childBalancers.keySet()) {
if (!targets.containsKey(targetName)) {
childBalancers.get(targetName).shutdown();
}
}
childBalancers.keySet().retainAll(targets.keySet());
childHelpers.keySet().retainAll(targets.keySet());
}

@Override
public void handleNameResolutionError(Status error) {
logger.log(XdsLogLevel.WARNING, "Received name resolution error: {0}", error);
if (childBalancers.isEmpty()) {
helper.updateBalancingState(TRANSIENT_FAILURE, new ErrorPicker(error));
}
for (LoadBalancer childBalancer : childBalancers.values()) {
childBalancer.handleNameResolutionError(error);
}
}

@Override
public boolean canHandleEmptyAddressListFromNameResolution() {
return true;
}

@Override
public void shutdown() {
logger.log(XdsLogLevel.INFO, "Shutdown");
for (LoadBalancer childBalancer : childBalancers.values()) {
childBalancer.shutdown();
}
}

private void updateOverallBalancingState() {
List<WeightedChildPicker> childPickers = new ArrayList<>();

ConnectivityState overallState = null;
for (String name : targets.keySet()) {
ChildHelper childHelper = childHelpers.get(name);
ConnectivityState childState = childHelper.currentState;
overallState = aggregateState(overallState, childState);
if (READY == childState) {
int weight = targets.get(name).weight;
childPickers.add(new WeightedChildPicker(weight, childHelper.currentPicker));
}
}

SubchannelPicker picker;
if (childPickers.isEmpty()) {
if (overallState == TRANSIENT_FAILURE) {
picker = new ErrorPicker(Status.UNAVAILABLE); // TODO: more details in status
} else {
picker = XdsSubchannelPickers.BUFFER_PICKER;
}
} else {
picker = new WeightedRandomPicker(childPickers);
}

if (overallState != null) {
helper.updateBalancingState(overallState, picker);
}
}

@Nullable
private ConnectivityState aggregateState(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want to make a utility method for this, as it is used in a couple of places (for any load balancers that contain a bunch of child balancers).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is related to #6650. Might do it after the design in general is clear.

@Nullable ConnectivityState overallState, ConnectivityState childState) {
if (overallState == null) {
return childState;
}
if (overallState == READY || childState == READY) {
return READY;
}
if (overallState == CONNECTING || childState == CONNECTING) {
return CONNECTING;
}
if (overallState == IDLE || childState == IDLE) {
return IDLE;
}
return overallState;
}

private final class ChildHelper extends ForwardingLoadBalancerHelper {
ConnectivityState currentState = CONNECTING;
SubchannelPicker currentPicker = BUFFER_PICKER;

@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
currentState = newState;
currentPicker = newPicker;
updateOverallBalancingState();
}

@Override
protected Helper delegate() {
return helper;
}
}
}