Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 10 additions & 80 deletions core/src/main/java/io/grpc/internal/PickFirstLeafLoadBalancer.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ final class PickFirstLeafLoadBalancer extends LoadBalancer {
private static final Logger log = Logger.getLogger(PickFirstLeafLoadBalancer.class.getName());
@VisibleForTesting
static final int CONNECTION_DELAY_INTERVAL_MS = 250;
private final boolean enableHappyEyeballs = !isSerializingRetries()
&& PickFirstLoadBalancerProvider.isEnabledHappyEyeballs();
private final boolean enableHappyEyeballs =
PickFirstLoadBalancerProvider.isEnabledHappyEyeballs();
static boolean weightedShuffling =
GrpcUtil.getFlag("GRPC_EXPERIMENTAL_PF_WEIGHTED_SHUFFLING", true);
private final Helper helper;
Expand All @@ -75,20 +75,11 @@ final class PickFirstLeafLoadBalancer extends LoadBalancer {
private ConnectivityState rawConnectivityState = IDLE;
private ConnectivityState concludedState = IDLE;
private boolean notAPetiolePolicy = true; // means not under a petiole policy
private final BackoffPolicy.Provider bkoffPolProvider = new ExponentialBackoffPolicy.Provider();
private BackoffPolicy reconnectPolicy;
@Nullable
private ScheduledHandle reconnectTask = null;
private final boolean serializingRetries = isSerializingRetries();

PickFirstLeafLoadBalancer(Helper helper) {
this.helper = checkNotNull(helper, "helper");
}

static boolean isSerializingRetries() {
return GrpcUtil.getFlag("GRPC_SERIALIZE_RETRIES", false);
}

@Override
public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
if (rawConnectivityState == SHUTDOWN) {
Expand Down Expand Up @@ -366,15 +357,11 @@ void processSubchannelState(SubchannelData subchannelData, ConnectivityStateInfo
if (addressIndex.increment()) {
cancelScheduleTask();
requestConnection(); // is recursive so might hit the end of the addresses
} else {
if (subchannels.size() >= addressIndex.size()) {
scheduleBackoff();
} else {
// We must have done a seek to the middle of the list lets start over from the
// beginning
addressIndex.reset();
requestConnection();
}
} else if (subchannels.size() < addressIndex.size()) {
// We must have done a seek to the middle of the list lets start over from the
// beginning
addressIndex.reset();
requestConnection();
}
}

Expand Down Expand Up @@ -402,39 +389,6 @@ void processSubchannelState(SubchannelData subchannelData, ConnectivityStateInfo
}
}

/**
* Only called after all addresses attempted and failed (TRANSIENT_FAILURE).
*/
private void scheduleBackoff() {
if (!serializingRetries) {
return;
}

class EndOfCurrentBackoff implements Runnable {
@Override
public void run() {
reconnectTask = null;
addressIndex.reset();
requestConnection();
}
}

// Just allow the previous one to trigger when ready if we're already in backoff
if (reconnectTask != null) {
return;
}

if (reconnectPolicy == null) {
reconnectPolicy = bkoffPolProvider.get();
}
long delayNanos = reconnectPolicy.nextBackoffNanos();
reconnectTask = helper.getSynchronizationContext().schedule(
new EndOfCurrentBackoff(),
delayNanos,
TimeUnit.NANOSECONDS,
helper.getScheduledExecutorService());
}

private void updateHealthCheckedState(SubchannelData subchannelData) {
if (subchannelData.state != READY) {
return;
Expand Down Expand Up @@ -469,11 +423,6 @@ public void shutdown() {
rawConnectivityState = SHUTDOWN;
concludedState = SHUTDOWN;
cancelScheduleTask();
if (reconnectTask != null) {
reconnectTask.cancel();
reconnectTask = null;
}
reconnectPolicy = null;

for (SubchannelData subchannelData : subchannels.values()) {
subchannelData.getSubchannel().shutdown();
Expand All @@ -487,12 +436,6 @@ public void shutdown() {
* that all other subchannels must be shutdown.
*/
private void shutdownRemaining(SubchannelData activeSubchannelData) {
if (reconnectTask != null) {
reconnectTask.cancel();
reconnectTask = null;
}
reconnectPolicy = null;

cancelScheduleTask();
for (SubchannelData subchannelData : subchannels.values()) {
if (!subchannelData.getSubchannel().equals(activeSubchannelData.subchannel)) {
Expand All @@ -513,7 +456,7 @@ private void shutdownRemaining(SubchannelData activeSubchannelData) {
*/
@Override
public void requestConnection() {
if (!addressIndex.isValid() || rawConnectivityState == SHUTDOWN || reconnectTask != null) {
if (!addressIndex.isValid() || rawConnectivityState == SHUTDOWN) {
return;
}

Expand All @@ -537,20 +480,8 @@ public void requestConnection() {
scheduleNextConnection();
break;
case TRANSIENT_FAILURE:
if (!serializingRetries) {
addressIndex.increment();
requestConnection();
} else {
if (!addressIndex.isValid()) {
scheduleBackoff();
} else {
subchannelData.subchannel.requestConnection();
subchannelData.updateState(CONNECTING);
if (rawConnectivityState == IDLE) {
rawConnectivityState = CONNECTING;
}
}
}
addressIndex.increment();
requestConnection();
break;
default:
// Wait for current subchannel to change state
Expand Down Expand Up @@ -599,7 +530,6 @@ private SubchannelData createNewSubchannel(SocketAddress addr, Attributes attrs)
.setAddresses(Lists.newArrayList(
new EquivalentAddressGroup(addr, attrs)))
.addOption(HEALTH_CONSUMER_LISTENER_ARG_KEY, hcListener)
.addOption(LoadBalancer.DISABLE_SUBCHANNEL_RECONNECT_KEY, serializingRetries)
.build());
if (subchannel == null) {
log.warning("Was not able to create subchannel for " + addr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import static io.grpc.LoadBalancer.HEALTH_CONSUMER_LISTENER_ARG_KEY;
import static io.grpc.LoadBalancer.IS_PETIOLE_POLICY;
import static io.grpc.internal.PickFirstLeafLoadBalancer.CONNECTION_DELAY_INTERVAL_MS;
import static io.grpc.internal.PickFirstLeafLoadBalancer.isSerializingRetries;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
Expand Down Expand Up @@ -99,20 +98,15 @@
public class PickFirstLeafLoadBalancerTest {
public static final Status CONNECTION_ERROR =
Status.UNAVAILABLE.withDescription("Simulated connection error");
public static final String GRPC_SERIALIZE_RETRIES = "GRPC_SERIALIZE_RETRIES";

@Parameterized.Parameters(name = "{0}-{1}")
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> data() {
return Arrays.asList(new Object[][] {
{false, false},
{false, true},
{true, false}});
{false},
{true}});
}

@Parameterized.Parameter(value = 0)
public boolean serializeRetries;

@Parameterized.Parameter(value = 1)
public boolean enableHappyEyeballs;

private PickFirstLeafLoadBalancer loadBalancer;
Expand Down Expand Up @@ -152,19 +146,10 @@ public void uncaughtException(Thread t, Throwable e) {
private PickSubchannelArgs mockArgs;

private String originalHappyEyeballsEnabledValue;
private String originalSerializeRetriesValue;
private boolean originalWeightedShuffling;

private long backoffMillis;

@Before
public void setUp() {
assumeTrue(!serializeRetries || !enableHappyEyeballs); // they are not compatible

backoffMillis = TimeUnit.SECONDS.toMillis(1);
originalSerializeRetriesValue = System.getProperty(GRPC_SERIALIZE_RETRIES);
System.setProperty(GRPC_SERIALIZE_RETRIES, Boolean.toString(serializeRetries));

originalHappyEyeballsEnabledValue =
System.getProperty(PickFirstLoadBalancerProvider.GRPC_PF_USE_HAPPY_EYEBALLS);
System.setProperty(PickFirstLoadBalancerProvider.GRPC_PF_USE_HAPPY_EYEBALLS,
Expand Down Expand Up @@ -203,11 +188,6 @@ public void setUp() {

@After
public void tearDown() {
if (originalSerializeRetriesValue == null) {
System.clearProperty(GRPC_SERIALIZE_RETRIES);
} else {
System.setProperty(GRPC_SERIALIZE_RETRIES, originalSerializeRetriesValue);
}
if (originalHappyEyeballsEnabledValue == null) {
System.clearProperty(PickFirstLoadBalancerProvider.GRPC_PF_USE_HAPPY_EYEBALLS);
} else {
Expand Down Expand Up @@ -598,11 +578,7 @@ public void pickAfterTransientFailureIdleAndResolvedAddressesChanged() {
// Simulate the IDLE picker getting used upon an incoming RPC, triggering requestConnection()
// starting at the first subchannel (which is in TF)
assertEquals(Status.OK, pickerCaptor.getValue().pickSubchannel(mockArgs).getStatus());
if (serializeRetries) {
inOrder.verify(mockSubchannel1).requestConnection();
} else {
inOrder.verify(mockSubchannel2).requestConnection();
}
inOrder.verify(mockSubchannel2).requestConnection();
assertEquals(CONNECTING, loadBalancer.getRawConnectivityState());

// Re-resolution result arrives before subchannel reports CONNECTING
Expand Down Expand Up @@ -733,8 +709,6 @@ public void healthCheckFlow() {
// reproduces #12796
@Test
public void healthCheckWithTF_AllowsStateInconsistency() {
assumeTrue(!serializeRetries);

when(mockSubchannel1.getAttributes()).thenReturn(
Attributes.newBuilder().set(HAS_HEALTH_PRODUCER_LISTENER_KEY, true).build());

Expand Down Expand Up @@ -1670,11 +1644,6 @@ public void updateAddresses_disjoint_transient_failure() {
loadBalancer.acceptResolvedAddresses(
ResolvedAddresses.newBuilder().setAddresses(newServers).setAttributes(affinity).build());

if (serializeRetries) {
inOrder.verify(mockSubchannel3, never()).start(stateListenerCaptor.capture());
forwardTimeByBackoffDelay();
}

// subchannel 3 still attempts a connection even though we stay in transient failure
assertEquals(TRANSIENT_FAILURE, loadBalancer.getConcludedConnectivityState());
inOrder.verify(mockSubchannel3).start(stateListenerCaptor.capture());
Expand Down Expand Up @@ -1891,8 +1860,6 @@ public void updateAddresses_intersecting_ready() {

@Test
public void updateAddresses_intersecting_transient_failure() {
assumeTrue(!isSerializingRetries());

// Starting first connection attempt
InOrder inOrder = inOrder(mockHelper, mockSubchannel1, mockSubchannel2,
mockSubchannel3, mockSubchannel4); // captor: captures
Expand Down Expand Up @@ -2157,8 +2124,6 @@ public void updateAddresses_identical_ready() {

@Test
public void updateAddresses_identical_transient_failure() {
assumeTrue(!isSerializingRetries());

InOrder inOrder = inOrder(mockHelper, mockSubchannel1, mockSubchannel2,
mockSubchannel3, mockSubchannel4);
// Creating first set of endpoints/addresses
Expand Down Expand Up @@ -2968,44 +2933,6 @@ public void advance_index_then_request_connection() {
loadBalancer.requestConnection(); // should be handled without throwing exception
}

@Test
public void serialized_retries_two_passes() {
assumeTrue(serializeRetries); // This test is only for serialized retries

InOrder inOrder = inOrder(mockHelper, mockSubchannel1, mockSubchannel2, mockSubchannel3);
Status error = Status.UNAUTHENTICATED.withDescription("simulated failure");

List<EquivalentAddressGroup> addrs =
Lists.newArrayList(servers.get(0), servers.get(1), servers.get(2));
Subchannel[] subchannels = new Subchannel[]{mockSubchannel1, mockSubchannel2, mockSubchannel3};
SubchannelStateListener[] listeners = new SubchannelStateListener[subchannels.length];
loadBalancer.acceptResolvedAddresses(
ResolvedAddresses.newBuilder().setAddresses(addrs).build());
forwardTimeByConnectionDelay(2);
for (int i = 0; i < subchannels.length; i++) {
inOrder.verify(subchannels[i]).start(stateListenerCaptor.capture());
inOrder.verify(subchannels[i]).requestConnection();
listeners[i] = stateListenerCaptor.getValue();
listeners[i].onSubchannelState(ConnectivityStateInfo.forTransientFailure(error));
}
assertEquals(TRANSIENT_FAILURE, loadBalancer.getConcludedConnectivityState());
assertFalse("Index should be at end", loadBalancer.isIndexValid());

forwardTimeByBackoffDelay(); // should trigger retry
for (int i = 0; i < subchannels.length; i++) {
inOrder.verify(subchannels[i]).requestConnection();
listeners[i].onSubchannelState(ConnectivityStateInfo.forTransientFailure(error)); // cascade
}
inOrder.verify(subchannels[0], never()).requestConnection(); // should wait for backoff delay

forwardTimeByBackoffDelay(); // should trigger retry again
for (int i = 0; i < subchannels.length; i++) {
inOrder.verify(subchannels[i]).requestConnection();
assertEquals(i, loadBalancer.getIndexLocation());
listeners[i].onSubchannelState(ConnectivityStateInfo.forTransientFailure(error)); // cascade
}
}

@Test
public void index_looping() {
Attributes.Key<String> key = Attributes.Key.create("some-key");
Expand Down Expand Up @@ -3222,11 +3149,6 @@ private void forwardTimeByConnectionDelay(int times) {
}
}

private void forwardTimeByBackoffDelay() {
backoffMillis = (long) (backoffMillis * 1.8); // backoff factor default is 1.6 with Jitter .2
fakeClock.forwardTime(backoffMillis, TimeUnit.MILLISECONDS);
}

private void acceptXSubchannels(int num) {
List<EquivalentAddressGroup> newServers = new ArrayList<>();
for (int i = 0; i < num; i++) {
Expand Down
Loading