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

grpc / grpc-java / #19435

22 Aug 2024 06:23PM UTC coverage: 84.503% (+0.01%) from 84.489%
#19435

push

github

ejona86
core: In PF, disjoint update while READY should transition to IDLE

This is the same as if we received a GOAWAY. We wait for the next RPC to
begin connecting again. This is InternalSubchannel's behavior.

33394 of 39518 relevant lines covered (84.5%)

0.85 hits per line

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

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

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

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

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

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

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

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

107
    List<EquivalentAddressGroup> cleanServers = deDupAddresses(servers);
1✔
108

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

121
    final ImmutableList<EquivalentAddressGroup> newImmutableAddressGroups =
122
        ImmutableList.<EquivalentAddressGroup>builder().addAll(cleanServers).build();
1✔
123

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

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

142
    // Flatten the new EAGs addresses
143
    Set<SocketAddress> newAddrs = new HashSet<>();
1✔
144
    for (EquivalentAddressGroup endpoint : newImmutableAddressGroups) {
1✔
145
      newAddrs.addAll(endpoint.getAddresses());
1✔
146
    }
1✔
147

148
    // Shut them down and remove them
149
    for (SocketAddress oldAddr : oldAddrs) {
1✔
150
      if (!newAddrs.contains(oldAddr)) {
1✔
151
        subchannels.remove(oldAddr).getSubchannel().shutdown();
1✔
152
      }
153
    }
1✔
154

155
    if (oldAddrs.size() == 0) {
1✔
156
      // Make tests happy; they don't properly assume starting in CONNECTING
157
      rawConnectivityState = CONNECTING;
1✔
158
      updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
159
    }
160

161
    if (rawConnectivityState == READY) {
1✔
162
      // connect from beginning when prompted
163
      rawConnectivityState = IDLE;
1✔
164
      updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
165

166
    } else if (rawConnectivityState == CONNECTING || rawConnectivityState == TRANSIENT_FAILURE) {
1✔
167
      // start connection attempt at first address
168
      cancelScheduleTask();
1✔
169
      requestConnection();
1✔
170
    }
171

172
    return Status.OK;
1✔
173
  }
174

175
  private static List<EquivalentAddressGroup> deDupAddresses(List<EquivalentAddressGroup> groups) {
176
    Set<SocketAddress> seenAddresses = new HashSet<>();
1✔
177
    List<EquivalentAddressGroup> newGroups = new ArrayList<>();
1✔
178

179
    for (EquivalentAddressGroup group : groups) {
1✔
180
      List<SocketAddress> addrs = new ArrayList<>();
1✔
181
      for (SocketAddress addr : group.getAddresses()) {
1✔
182
        if (seenAddresses.add(addr)) {
1✔
183
          addrs.add(addr);
1✔
184
        }
185
      }
1✔
186
      if (!addrs.isEmpty()) {
1✔
187
        newGroups.add(new EquivalentAddressGroup(addrs, group.getAttributes()));
1✔
188
      }
189
    }
1✔
190

191
    return newGroups;
1✔
192
  }
193

194
  @Override
195
  public void handleNameResolutionError(Status error) {
196
    if (rawConnectivityState == SHUTDOWN) {
1✔
197
      return;
×
198
    }
199

200
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
201
      subchannelData.getSubchannel().shutdown();
1✔
202
    }
1✔
203
    subchannels.clear();
1✔
204
    addressIndex.updateGroups(ImmutableList.of());
1✔
205
    rawConnectivityState = TRANSIENT_FAILURE;
1✔
206
    updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(error)));
1✔
207
  }
1✔
208

209
  void processSubchannelState(SubchannelData subchannelData, ConnectivityStateInfo stateInfo) {
210
    ConnectivityState newState = stateInfo.getState();
1✔
211

212
    // Shutdown channels/previously relevant subchannels can still callback with state updates.
213
    // To prevent pickers from returning these obsolete subchannels, this logic
214
    // is included to check if the current list of active subchannels includes this subchannel.
215
    if (subchannelData != subchannels.get(getAddress(subchannelData.subchannel))) {
1✔
216
      return;
1✔
217
    }
218

219
    if (newState == SHUTDOWN) {
1✔
220
      return;
1✔
221
    }
222

223
    if (newState == IDLE) {
1✔
224
      helper.refreshNameResolution();
1✔
225
    }
226
    // If we are transitioning from a TRANSIENT_FAILURE to CONNECTING or IDLE we ignore this state
227
    // transition and still keep the LB in TRANSIENT_FAILURE state. This is referred to as "sticky
228
    // transient failure". Only a subchannel state change to READY will get the LB out of
229
    // TRANSIENT_FAILURE. If the state is IDLE we additionally request a new connection so that we
230
    // keep retrying for a connection.
231

232
    // With the new pick first implementation, individual subchannels will have their own backoff
233
    // on a per-address basis. Thus, iterative requests for connections will not be requested
234
    // once the first pass through is complete.
235
    // However, every time there is an address update, we will perform a pass through for the new
236
    // addresses in the updated list.
237
    subchannelData.updateState(newState);
1✔
238
    if (rawConnectivityState == TRANSIENT_FAILURE || concludedState == TRANSIENT_FAILURE)  {
1✔
239
      if (newState == CONNECTING) {
1✔
240
        // each subchannel is responsible for its own backoff
241
        return;
1✔
242
      } else if (newState == IDLE) {
1✔
243
        requestConnection();
1✔
244
        return;
1✔
245
      }
246
    }
247

248
    switch (newState) {
1✔
249
      case IDLE:
250
        // Shutdown when ready: connect from beginning when prompted
251
        addressIndex.reset();
1✔
252
        rawConnectivityState = IDLE;
1✔
253
        updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
254
        break;
1✔
255

256
      case CONNECTING:
257
        rawConnectivityState = CONNECTING;
1✔
258
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
259
        break;
1✔
260

261
      case READY:
262
        shutdownRemaining(subchannelData);
1✔
263
        addressIndex.seekTo(getAddress(subchannelData.subchannel));
1✔
264
        rawConnectivityState = READY;
1✔
265
        updateHealthCheckedState(subchannelData);
1✔
266
        break;
1✔
267

268
      case TRANSIENT_FAILURE:
269
        // If we are looking at current channel, request a connection if possible
270
        if (addressIndex.isValid()
1✔
271
            && subchannels.get(addressIndex.getCurrentAddress()) == subchannelData) {
1✔
272
          if (addressIndex.increment()) {
1✔
273
            cancelScheduleTask();
1✔
274
            requestConnection(); // is recursive so might hit the end of the addresses
1✔
275
          }
276
        }
277

278
        if (isPassComplete()) {
1✔
279
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
280
          updateBalancingState(TRANSIENT_FAILURE,
1✔
281
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
282

283
          // Refresh Name Resolution, but only when all 3 conditions are met
284
          // * We are at the end of addressIndex
285
          // * have had status reported for all subchannels.
286
          // * And one of the following conditions:
287
          //    * Have had enough TF reported since we completed first pass
288
          //    * Just completed the first pass
289
          if (++numTf >= addressIndex.size() || firstPass) {
1✔
290
            firstPass = false;
1✔
291
            numTf = 0;
1✔
292
            helper.refreshNameResolution();
1✔
293
          }
294
        }
295
        break;
296

297
      default:
298
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
299
    }
300
  }
1✔
301

302
  private void updateHealthCheckedState(SubchannelData subchannelData) {
303
    if (subchannelData.state != READY) {
1✔
304
      return;
1✔
305
    }
306
    if (subchannelData.getHealthState() == READY) {
1✔
307
      updateBalancingState(READY,
1✔
308
          new FixedResultPicker(PickResult.withSubchannel(subchannelData.subchannel)));
1✔
309
    } else if (subchannelData.getHealthState() == TRANSIENT_FAILURE) {
1✔
310
      updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(
1✔
311
          subchannelData.healthStateInfo.getStatus())));
1✔
312
    } else if (concludedState != TRANSIENT_FAILURE) {
1✔
313
      updateBalancingState(subchannelData.getHealthState(),
1✔
314
          new Picker(PickResult.withNoResult()));
1✔
315
    }
316
  }
1✔
317

318
  private void updateBalancingState(ConnectivityState state, SubchannelPicker picker) {
319
    // an optimization: de-dup IDLE or CONNECTING notification.
320
    if (state == concludedState && (state == IDLE || state == CONNECTING)) {
1✔
321
      return;
1✔
322
    }
323
    concludedState = state;
1✔
324
    helper.updateBalancingState(state, picker);
1✔
325
  }
1✔
326

327
  @Override
328
  public void shutdown() {
329
    log.log(Level.FINE,
1✔
330
        "Shutting down, currently have {} subchannels created", subchannels.size());
1✔
331
    rawConnectivityState = SHUTDOWN;
1✔
332
    concludedState = SHUTDOWN;
1✔
333
    cancelScheduleTask();
1✔
334

335
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
336
      subchannelData.getSubchannel().shutdown();
1✔
337
    }
1✔
338

339
    subchannels.clear();
1✔
340
  }
1✔
341

342
  /**
343
  * Shuts down remaining subchannels. Called when a subchannel becomes ready, which means
344
  * that all other subchannels must be shutdown.
345
  */
346
  private void shutdownRemaining(SubchannelData activeSubchannelData) {
347
    cancelScheduleTask();
1✔
348
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
349
      if (!subchannelData.getSubchannel().equals(activeSubchannelData.subchannel)) {
1✔
350
        subchannelData.getSubchannel().shutdown();
1✔
351
      }
352
    }
1✔
353
    subchannels.clear();
1✔
354
    activeSubchannelData.updateState(READY);
1✔
355
    subchannels.put(getAddress(activeSubchannelData.subchannel), activeSubchannelData);
1✔
356
  }
1✔
357

358
  /**
359
   * Requests a connection to the next applicable address' subchannel, creating one if necessary.
360
   * Schedules a connection to next address in list as well.
361
   * If the current channel has already attempted a connection, we attempt a connection
362
   * to the next address/subchannel in our list.  We assume that createNewSubchannel will never
363
   * return null.
364
   */
365
  @Override
366
  public void requestConnection() {
367
    if (!addressIndex.isValid() || rawConnectivityState == SHUTDOWN) {
1✔
368
      return;
1✔
369
    }
370

371
    SocketAddress currentAddress = addressIndex.getCurrentAddress();
1✔
372
    SubchannelData subchannelData = subchannels.get(currentAddress);
1✔
373
    if (subchannelData == null) {
1✔
374
      subchannelData = createNewSubchannel(currentAddress, addressIndex.getCurrentEagAttributes());
1✔
375
    }
376

377
    ConnectivityState subchannelState = subchannelData.getState();
1✔
378
    switch (subchannelState) {
1✔
379
      case IDLE:
380
        subchannelData.subchannel.requestConnection();
1✔
381
        subchannelData.updateState(CONNECTING);
1✔
382
        scheduleNextConnection();
1✔
383
        break;
1✔
384
      case CONNECTING:
385
        scheduleNextConnection();
1✔
386
        break;
1✔
387
      case TRANSIENT_FAILURE:
388
        addressIndex.increment();
1✔
389
        requestConnection();
1✔
390
        break;
1✔
391
      default:
392
        // Wait for current subchannel to change state
393
    }
394
  }
1✔
395

396

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

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

417
    scheduleConnectionTask = helper.getSynchronizationContext().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 SubchannelData 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);
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
      subchannelData.healthStateInfo = ConnectivityStateInfo.forNonError(READY);
1✔
449
    }
450
    subchannel.start(stateInfo -> processSubchannelState(subchannelData, stateInfo));
1✔
451
    return subchannelData;
1✔
452
  }
453

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

466
  private final class HealthListener implements SubchannelStateListener {
1✔
467
    private SubchannelData subchannelData;
468

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

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

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

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

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

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

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

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

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

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

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

544
    public Index(List<EquivalentAddressGroup> groups) {
1✔
545
      updateGroups(groups);
1✔
546
    }
1✔
547

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

553
    public boolean isAtBeginning() {
554
      return groupIndex == 0 && addressIndex == 0;
1✔
555
    }
556

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

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

574
      return true;
1✔
575
    }
576

577
    public void reset() {
578
      groupIndex = 0;
1✔
579
      addressIndex = 0;
1✔
580
    }
1✔
581

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

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

596
    public List<EquivalentAddressGroup> getCurrentEagAsList() {
597
      return Collections.singletonList(
1✔
598
          new EquivalentAddressGroup(getCurrentAddress(), getCurrentEagAttributes()));
1✔
599
    }
600

601
    /**
602
     * Update to new groups, resetting the current index.
603
     */
604
    public void updateGroups(List<EquivalentAddressGroup> newGroups) {
605
      addressGroups = checkNotNull(newGroups, "newGroups");
1✔
606
      reset();
1✔
607
      int size = 0;
1✔
608
      for (EquivalentAddressGroup eag : newGroups) {
1✔
609
        size += eag.getAddresses().size();
1✔
610
      }
1✔
611
      this.size = size;
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 size;
1✔
633
    }
634
  }
635

636
  private static final class SubchannelData {
637
    private final Subchannel subchannel;
638
    private ConnectivityState state;
639
    private boolean completedConnectivityAttempt = false;
1✔
640
    private ConnectivityStateInfo healthStateInfo = ConnectivityStateInfo.forNonError(IDLE);
1✔
641

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

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

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

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

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

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

673
  public static final class PickFirstLeafLoadBalancerConfig {
674

675
    @Nullable
676
    public final Boolean shuffleAddressList;
677

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

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

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

© 2025 Coveralls, Inc