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

grpc / grpc-java / #19292

21 Jun 2024 08:20PM UTC coverage: 88.319% (+0.002%) from 88.317%
#19292

push

github

web-flow
Eliminate NPE after recovering from a temporary name resolution failure. (#11298)

* Eliminate NPE after recovering from a temporary name resolution failure.

* Add test case for 2 failing subchannels to make sure it causes channel to go into TF.

32073 of 36315 relevant lines covered (88.32%)

0.88 hits per line

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

95.54
/../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
    if (rawConnectivityState == SHUTDOWN) {
1✔
184
      return;
×
185
    }
186

187
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
188
      subchannelData.getSubchannel().shutdown();
1✔
189
    }
1✔
190
    subchannels.clear();
1✔
191
    if (addressIndex != null) {
1✔
192
      addressIndex.updateGroups(null);
1✔
193
    }
194
    rawConnectivityState = TRANSIENT_FAILURE;
1✔
195
    updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(error)));
1✔
196
  }
1✔
197

198
  void processSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
199
    ConnectivityState newState = stateInfo.getState();
1✔
200

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

209
    if (newState == SHUTDOWN) {
1✔
210
      return;
×
211
    }
212

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

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

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

246
      case CONNECTING:
247
        rawConnectivityState = CONNECTING;
1✔
248
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
249
        break;
1✔
250

251
      case READY:
252
        shutdownRemaining(subchannelData);
1✔
253
        addressIndex.seekTo(getAddress(subchannel));
1✔
254
        rawConnectivityState = READY;
1✔
255
        updateHealthCheckedState(subchannelData);
1✔
256
        break;
1✔
257

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

268
        if (isPassComplete()) {
1✔
269
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
270
          updateBalancingState(TRANSIENT_FAILURE,
1✔
271
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
272

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

287
      default:
288
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
289
    }
290
  }
1✔
291

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

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

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

325
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
326
      subchannelData.getSubchannel().shutdown();
1✔
327
    }
1✔
328

329
    subchannels.clear();
1✔
330
  }
1✔
331

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

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

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

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

395

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

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

416
    SynchronizationContext synchronizationContext = null;
1✔
417
    try {
418
      synchronizationContext = helper.getSynchronizationContext();
1✔
419
    } catch (NullPointerException e) {
×
420
      // All helpers should have a sync context, but if one doesn't (ex. user had a custom test)
421
      // we don't want to break previously working functionality.
422
      return;
×
423
    }
1✔
424

425
    scheduleConnectionTask = synchronizationContext.schedule(
1✔
426
        new StartNextConnection(),
427
        CONNECTION_DELAY_INTERVAL_MS,
428
        TimeUnit.MILLISECONDS,
429
        helper.getScheduledExecutorService());
1✔
430
  }
1✔
431

432
  private void cancelScheduleTask() {
433
    if (scheduleConnectionTask != null) {
1✔
434
      scheduleConnectionTask.cancel();
1✔
435
      scheduleConnectionTask = null;
1✔
436
    }
437
  }
1✔
438

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

462
  private boolean isPassComplete() {
463
    if (addressIndex == null || addressIndex.isValid()
1✔
464
        || subchannels.size() < addressIndex.size()) {
1✔
465
      return false;
1✔
466
    }
467
    for (SubchannelData sc : subchannels.values()) {
1✔
468
      if (!sc.isCompletedConnectivityAttempt() ) {
1✔
469
        return false;
1✔
470
      }
471
    }
1✔
472
    return true;
1✔
473
  }
474

475
  private final class HealthListener implements SubchannelStateListener {
1✔
476
    private ConnectivityStateInfo healthStateInfo = ConnectivityStateInfo.forNonError(IDLE);
1✔
477
    private SubchannelData subchannelData;
478

479
    @Override
480
    public void onSubchannelState(ConnectivityStateInfo newState) {
481
      log.log(Level.FINE, "Received health status {0} for subchannel {1}",
1✔
482
          new Object[]{newState, subchannelData.subchannel});
1✔
483
      healthStateInfo = newState;
1✔
484
      try {
485
        SubchannelData curSubChanData = subchannels.get(addressIndex.getCurrentAddress());
1✔
486
        if (curSubChanData != null && curSubChanData.healthListener == this) {
1✔
487
          updateHealthCheckedState(subchannelData);
1✔
488
        }
489
      } catch (IllegalStateException e) {
×
490
        log.fine("Health listener received state change after subchannel was removed");
×
491
      }
1✔
492
    }
1✔
493
  }
494

495
  private SocketAddress getAddress(Subchannel subchannel) {
496
    return subchannel.getAddresses().getAddresses().get(0);
1✔
497
  }
498

499
  @VisibleForTesting
500
  ConnectivityState getConcludedConnectivityState() {
501
    return this.concludedState;
1✔
502
  }
503

504
  /**
505
   * No-op picker which doesn't add any custom picking logic. It just passes already known result
506
   * received in constructor.
507
   */
508
  private static final class Picker extends SubchannelPicker {
509
    private final PickResult result;
510

511
    Picker(PickResult result) {
1✔
512
      this.result = checkNotNull(result, "result");
1✔
513
    }
1✔
514

515
    @Override
516
    public PickResult pickSubchannel(PickSubchannelArgs args) {
517
      return result;
1✔
518
    }
519

520
    @Override
521
    public String toString() {
522
      return MoreObjects.toStringHelper(Picker.class).add("result", result).toString();
×
523
    }
524
  }
525

526
  /**
527
   * Picker that requests connection during the first pick, and returns noResult.
528
   */
529
  private final class RequestConnectionPicker extends SubchannelPicker {
530
    private final PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer;
531
    private final AtomicBoolean connectionRequested = new AtomicBoolean(false);
1✔
532

533
    RequestConnectionPicker(PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer) {
1✔
534
      this.pickFirstLeafLoadBalancer =
1✔
535
          checkNotNull(pickFirstLeafLoadBalancer, "pickFirstLeafLoadBalancer");
1✔
536
    }
1✔
537

538
    @Override
539
    public PickResult pickSubchannel(PickSubchannelArgs args) {
540
      if (connectionRequested.compareAndSet(false, true)) {
1✔
541
        helper.getSynchronizationContext().execute(pickFirstLeafLoadBalancer::requestConnection);
1✔
542
      }
543
      return PickResult.withNoResult();
1✔
544
    }
545
  }
546

547
  /**
548
   * Index as in 'i', the pointer to an entry. Not a "search index."
549
   * All updates should be done in a synchronization context.
550
   */
551
  @VisibleForTesting
552
  static final class Index {
553
    private List<EquivalentAddressGroup> addressGroups;
554
    private int groupIndex;
555
    private int addressIndex;
556

557
    public Index(List<EquivalentAddressGroup> groups) {
1✔
558
      this.addressGroups = groups != null ? groups : Collections.emptyList();
1✔
559
    }
1✔
560

561
    public boolean isValid() {
562
      // Is invalid if empty or has incremented off the end
563
      return groupIndex < addressGroups.size();
1✔
564
    }
565

566
    public boolean isAtBeginning() {
567
      return groupIndex == 0 && addressIndex == 0;
1✔
568
    }
569

570
    /**
571
     * Move to next address in group.  If last address in group move to first address of next group.
572
     * @return false if went off end of the list, otherwise true
573
     */
574
    public boolean increment() {
575
      if (!isValid()) {
1✔
576
        return false;
1✔
577
      }
578

579
      EquivalentAddressGroup group = addressGroups.get(groupIndex);
1✔
580
      addressIndex++;
1✔
581
      if (addressIndex >= group.getAddresses().size()) {
1✔
582
        groupIndex++;
1✔
583
        addressIndex = 0;
1✔
584
        return groupIndex < addressGroups.size();
1✔
585
      }
586

587
      return true;
1✔
588
    }
589

590
    public void reset() {
591
      groupIndex = 0;
1✔
592
      addressIndex = 0;
1✔
593
    }
1✔
594

595
    public SocketAddress getCurrentAddress() {
596
      if (!isValid()) {
1✔
597
        throw new IllegalStateException("Index is past the end of the address group list");
×
598
      }
599
      return addressGroups.get(groupIndex).getAddresses().get(addressIndex);
1✔
600
    }
601

602
    public Attributes getCurrentEagAttributes() {
603
      if (!isValid()) {
1✔
604
        throw new IllegalStateException("Index is off the end of the address group list");
×
605
      }
606
      return addressGroups.get(groupIndex).getAttributes();
1✔
607
    }
608

609
    public List<EquivalentAddressGroup> getCurrentEagAsList() {
610
      return Collections.singletonList(
1✔
611
          new EquivalentAddressGroup(getCurrentAddress(), getCurrentEagAttributes()));
1✔
612
    }
613

614
    /**
615
     * Update to new groups, resetting the current index.
616
     */
617
    public void updateGroups(ImmutableList<EquivalentAddressGroup> newGroups) {
618
      addressGroups = newGroups != null ? newGroups : Collections.emptyList();
1✔
619
      reset();
1✔
620
    }
1✔
621

622
    /**
623
     * Returns false if the needle was not found and the current index was left unchanged.
624
     */
625
    public boolean seekTo(SocketAddress needle) {
626
      for (int i = 0; i < addressGroups.size(); i++) {
1✔
627
        EquivalentAddressGroup group = addressGroups.get(i);
1✔
628
        int j = group.getAddresses().indexOf(needle);
1✔
629
        if (j == -1) {
1✔
630
          continue;
1✔
631
        }
632
        this.groupIndex = i;
1✔
633
        this.addressIndex = j;
1✔
634
        return true;
1✔
635
      }
636
      return false;
1✔
637
    }
638

639
    public int size() {
640
      return (addressGroups != null) ? addressGroups.size() : 0;
1✔
641
    }
642
  }
643

644
  private static final class SubchannelData {
645
    private final Subchannel subchannel;
646
    private ConnectivityState state;
647
    private final HealthListener healthListener;
648
    private boolean completedConnectivityAttempt = false;
1✔
649

650
    public SubchannelData(Subchannel subchannel, ConnectivityState state,
651
                          HealthListener subchannelHealthListener) {
1✔
652
      this.subchannel = subchannel;
1✔
653
      this.state = state;
1✔
654
      this.healthListener = subchannelHealthListener;
1✔
655
    }
1✔
656

657
    public Subchannel getSubchannel() {
658
      return this.subchannel;
1✔
659
    }
660

661
    public ConnectivityState getState() {
662
      return this.state;
1✔
663
    }
664

665
    public boolean isCompletedConnectivityAttempt() {
666
      return completedConnectivityAttempt;
1✔
667
    }
668

669
    private void updateState(ConnectivityState newState) {
670
      this.state = newState;
1✔
671
      if (newState == READY || newState == TRANSIENT_FAILURE) {
1✔
672
        completedConnectivityAttempt = true;
1✔
673
      } else if (newState == IDLE) {
1✔
674
        completedConnectivityAttempt = false;
1✔
675
      }
676
    }
1✔
677

678
    private ConnectivityState getHealthState() {
679
      return healthListener.healthStateInfo.getState();
1✔
680
    }
681
  }
682

683
  public static final class PickFirstLeafLoadBalancerConfig {
684

685
    @Nullable
686
    public final Boolean shuffleAddressList;
687

688
    // For testing purposes only, not meant to be parsed from a real config.
689
    @Nullable
690
    final Long randomSeed;
691

692
    public PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList) {
693
      this(shuffleAddressList, null);
1✔
694
    }
1✔
695

696
    PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList,
697
        @Nullable Long randomSeed) {
1✔
698
      this.shuffleAddressList = shuffleAddressList;
1✔
699
      this.randomSeed = randomSeed;
1✔
700
    }
1✔
701
  }
702
}
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