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

grpc / grpc-java / #19431

21 Aug 2024 02:16PM CUT coverage: 84.49% (+0.01%) from 84.479%
#19431

push

github

ejona86
core: In PF, remove extraneous index.reset()

The index was just reset by updateGroups().

33394 of 39524 relevant lines covered (84.49%)

0.84 hits per line

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

97.76
/../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 || rawConnectivityState == CONNECTING
1✔
156
        || rawConnectivityState == READY) {
157
      // start connection attempt at first address
158
      rawConnectivityState = CONNECTING;
1✔
159
      updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
160
      cancelScheduleTask();
1✔
161
      requestConnection();
1✔
162

163
    } else if (rawConnectivityState == IDLE) {
1✔
164
      // start connection attempt at first address when requested
165
      SubchannelPicker picker = new RequestConnectionPicker(this);
1✔
166
      updateBalancingState(IDLE, picker);
1✔
167

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

174
    return Status.OK;
1✔
175
  }
176

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

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

193
    return newGroups;
1✔
194
  }
195

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

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

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

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

221
    if (newState == SHUTDOWN) {
1✔
222
      return;
1✔
223
    }
224

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

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

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

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

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

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

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

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

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

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

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

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

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

341
    subchannels.clear();
1✔
342
  }
1✔
343

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

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

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

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

398

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

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

419
    scheduleConnectionTask = helper.getSynchronizationContext().schedule(
1✔
420
        new StartNextConnection(),
421
        CONNECTION_DELAY_INTERVAL_MS,
422
        TimeUnit.MILLISECONDS,
423
        helper.getScheduledExecutorService());
1✔
424
  }
1✔
425

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

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

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

468
  private final class HealthListener implements SubchannelStateListener {
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
      subchannelData.healthStateInfo = newState;
1✔
476
      if (addressIndex.isValid()
1✔
477
          && subchannelData == subchannels.get(addressIndex.getCurrentAddress())) {
1✔
478
        updateHealthCheckedState(subchannelData);
1✔
479
      }
480
    }
1✔
481
  }
482

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

576
      return true;
1✔
577
    }
578

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

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

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

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

603
    /**
604
     * Update to new groups, resetting the current index.
605
     */
606
    public void updateGroups(List<EquivalentAddressGroup> newGroups) {
607
      addressGroups = checkNotNull(newGroups, "newGroups");
1✔
608
      reset();
1✔
609
      int size = 0;
1✔
610
      for (EquivalentAddressGroup eag : newGroups) {
1✔
611
        size += eag.getAddresses().size();
1✔
612
      }
1✔
613
      this.size = size;
1✔
614
    }
1✔
615

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

633
    public int size() {
634
      return size;
1✔
635
    }
636
  }
637

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

644
    public SubchannelData(Subchannel subchannel, ConnectivityState state) {
1✔
645
      this.subchannel = subchannel;
1✔
646
      this.state = state;
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 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