• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #19212

08 May 2024 11:06PM UTC coverage: 88.335% (+0.03%) from 88.309%
#19212

push

github

web-flow
Change HappyEyeballs and new pick first LB flags default value to false (#11120) (#11177)

* Change HappyEyeballs flag default value to false since some G3 users are seeing problems.
Put the flag logic in a common place for PickFirstLeafLoadBalancer & WRR's test.

* Set expected requestConnection count based on whether happy eyeballs is enabled or not

* Disable new PickFirstLB

* Fix test expectations to handle both new and old PF LB paths.

31526 of 35689 relevant lines covered (88.34%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.79
/../core/src/main/java/io/grpc/internal/PickFirstLeafLoadBalancer.java
1
/*
2
 * Copyright 2023 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.internal;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20
import static io.grpc.ConnectivityState.CONNECTING;
21
import static io.grpc.ConnectivityState.IDLE;
22
import static io.grpc.ConnectivityState.READY;
23
import static io.grpc.ConnectivityState.SHUTDOWN;
24
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
25

26
import com.google.common.annotations.VisibleForTesting;
27
import com.google.common.base.MoreObjects;
28
import com.google.common.collect.ImmutableList;
29
import com.google.common.collect.Lists;
30
import io.grpc.Attributes;
31
import io.grpc.ConnectivityState;
32
import io.grpc.ConnectivityStateInfo;
33
import io.grpc.EquivalentAddressGroup;
34
import io.grpc.LoadBalancer;
35
import io.grpc.Status;
36
import io.grpc.SynchronizationContext;
37
import io.grpc.SynchronizationContext.ScheduledHandle;
38
import java.net.SocketAddress;
39
import java.util.ArrayList;
40
import java.util.Collections;
41
import java.util.HashMap;
42
import java.util.HashSet;
43
import java.util.List;
44
import java.util.Map;
45
import java.util.Random;
46
import java.util.Set;
47
import java.util.concurrent.TimeUnit;
48
import java.util.concurrent.atomic.AtomicBoolean;
49
import java.util.logging.Level;
50
import java.util.logging.Logger;
51
import javax.annotation.Nullable;
52

53
/**
54
 * A {@link LoadBalancer} that provides no load-balancing over the addresses from the {@link
55
 * io.grpc.NameResolver}. The channel's default behavior is used, which is walking down the address
56
 * list and sticking to the first that works.
57
 */
58
final class PickFirstLeafLoadBalancer extends LoadBalancer {
59
  private static final Logger log = Logger.getLogger(PickFirstLeafLoadBalancer.class.getName());
1✔
60
  @VisibleForTesting
61
  static final int CONNECTION_DELAY_INTERVAL_MS = 250;
62
  private final Helper helper;
63
  private final Map<SocketAddress, SubchannelData> subchannels = new HashMap<>();
1✔
64
  private Index addressIndex;
65
  private int numTf = 0;
1✔
66
  private boolean firstPass = true;
1✔
67
  @Nullable
68
  private ScheduledHandle scheduleConnectionTask;
69
  private ConnectivityState rawConnectivityState = IDLE;
1✔
70
  private ConnectivityState concludedState = IDLE;
1✔
71
  private final boolean enableHappyEyeballs =
1✔
72
      PickFirstLoadBalancerProvider.isEnabledHappyEyeballs();
1✔
73

74
  PickFirstLeafLoadBalancer(Helper helper) {
1✔
75
    this.helper = checkNotNull(helper, "helper");
1✔
76
  }
1✔
77

78
  @Override
79
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
80
    if (rawConnectivityState == SHUTDOWN) {
1✔
81
      return Status.FAILED_PRECONDITION.withDescription("Already shut down");
1✔
82
    }
83

84
    List<EquivalentAddressGroup> servers = resolvedAddresses.getAddresses();
1✔
85

86
    // Validate the address list
87
    if (servers.isEmpty()) {
1✔
88
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
1✔
89
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
1✔
90
                      + ", attrs=" + resolvedAddresses.getAttributes());
1✔
91
      handleNameResolutionError(unavailableStatus);
1✔
92
      return unavailableStatus;
1✔
93
    }
94
    for (EquivalentAddressGroup eag : servers) {
1✔
95
      if (eag == null) {
1✔
96
        Status unavailableStatus = Status.UNAVAILABLE.withDescription(
1✔
97
            "NameResolver returned address list with null endpoint. addrs="
98
                + resolvedAddresses.getAddresses() + ", attrs="
1✔
99
                + resolvedAddresses.getAttributes());
1✔
100
        handleNameResolutionError(unavailableStatus);
1✔
101
        return unavailableStatus;
1✔
102
      }
103
    }
1✔
104

105
    // Since we have a new set of addresses, we are again at first pass
106
    firstPass = true;
1✔
107

108
    // We can optionally be configured to shuffle the address list. This can help better distribute
109
    // the load.
110
    if (resolvedAddresses.getLoadBalancingPolicyConfig()
1✔
111
        instanceof PickFirstLeafLoadBalancerConfig) {
112
      PickFirstLeafLoadBalancerConfig config
1✔
113
          = (PickFirstLeafLoadBalancerConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
114
      if (config.shuffleAddressList != null && config.shuffleAddressList) {
1✔
115
        servers = new ArrayList<>(servers);
1✔
116
        Collections.shuffle(servers,
1✔
117
            config.randomSeed != null ? new Random(config.randomSeed) : new Random());
1✔
118
      }
119
    }
120

121
    // Make sure we're storing our own list rather than what was passed in
122
    final ImmutableList<EquivalentAddressGroup> newImmutableAddressGroups =
123
        ImmutableList.<EquivalentAddressGroup>builder().addAll(servers).build();
1✔
124

125
    if (addressIndex == null) {
1✔
126
      addressIndex = new Index(newImmutableAddressGroups);
1✔
127
    } else if (rawConnectivityState == READY) {
1✔
128
      // If the previous ready subchannel exists in new address list,
129
      // keep this connection and don't create new subchannels
130
      SocketAddress previousAddress = addressIndex.getCurrentAddress();
1✔
131
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
132
      if (addressIndex.seekTo(previousAddress)) {
1✔
133
        SubchannelData subchannelData = subchannels.get(previousAddress);
1✔
134
        subchannelData.getSubchannel().updateAddresses(addressIndex.getCurrentEagAsList());
1✔
135
        return Status.OK;
1✔
136
      } else {
137
        addressIndex.reset(); // Previous ready subchannel not in the new list of addresses
1✔
138
      }
139
    } else {
1✔
140
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
141
    }
142

143
    // remove old subchannels that were not in new address list
144
    Set<SocketAddress> oldAddrs = new HashSet<>(subchannels.keySet());
1✔
145

146
    // Flatten the new EAGs addresses
147
    Set<SocketAddress> newAddrs = new HashSet<>();
1✔
148
    for (EquivalentAddressGroup endpoint : newImmutableAddressGroups) {
1✔
149
      newAddrs.addAll(endpoint.getAddresses());
1✔
150
    }
1✔
151

152
    // Shut them down and remove them
153
    for (SocketAddress oldAddr : oldAddrs) {
1✔
154
      if (!newAddrs.contains(oldAddr)) {
1✔
155
        subchannels.remove(oldAddr).getSubchannel().shutdown();
1✔
156
      }
157
    }
1✔
158

159
    if (oldAddrs.size() == 0 || rawConnectivityState == CONNECTING
1✔
160
        || rawConnectivityState == READY) {
161
      // start connection attempt at first address
162
      rawConnectivityState = CONNECTING;
1✔
163
      updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
164
      cancelScheduleTask();
1✔
165
      requestConnection();
1✔
166

167
    } else if (rawConnectivityState == IDLE) {
1✔
168
      // start connection attempt at first address when requested
169
      SubchannelPicker picker = new RequestConnectionPicker(this);
1✔
170
      updateBalancingState(IDLE, picker);
1✔
171

172
    } else if (rawConnectivityState == TRANSIENT_FAILURE) {
1✔
173
      // start connection attempt at first address
174
      cancelScheduleTask();
1✔
175
      requestConnection();
1✔
176
    }
177

178
    return Status.OK;
1✔
179
  }
180

181
  @Override
182
  public void handleNameResolutionError(Status error) {
183
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
184
      subchannelData.getSubchannel().shutdown();
1✔
185
    }
1✔
186
    subchannels.clear();
1✔
187
    updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(error)));
1✔
188
  }
1✔
189

190
  void processSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
191
    ConnectivityState newState = stateInfo.getState();
1✔
192
    // Shutdown channels/previously relevant subchannels can still callback with state updates.
193
    // To prevent pickers from returning these obsolete subchannels, this logic
194
    // is included to check if the current list of active subchannels includes this subchannel.
195
    SubchannelData subchannelData = subchannels.get(getAddress(subchannel));
1✔
196
    if (subchannelData == null || subchannelData.getSubchannel() != subchannel) {
1✔
197
      return;
1✔
198
    }
199
    if (newState == SHUTDOWN) {
1✔
200
      return;
×
201
    }
202

203
    if (newState == IDLE) {
1✔
204
      helper.refreshNameResolution();
1✔
205
    }
206
    // If we are transitioning from a TRANSIENT_FAILURE to CONNECTING or IDLE we ignore this state
207
    // transition and still keep the LB in TRANSIENT_FAILURE state. This is referred to as "sticky
208
    // transient failure". Only a subchannel state change to READY will get the LB out of
209
    // TRANSIENT_FAILURE. If the state is IDLE we additionally request a new connection so that we
210
    // keep retrying for a connection.
211

212
    // With the new pick first implementation, individual subchannels will have their own backoff
213
    // on a per-address basis. Thus, iterative requests for connections will not be requested
214
    // once the first pass through is complete.
215
    // However, every time there is an address update, we will perform a pass through for the new
216
    // addresses in the updated list.
217
    subchannelData.updateState(newState);
1✔
218
    if (rawConnectivityState == TRANSIENT_FAILURE || concludedState == TRANSIENT_FAILURE)  {
1✔
219
      if (newState == CONNECTING) {
1✔
220
        // each subchannel is responsible for its own backoff
221
        return;
1✔
222
      } else if (newState == IDLE) {
1✔
223
        requestConnection();
1✔
224
        return;
1✔
225
      }
226
    }
227

228
    switch (newState) {
1✔
229
      case IDLE:
230
        // Shutdown when ready: connect from beginning when prompted
231
        addressIndex.reset();
1✔
232
        rawConnectivityState = IDLE;
1✔
233
        updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
234
        break;
1✔
235

236
      case CONNECTING:
237
        rawConnectivityState = CONNECTING;
1✔
238
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
239
        break;
1✔
240

241
      case READY:
242
        shutdownRemaining(subchannelData);
1✔
243
        addressIndex.seekTo(getAddress(subchannel));
1✔
244
        rawConnectivityState = READY;
1✔
245
        updateHealthCheckedState(subchannelData);
1✔
246
        break;
1✔
247

248
      case TRANSIENT_FAILURE:
249
        // If we are looking at current channel, request a connection if possible
250
        if (addressIndex.isValid()
1✔
251
            && subchannels.get(addressIndex.getCurrentAddress()).getSubchannel() == subchannel) {
1✔
252
          if (addressIndex.increment()) {
1✔
253
            cancelScheduleTask();
1✔
254
            requestConnection(); // is recursive so might hit the end of the addresses
1✔
255
          }
256
        }
257

258
        if (isPassComplete()) {
1✔
259
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
260
          updateBalancingState(TRANSIENT_FAILURE,
1✔
261
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
262

263
          // Refresh Name Resolution, but only when all 3 conditions are met
264
          // * We are at the end of addressIndex
265
          // * have had status reported for all subchannels.
266
          // * And one of the following conditions:
267
          //    * Have had enough TF reported since we completed first pass
268
          //    * Just completed the first pass
269
          if (++numTf >= addressIndex.size() || firstPass) {
1✔
270
            firstPass = false;
1✔
271
            numTf = 0;
1✔
272
            helper.refreshNameResolution();
1✔
273
          }
274
        }
275
        break;
276

277
      default:
278
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
279
    }
280
  }
1✔
281

282
  private void updateHealthCheckedState(SubchannelData subchannelData) {
283
    if (subchannelData.state != READY) {
1✔
284
      return;
1✔
285
    }
286
    if (subchannelData.getHealthState() == READY) {
1✔
287
      updateBalancingState(READY,
1✔
288
          new FixedResultPicker(PickResult.withSubchannel(subchannelData.subchannel)));
1✔
289
    } else if (subchannelData.getHealthState() == TRANSIENT_FAILURE) {
1✔
290
      updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(
1✔
291
          subchannelData.healthListener.healthStateInfo.getStatus())));
1✔
292
    } else if (concludedState != TRANSIENT_FAILURE) {
1✔
293
      updateBalancingState(subchannelData.getHealthState(),
1✔
294
          new Picker(PickResult.withNoResult()));
1✔
295
    }
296
  }
1✔
297

298
  private void updateBalancingState(ConnectivityState state, SubchannelPicker picker) {
299
    // an optimization: de-dup IDLE or CONNECTING notification.
300
    if (state == concludedState && (state == IDLE || state == CONNECTING)) {
1✔
301
      return;
1✔
302
    }
303
    concludedState = state;
1✔
304
    helper.updateBalancingState(state, picker);
1✔
305
  }
1✔
306

307
  @Override
308
  public void shutdown() {
309
    log.log(Level.FINE,
1✔
310
        "Shutting down, currently have {} subchannels created", subchannels.size());
1✔
311
    rawConnectivityState = SHUTDOWN;
1✔
312
    concludedState = SHUTDOWN;
1✔
313
    cancelScheduleTask();
1✔
314

315
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
316
      subchannelData.getSubchannel().shutdown();
1✔
317
    }
1✔
318

319
    subchannels.clear();
1✔
320
  }
1✔
321

322
  /**
323
  * Shuts down remaining subchannels. Called when a subchannel becomes ready, which means
324
  * that all other subchannels must be shutdown.
325
  */
326
  private void shutdownRemaining(SubchannelData activeSubchannelData) {
327
    cancelScheduleTask();
1✔
328
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
329
      if (!subchannelData.getSubchannel().equals(activeSubchannelData.subchannel)) {
1✔
330
        subchannelData.getSubchannel().shutdown();
1✔
331
      }
332
    }
1✔
333
    subchannels.clear();
1✔
334
    activeSubchannelData.updateState(READY);
1✔
335
    subchannels.put(getAddress(activeSubchannelData.subchannel), activeSubchannelData);
1✔
336
  }
1✔
337

338
  /**
339
   * Requests a connection to the next applicable address' subchannel, creating one if necessary.
340
   * Schedules a connection to next address in list as well.
341
   * If the current channel has already attempted a connection, we attempt a connection
342
   * to the next address/subchannel in our list.  We assume that createNewSubchannel will never
343
   * return null.
344
   */
345
  @Override
346
  public void requestConnection() {
347
    if (addressIndex == null || !addressIndex.isValid() || rawConnectivityState == SHUTDOWN ) {
1✔
348
      return;
1✔
349
    }
350

351
    Subchannel subchannel;
352
    SocketAddress currentAddress;
353
    currentAddress = addressIndex.getCurrentAddress();
1✔
354
    subchannel = subchannels.containsKey(currentAddress)
1✔
355
        ? subchannels.get(currentAddress).getSubchannel()
1✔
356
        : createNewSubchannel(currentAddress, addressIndex.getCurrentEagAttributes());
1✔
357

358
    ConnectivityState subchannelState = subchannels.get(currentAddress).getState();
1✔
359
    switch (subchannelState) {
1✔
360
      case IDLE:
361
        subchannel.requestConnection();
1✔
362
        subchannels.get(currentAddress).updateState(CONNECTING);
1✔
363
        scheduleNextConnection();
1✔
364
        break;
1✔
365
      case CONNECTING:
366
        if (enableHappyEyeballs) {
1✔
367
          scheduleNextConnection();
1✔
368
        } else {
369
          subchannel.requestConnection();
1✔
370
        }
371
        break;
1✔
372
      case TRANSIENT_FAILURE:
373
        addressIndex.increment();
1✔
374
        requestConnection();
1✔
375
        break;
1✔
376
      case READY: // Shouldn't ever happen
377
        log.warning("Requesting a connection even though we have a READY subchannel");
×
378
        break;
×
379
      case SHUTDOWN:
380
      default:
381
        // Makes checkstyle happy
382
    }
383
  }
1✔
384

385

386
  /**
387
  * Happy Eyeballs
388
  * Schedules connection attempt to happen after a delay to the next available address.
389
  */
390
  private void scheduleNextConnection() {
391
    if (!enableHappyEyeballs
1✔
392
        || (scheduleConnectionTask != null && scheduleConnectionTask.isPending())) {
1✔
393
      return;
1✔
394
    }
395

396
    class StartNextConnection implements Runnable {
1✔
397
      @Override
398
      public void run() {
399
        scheduleConnectionTask = null;
1✔
400
        if (addressIndex.increment()) {
1✔
401
          requestConnection();
1✔
402
        }
403
      }
1✔
404
    }
405

406
    SynchronizationContext synchronizationContext = null;
1✔
407
    try {
408
      synchronizationContext = helper.getSynchronizationContext();
1✔
409
    } catch (NullPointerException e) {
×
410
      // All helpers should have a sync context, but if one doesn't (ex. user had a custom test)
411
      // we don't want to break previously working functionality.
412
      return;
×
413
    }
1✔
414

415
    scheduleConnectionTask = synchronizationContext.schedule(
1✔
416
        new StartNextConnection(),
417
        CONNECTION_DELAY_INTERVAL_MS,
418
        TimeUnit.MILLISECONDS,
419
        helper.getScheduledExecutorService());
1✔
420
  }
1✔
421

422
  private void cancelScheduleTask() {
423
    if (scheduleConnectionTask != null) {
1✔
424
      scheduleConnectionTask.cancel();
1✔
425
      scheduleConnectionTask = null;
1✔
426
    }
427
  }
1✔
428

429
  private Subchannel createNewSubchannel(SocketAddress addr, Attributes attrs) {
430
    HealthListener hcListener = new HealthListener();
1✔
431
    final Subchannel subchannel = helper.createSubchannel(
1✔
432
        CreateSubchannelArgs.newBuilder()
1✔
433
        .setAddresses(Lists.newArrayList(
1✔
434
            new EquivalentAddressGroup(addr, attrs)))
435
        .addOption(HEALTH_CONSUMER_LISTENER_ARG_KEY, hcListener)
1✔
436
            .build());
1✔
437
    if (subchannel == null) {
1✔
438
      log.warning("Was not able to create subchannel for " + addr);
×
439
      throw new IllegalStateException("Can't create subchannel");
×
440
    }
441
    SubchannelData subchannelData = new SubchannelData(subchannel, IDLE, hcListener);
1✔
442
    hcListener.subchannelData = subchannelData;
1✔
443
    subchannels.put(addr, subchannelData);
1✔
444
    Attributes scAttrs = subchannel.getAttributes();
1✔
445
    if (scAttrs.get(LoadBalancer.HAS_HEALTH_PRODUCER_LISTENER_KEY) == null) {
1✔
446
      hcListener.healthStateInfo = ConnectivityStateInfo.forNonError(READY);
1✔
447
    }
448
    subchannel.start(stateInfo -> processSubchannelState(subchannel, stateInfo));
1✔
449
    return subchannel;
1✔
450
  }
451

452
  private boolean isPassComplete() {
453
    if (addressIndex == null || addressIndex.isValid()
1✔
454
        || subchannels.size() < addressIndex.size()) {
1✔
455
      return false;
1✔
456
    }
457
    for (SubchannelData sc : subchannels.values()) {
1✔
458
      if (!sc.isCompletedConnectivityAttempt() ) {
1✔
459
        return false;
1✔
460
      }
461
    }
1✔
462
    return true;
1✔
463
  }
464

465
  private final class HealthListener implements SubchannelStateListener {
1✔
466
    private ConnectivityStateInfo healthStateInfo = ConnectivityStateInfo.forNonError(IDLE);
1✔
467
    private SubchannelData subchannelData;
468

469
    @Override
470
    public void onSubchannelState(ConnectivityStateInfo newState) {
471
      log.log(Level.FINE, "Received health status {0} for subchannel {1}",
1✔
472
          new Object[]{newState, subchannelData.subchannel});
1✔
473
      healthStateInfo = newState;
1✔
474
      try {
475
        SubchannelData curSubChanData = subchannels.get(addressIndex.getCurrentAddress());
1✔
476
        if (curSubChanData != null && curSubChanData.healthListener == this) {
1✔
477
          updateHealthCheckedState(subchannelData);
1✔
478
        }
479
      } catch (IllegalStateException e) {
×
480
        log.fine("Health listener received state change after subchannel was removed");
×
481
      }
1✔
482
    }
1✔
483
  }
484

485
  private SocketAddress getAddress(Subchannel subchannel) {
486
    return subchannel.getAddresses().getAddresses().get(0);
1✔
487
  }
488

489
  @VisibleForTesting
490
  ConnectivityState getConcludedConnectivityState() {
491
    return this.concludedState;
1✔
492
  }
493

494
  /**
495
   * No-op picker which doesn't add any custom picking logic. It just passes already known result
496
   * received in constructor.
497
   */
498
  private static final class Picker extends SubchannelPicker {
499
    private final PickResult result;
500

501
    Picker(PickResult result) {
1✔
502
      this.result = checkNotNull(result, "result");
1✔
503
    }
1✔
504

505
    @Override
506
    public PickResult pickSubchannel(PickSubchannelArgs args) {
507
      return result;
1✔
508
    }
509

510
    @Override
511
    public String toString() {
512
      return MoreObjects.toStringHelper(Picker.class).add("result", result).toString();
×
513
    }
514
  }
515

516
  /**
517
   * Picker that requests connection during the first pick, and returns noResult.
518
   */
519
  private final class RequestConnectionPicker extends SubchannelPicker {
520
    private final PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer;
521
    private final AtomicBoolean connectionRequested = new AtomicBoolean(false);
1✔
522

523
    RequestConnectionPicker(PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer) {
1✔
524
      this.pickFirstLeafLoadBalancer =
1✔
525
          checkNotNull(pickFirstLeafLoadBalancer, "pickFirstLeafLoadBalancer");
1✔
526
    }
1✔
527

528
    @Override
529
    public PickResult pickSubchannel(PickSubchannelArgs args) {
530
      if (connectionRequested.compareAndSet(false, true)) {
1✔
531
        helper.getSynchronizationContext().execute(pickFirstLeafLoadBalancer::requestConnection);
1✔
532
      }
533
      return PickResult.withNoResult();
1✔
534
    }
535
  }
536

537
  /**
538
   * Index as in 'i', the pointer to an entry. Not a "search index."
539
   * All updates should be done in a synchronization context.
540
   */
541
  @VisibleForTesting
542
  static final class Index {
543
    private List<EquivalentAddressGroup> addressGroups;
544
    private int groupIndex;
545
    private int addressIndex;
546

547
    public Index(List<EquivalentAddressGroup> groups) {
1✔
548
      this.addressGroups = groups != null ? groups : Collections.emptyList();
1✔
549
    }
1✔
550

551
    public boolean isValid() {
552
      // Is invalid if empty or has incremented off the end
553
      return groupIndex < addressGroups.size();
1✔
554
    }
555

556
    public boolean isAtBeginning() {
557
      return groupIndex == 0 && addressIndex == 0;
1✔
558
    }
559

560
    /**
561
     * Move to next address in group.  If last address in group move to first address of next group.
562
     * @return false if went off end of the list, otherwise true
563
     */
564
    public boolean increment() {
565
      if (!isValid()) {
1✔
566
        return false;
1✔
567
      }
568

569
      EquivalentAddressGroup group = addressGroups.get(groupIndex);
1✔
570
      addressIndex++;
1✔
571
      if (addressIndex >= group.getAddresses().size()) {
1✔
572
        groupIndex++;
1✔
573
        addressIndex = 0;
1✔
574
        return groupIndex < addressGroups.size();
1✔
575
      }
576

577
      return true;
1✔
578
    }
579

580
    public void reset() {
581
      groupIndex = 0;
1✔
582
      addressIndex = 0;
1✔
583
    }
1✔
584

585
    public SocketAddress getCurrentAddress() {
586
      if (!isValid()) {
1✔
587
        throw new IllegalStateException("Index is past the end of the address group list");
×
588
      }
589
      return addressGroups.get(groupIndex).getAddresses().get(addressIndex);
1✔
590
    }
591

592
    public Attributes getCurrentEagAttributes() {
593
      if (!isValid()) {
1✔
594
        throw new IllegalStateException("Index is off the end of the address group list");
×
595
      }
596
      return addressGroups.get(groupIndex).getAttributes();
1✔
597
    }
598

599
    public List<EquivalentAddressGroup> getCurrentEagAsList() {
600
      return Collections.singletonList(
1✔
601
          new EquivalentAddressGroup(getCurrentAddress(), getCurrentEagAttributes()));
1✔
602
    }
603

604
    /**
605
     * Update to new groups, resetting the current index.
606
     */
607
    public void updateGroups(ImmutableList<EquivalentAddressGroup> newGroups) {
608
      addressGroups = newGroups != null ? newGroups : Collections.emptyList();
1✔
609
      reset();
1✔
610
    }
1✔
611

612
    /**
613
     * Returns false if the needle was not found and the current index was left unchanged.
614
     */
615
    public boolean seekTo(SocketAddress needle) {
616
      for (int i = 0; i < addressGroups.size(); i++) {
1✔
617
        EquivalentAddressGroup group = addressGroups.get(i);
1✔
618
        int j = group.getAddresses().indexOf(needle);
1✔
619
        if (j == -1) {
1✔
620
          continue;
1✔
621
        }
622
        this.groupIndex = i;
1✔
623
        this.addressIndex = j;
1✔
624
        return true;
1✔
625
      }
626
      return false;
1✔
627
    }
628

629
    public int size() {
630
      return (addressGroups != null) ? addressGroups.size() : 0;
1✔
631
    }
632
  }
633

634
  private static final class SubchannelData {
635
    private final Subchannel subchannel;
636
    private ConnectivityState state;
637
    private final HealthListener healthListener;
638
    private boolean completedConnectivityAttempt = false;
1✔
639

640
    public SubchannelData(Subchannel subchannel, ConnectivityState state,
641
                          HealthListener subchannelHealthListener) {
1✔
642
      this.subchannel = subchannel;
1✔
643
      this.state = state;
1✔
644
      this.healthListener = subchannelHealthListener;
1✔
645
    }
1✔
646

647
    public Subchannel getSubchannel() {
648
      return this.subchannel;
1✔
649
    }
650

651
    public ConnectivityState getState() {
652
      return this.state;
1✔
653
    }
654

655
    public boolean isCompletedConnectivityAttempt() {
656
      return completedConnectivityAttempt;
1✔
657
    }
658

659
    private void updateState(ConnectivityState newState) {
660
      this.state = newState;
1✔
661
      if (newState == READY || newState == TRANSIENT_FAILURE) {
1✔
662
        completedConnectivityAttempt = true;
1✔
663
      } else if (newState == IDLE) {
1✔
664
        completedConnectivityAttempt = false;
1✔
665
      }
666
    }
1✔
667

668
    private ConnectivityState getHealthState() {
669
      return healthListener.healthStateInfo.getState();
1✔
670
    }
671
  }
672

673
  public static final class PickFirstLeafLoadBalancerConfig {
674

675
    @Nullable
676
    public final Boolean shuffleAddressList;
677

678
    // For testing purposes only, not meant to be parsed from a real config.
679
    @Nullable
680
    final Long randomSeed;
681

682
    public PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList) {
683
      this(shuffleAddressList, null);
1✔
684
    }
1✔
685

686
    PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList,
687
        @Nullable Long randomSeed) {
1✔
688
      this.shuffleAddressList = shuffleAddressList;
1✔
689
      this.randomSeed = randomSeed;
1✔
690
    }
1✔
691
  }
692
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc