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

grpc / grpc-java / #19102

14 Mar 2024 03:53AM UTC coverage: 88.259% (-0.05%) from 88.311%
#19102

push

github

web-flow
core: Eliminate NPE seen in PickFirstLeafLoadBalancer (#11013)

ref b/329420531

31150 of 35294 relevant lines covered (88.26%)

0.88 hits per line

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

97.37
/../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
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
135
      if (addressIndex.seekTo(previousAddress)) {
1✔
136
        SubchannelData subchannelData = subchannels.get(previousAddress);
1✔
137
        subchannelData.getSubchannel().updateAddresses(addressIndex.getCurrentEagAsList());
1✔
138
        return Status.OK;
1✔
139
      } else {
140
        addressIndex.reset(); // Previous ready subchannel not in the new list of addresses
1✔
141
      }
142
    } else {
1✔
143
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
144
    }
145

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

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

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

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

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

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

181
    return Status.OK;
1✔
182
  }
183

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

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

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

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

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

239
      case CONNECTING:
240
        rawConnectivityState = CONNECTING;
1✔
241
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
242
        break;
1✔
243

244
      case READY:
245
        shutdownRemaining(subchannelData);
1✔
246
        addressIndex.seekTo(getAddress(subchannel));
1✔
247
        rawConnectivityState = READY;
1✔
248
        updateHealthCheckedState(subchannelData);
1✔
249
        break;
1✔
250

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

261
        if (isPassComplete()) {
1✔
262
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
263
          updateBalancingState(TRANSIENT_FAILURE,
1✔
264
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
265

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

280
      default:
281
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
282
    }
283
  }
1✔
284

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

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

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

318
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
319
      subchannelData.getSubchannel().shutdown();
1✔
320
    }
1✔
321

322
    subchannels.clear();
1✔
323
  }
1✔
324

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

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

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

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

388

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

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

409
    scheduleConnectionTask = helper.getSynchronizationContext().schedule(
1✔
410
        new StartNextConnection(),
411
        CONNECTION_DELAY_INTERVAL_MS,
412
        TimeUnit.MILLISECONDS,
413
        helper.getScheduledExecutorService());
1✔
414
  }
1✔
415

416
  private void cancelScheduleTask() {
417
    if (scheduleConnectionTask != null) {
1✔
418
      scheduleConnectionTask.cancel();
1✔
419
      scheduleConnectionTask = null;
1✔
420
    }
421
  }
1✔
422

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

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

459
  private final class HealthListener implements SubchannelStateListener {
1✔
460
    private ConnectivityStateInfo healthStateInfo = ConnectivityStateInfo.forNonError(IDLE);
1✔
461
    private SubchannelData subchannelData;
462

463
    @Override
464
    public void onSubchannelState(ConnectivityStateInfo newState) {
465
      log.log(Level.FINE, "Received health status {0} for subchannel {1}",
1✔
466
          new Object[]{newState, subchannelData.subchannel});
1✔
467
      healthStateInfo = newState;
1✔
468
      try {
469
        SubchannelData curSubChanData = subchannels.get(addressIndex.getCurrentAddress());
1✔
470
        if (curSubChanData != null && curSubChanData.healthListener == this) {
1✔
471
          updateHealthCheckedState(subchannelData);
1✔
472
        }
473
      } catch (IllegalStateException e) {
×
474
        log.fine("Health listener received state change after subchannel was removed");
×
475
      }
1✔
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();
1✔
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(
1✔
595
          new EquivalentAddressGroup(getCurrentAddress(), getCurrentEagAttributes()));
1✔
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