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

grpc / grpc-java / #19214

09 May 2024 12:14AM CUT coverage: 88.262% (+0.01%) from 88.25%
#19214

push

github

web-flow
Change HappyEyeballs and new pick first LB flags default value to false (1.63.x backport) (#11176)

* port PR 11120

* Revert backported changes that aren't relevant for v1.63.x

* Revert backported changes that aren't relevant for v1.63.x

31214 of 35365 relevant lines covered (88.26%)

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.ExperimentalApi;
35
import io.grpc.LoadBalancer;
36
import io.grpc.Status;
37
import io.grpc.SynchronizationContext;
38
import io.grpc.SynchronizationContext.ScheduledHandle;
39
import java.net.SocketAddress;
40
import java.util.ArrayList;
41
import java.util.Collections;
42
import java.util.HashMap;
43
import java.util.HashSet;
44
import java.util.List;
45
import java.util.Map;
46
import java.util.Random;
47
import java.util.Set;
48
import java.util.concurrent.TimeUnit;
49
import java.util.concurrent.atomic.AtomicBoolean;
50
import java.util.logging.Level;
51
import java.util.logging.Logger;
52
import javax.annotation.Nullable;
53

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

180
    return Status.OK;
1✔
181
  }
182

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

387

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

579
      return true;
1✔
580
    }
581

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

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

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

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

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

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

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

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

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

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

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

657
    public boolean isCompletedConnectivityAttempt() {
658
      return completedConnectivityAttempt;
1✔
659
    }
660

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

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

675
  public static final class PickFirstLeafLoadBalancerConfig {
676

677
    @Nullable
678
    public final Boolean shuffleAddressList;
679

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

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

688
    PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList,
689
        @Nullable Long randomSeed) {
1✔
690
      this.shuffleAddressList = shuffleAddressList;
1✔
691
      this.randomSeed = randomSeed;
1✔
692
    }
1✔
693
  }
694
}
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