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

grpc / grpc-java / #19097

11 Mar 2024 09:12PM UTC coverage: 88.289% (-0.02%) from 88.31%
#19097

push

github

web-flow
Prepare to switch flag to use new PickFirstLeafLoadBalancer by default (#10998)

* Fix PickFirstLeafLoadBalancer and tests to work when it is used.
* Actually use EAG attributes for subchannels.

31158 of 35291 relevant lines covered (88.29%)

0.88 hits per line

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

95.39
/../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.ExperimentalApi;
35
import io.grpc.LoadBalancer;
36
import io.grpc.Status;
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
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/10383")
59
final class PickFirstLeafLoadBalancer extends LoadBalancer {
60
  private static final Logger log = Logger.getLogger(PickFirstLeafLoadBalancer.class.getName());
1✔
61
  @VisibleForTesting
62
  static final int CONNECTION_DELAY_INTERVAL_MS = 250;
63
  public static final String GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS =
64
      "GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS";
65
  private final Helper helper;
66
  private final Map<SocketAddress, SubchannelData> subchannels = new HashMap<>();
1✔
67
  private Index addressIndex;
68
  private int numTf = 0;
1✔
69
  private boolean firstPass = true;
1✔
70
  @Nullable
71
  private ScheduledHandle scheduleConnectionTask;
72
  private ConnectivityState rawConnectivityState = IDLE;
1✔
73
  private ConnectivityState concludedState = IDLE;
1✔
74
  private final boolean enableHappyEyeballs =
1✔
75
      GrpcUtil.getFlag(GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS, false);
1✔
76

77
  PickFirstLeafLoadBalancer(Helper helper) {
1✔
78
    this.helper = checkNotNull(helper, "helper");
1✔
79
  }
1✔
80

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

87
    List<EquivalentAddressGroup> servers = resolvedAddresses.getAddresses();
1✔
88

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

108
    // Since we have a new set of addresses, we are again at first pass
109
    firstPass = true;
1✔
110

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

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

128
    if (addressIndex == null) {
1✔
129
      addressIndex = new Index(newImmutableAddressGroups);
1✔
130
    } else if (rawConnectivityState == READY) {
1✔
131
      // If the previous ready subchannel exists in new address list,
132
      // keep this connection and don't create new subchannels
133
      SocketAddress previousAddress = addressIndex.getCurrentAddress();
1✔
134
      Attributes prevEagAttrs = addressIndex.getCurrentEagAttributes();
1✔
135
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
136
      if (addressIndex.seekTo(previousAddress)) {
1✔
137
        if (!addressIndex.getCurrentEagAttributes().equals(prevEagAttrs)) {
1✔
138
          log.log(Level.FINE, "EAG attributes changed, need to update subchannel");
×
139
          SubchannelData subchannelData = subchannels.get(previousAddress);
×
140
          subchannelData.getSubchannel().updateAddresses(addressIndex.getCurrentEagAsList());
×
141
        }
142
        return Status.OK;
1✔
143
      } else {
144
        addressIndex.reset(); // Previous ready subchannel not in the new list of addresses
1✔
145
      }
146
    } else {
1✔
147
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
148
    }
149

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

153
    // Flatten the new EAGs addresses
154
    Set<SocketAddress> newAddrs = new HashSet<>();
1✔
155
    for (EquivalentAddressGroup endpoint : newImmutableAddressGroups) {
1✔
156
      newAddrs.addAll(endpoint.getAddresses());
1✔
157
    }
1✔
158

159
    // Shut them down and remove them
160
    for (SocketAddress oldAddr : oldAddrs) {
1✔
161
      if (!newAddrs.contains(oldAddr)) {
1✔
162
        subchannels.remove(oldAddr).getSubchannel().shutdown();
1✔
163
      }
164
    }
1✔
165

166
    if (oldAddrs.size() == 0 || rawConnectivityState == CONNECTING
1✔
167
        || rawConnectivityState == READY) {
168
      // start connection attempt at first address
169
      rawConnectivityState = CONNECTING;
1✔
170
      updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
171
      cancelScheduleTask();
1✔
172
      requestConnection();
1✔
173

174
    } else if (rawConnectivityState == IDLE) {
1✔
175
      // start connection attempt at first address when requested
176
      SubchannelPicker picker = new RequestConnectionPicker(this);
1✔
177
      updateBalancingState(IDLE, picker);
1✔
178

179
    } else if (rawConnectivityState == TRANSIENT_FAILURE) {
1✔
180
      // start connection attempt at first address
181
      cancelScheduleTask();
1✔
182
      requestConnection();
1✔
183
    }
184

185
    return Status.OK;
1✔
186
  }
187

188
  @Override
189
  public void handleNameResolutionError(Status error) {
190
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
191
      subchannelData.getSubchannel().shutdown();
1✔
192
    }
1✔
193
    subchannels.clear();
1✔
194
    updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(error)));
1✔
195
  }
1✔
196

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

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

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

235
    switch (newState) {
1✔
236
      case IDLE:
237
        // Shutdown when ready: connect from beginning when prompted
238
        addressIndex.reset();
1✔
239
        rawConnectivityState = IDLE;
1✔
240
        updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
241
        break;
1✔
242

243
      case CONNECTING:
244
        rawConnectivityState = CONNECTING;
1✔
245
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
246
        break;
1✔
247

248
      case READY:
249
        shutdownRemaining(subchannelData);
1✔
250
        addressIndex.seekTo(getAddress(subchannel));
1✔
251
        rawConnectivityState = READY;
1✔
252
        updateHealthCheckedState(subchannelData);
1✔
253
        break;
1✔
254

255
      case TRANSIENT_FAILURE:
256
        // If we are looking at current channel, request a connection if possible
257
        if (addressIndex.isValid()
1✔
258
            && subchannels.get(addressIndex.getCurrentAddress()).getSubchannel() == subchannel) {
1✔
259
          if (addressIndex.increment()) {
1✔
260
            cancelScheduleTask();
1✔
261
            requestConnection(); // is recursive so might hit the end of the addresses
1✔
262
          }
263
        }
264

265
        if (isPassComplete()) {
1✔
266
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
267
          updateBalancingState(TRANSIENT_FAILURE,
1✔
268
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
269

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

284
      default:
285
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
286
    }
287
  }
1✔
288

289
  private void updateHealthCheckedState(SubchannelData subchannelData) {
290
    if (subchannelData.state != READY) {
1✔
291
      return;
1✔
292
    }
293
    if (subchannelData.getHealthState() == READY) {
1✔
294
      updateBalancingState(READY,
1✔
295
          new FixedResultPicker(PickResult.withSubchannel(subchannelData.subchannel)));
1✔
296
    } else if (subchannelData.getHealthState() == TRANSIENT_FAILURE) {
1✔
297
      updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(
1✔
298
          subchannelData.healthListener.healthStateInfo.getStatus())));
1✔
299
    } else if (concludedState != TRANSIENT_FAILURE) {
1✔
300
      updateBalancingState(subchannelData.getHealthState(),
1✔
301
          new Picker(PickResult.withNoResult()));
1✔
302
    }
303
  }
1✔
304

305
  private void updateBalancingState(ConnectivityState state, SubchannelPicker picker) {
306
    // an optimization: de-dup IDLE or CONNECTING notification.
307
    if (state == concludedState && (state == IDLE || state == CONNECTING)) {
1✔
308
      return;
1✔
309
    }
310
    concludedState = state;
1✔
311
    helper.updateBalancingState(state, picker);
1✔
312
  }
1✔
313

314
  @Override
315
  public void shutdown() {
316
    log.log(Level.FINE,
1✔
317
        "Shutting down, currently have {} subchannels created", subchannels.size());
1✔
318
    rawConnectivityState = SHUTDOWN;
1✔
319
    concludedState = SHUTDOWN;
1✔
320
    cancelScheduleTask();
1✔
321

322
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
323
      subchannelData.getSubchannel().shutdown();
1✔
324
    }
1✔
325

326
    subchannels.clear();
1✔
327
  }
1✔
328

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

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

358
    Subchannel subchannel;
359
    SocketAddress currentAddress;
360
    currentAddress = addressIndex.getCurrentAddress();
1✔
361
    subchannel = subchannels.containsKey(currentAddress)
1✔
362
        ? subchannels.get(currentAddress).getSubchannel()
1✔
363
        : createNewSubchannel(currentAddress, addressIndex.getCurrentEagAttributes());
1✔
364

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

392

393
  /**
394
  * Happy Eyeballs
395
  * Schedules connection attempt to happen after a delay to the next available address.
396
  */
397
  private void scheduleNextConnection() {
398
    if (!enableHappyEyeballs
1✔
399
        || (scheduleConnectionTask != null && scheduleConnectionTask.isPending())) {
1✔
400
      return;
1✔
401
    }
402

403
    class StartNextConnection implements Runnable {
1✔
404
      @Override
405
      public void run() {
406
        scheduleConnectionTask = null;
1✔
407
        if (addressIndex.increment()) {
1✔
408
          requestConnection();
1✔
409
        }
410
      }
1✔
411
    }
412

413
    scheduleConnectionTask = helper.getSynchronizationContext().schedule(
1✔
414
        new StartNextConnection(),
415
        CONNECTION_DELAY_INTERVAL_MS,
416
        TimeUnit.MILLISECONDS,
417
        helper.getScheduledExecutorService());
1✔
418
  }
1✔
419

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

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

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

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

467
    @Override
468
    public void onSubchannelState(ConnectivityStateInfo newState) {
469
      log.log(Level.FINE, "Received health status {0} for subchannel {1}",
1✔
470
          new Object[]{newState, subchannelData.subchannel});
1✔
471
      healthStateInfo = newState;
1✔
472
      if (addressIndex.isValid()
1✔
473
          && subchannels.get(addressIndex.getCurrentAddress()).healthListener == this) {
1✔
474
        updateHealthCheckedState(subchannelData);
1✔
475
      }
476
    }
1✔
477
  }
478

479
  private SocketAddress getAddress(Subchannel subchannel) {
480
    return subchannel.getAddresses().getAddresses().get(0);
1✔
481
  }
482

483
  @VisibleForTesting
484
  ConnectivityState getConcludedConnectivityState() {
485
    return this.concludedState;
1✔
486
  }
487

488
  /**
489
   * No-op picker which doesn't add any custom picking logic. It just passes already known result
490
   * received in constructor.
491
   */
492
  private static final class Picker extends SubchannelPicker {
493
    private final PickResult result;
494

495
    Picker(PickResult result) {
1✔
496
      this.result = checkNotNull(result, "result");
1✔
497
    }
1✔
498

499
    @Override
500
    public PickResult pickSubchannel(PickSubchannelArgs args) {
501
      return result;
1✔
502
    }
503

504
    @Override
505
    public String toString() {
506
      return MoreObjects.toStringHelper(Picker.class).add("result", result).toString();
×
507
    }
508
  }
509

510
  /**
511
   * Picker that requests connection during the first pick, and returns noResult.
512
   */
513
  private final class RequestConnectionPicker extends SubchannelPicker {
514
    private final PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer;
515
    private final AtomicBoolean connectionRequested = new AtomicBoolean(false);
1✔
516

517
    RequestConnectionPicker(PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer) {
1✔
518
      this.pickFirstLeafLoadBalancer =
1✔
519
          checkNotNull(pickFirstLeafLoadBalancer, "pickFirstLeafLoadBalancer");
1✔
520
    }
1✔
521

522
    @Override
523
    public PickResult pickSubchannel(PickSubchannelArgs args) {
524
      if (connectionRequested.compareAndSet(false, true)) {
1✔
525
        helper.getSynchronizationContext().execute(pickFirstLeafLoadBalancer::requestConnection);
1✔
526
      }
527
      return PickResult.withNoResult();
1✔
528
    }
529
  }
530

531
  /**
532
   * Index as in 'i', the pointer to an entry. Not a "search index."
533
   * All updates should be done in a synchronization context.
534
   */
535
  @VisibleForTesting
536
  static final class Index {
537
    private List<EquivalentAddressGroup> addressGroups;
538
    private int groupIndex;
539
    private int addressIndex;
540

541
    public Index(List<EquivalentAddressGroup> groups) {
1✔
542
      this.addressGroups = groups != null ? groups : Collections.emptyList();
1✔
543
    }
1✔
544

545
    public boolean isValid() {
546
      // Is invalid if empty or has incremented off the end
547
      return groupIndex < addressGroups.size();
1✔
548
    }
549

550
    public boolean isAtBeginning() {
551
      return groupIndex == 0 && addressIndex == 0;
1✔
552
    }
553

554
    /**
555
     * Move to next address in group.  If last address in group move to first address of next group.
556
     * @return false if went off end of the list, otherwise true
557
     */
558
    public boolean increment() {
559
      if (!isValid()) {
1✔
560
        return false;
1✔
561
      }
562

563
      EquivalentAddressGroup group = addressGroups.get(groupIndex);
1✔
564
      addressIndex++;
1✔
565
      if (addressIndex >= group.getAddresses().size()) {
1✔
566
        groupIndex++;
1✔
567
        addressIndex = 0;
1✔
568
        return groupIndex < addressGroups.size();
1✔
569
      }
570

571
      return true;
1✔
572
    }
573

574
    public void reset() {
575
      groupIndex = 0;
1✔
576
      addressIndex = 0;
1✔
577
    }
1✔
578

579
    public SocketAddress getCurrentAddress() {
580
      if (!isValid()) {
1✔
581
        throw new IllegalStateException("Index is past the end of the address group list");
×
582
      }
583
      return addressGroups.get(groupIndex).getAddresses().get(addressIndex);
1✔
584
    }
585

586
    public Attributes getCurrentEagAttributes() {
587
      if (!isValid()) {
1✔
588
        throw new IllegalStateException("Index is off the end of the address group list");
×
589
      }
590
      return addressGroups.get(groupIndex).getAttributes();
1✔
591
    }
592

593
    public List<EquivalentAddressGroup> getCurrentEagAsList() {
594
      return Collections.singletonList(
×
595
          new EquivalentAddressGroup(getCurrentAddress(), getCurrentEagAttributes()));
×
596
    }
597

598
    /**
599
     * Update to new groups, resetting the current index.
600
     */
601
    public void updateGroups(ImmutableList<EquivalentAddressGroup> newGroups) {
602
      addressGroups = newGroups != null ? newGroups : Collections.emptyList();
1✔
603
      reset();
1✔
604
    }
1✔
605

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

623
    public int size() {
624
      return (addressGroups != null) ? addressGroups.size() : 0;
1✔
625
    }
626
  }
627

628
  private static final class SubchannelData {
629
    private final Subchannel subchannel;
630
    private ConnectivityState state;
631
    private final HealthListener healthListener;
632
    private boolean completedConnectivityAttempt = false;
1✔
633

634
    public SubchannelData(Subchannel subchannel, ConnectivityState state,
635
                          HealthListener subchannelHealthListener) {
1✔
636
      this.subchannel = subchannel;
1✔
637
      this.state = state;
1✔
638
      this.healthListener = subchannelHealthListener;
1✔
639
    }
1✔
640

641
    public Subchannel getSubchannel() {
642
      return this.subchannel;
1✔
643
    }
644

645
    public ConnectivityState getState() {
646
      return this.state;
1✔
647
    }
648

649
    public boolean isCompletedConnectivityAttempt() {
650
      return completedConnectivityAttempt;
1✔
651
    }
652

653
    private void updateState(ConnectivityState newState) {
654
      this.state = newState;
1✔
655
      if (newState == READY || newState == TRANSIENT_FAILURE) {
1✔
656
        completedConnectivityAttempt = true;
1✔
657
      } else if (newState == IDLE) {
1✔
658
        completedConnectivityAttempt = false;
1✔
659
      }
660
    }
1✔
661

662
    private ConnectivityState getHealthState() {
663
      return healthListener.healthStateInfo.getState();
1✔
664
    }
665
  }
666

667
  public static final class PickFirstLeafLoadBalancerConfig {
668

669
    @Nullable
670
    public final Boolean shuffleAddressList;
671

672
    // For testing purposes only, not meant to be parsed from a real config.
673
    @Nullable
674
    final Long randomSeed;
675

676
    public PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList) {
677
      this(shuffleAddressList, null);
1✔
678
    }
1✔
679

680
    PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList,
681
        @Nullable Long randomSeed) {
1✔
682
      this.shuffleAddressList = shuffleAddressList;
1✔
683
      this.randomSeed = randomSeed;
1✔
684
    }
1✔
685
  }
686
}
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

© 2026 Coveralls, Inc