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

grpc / grpc-java / #19639

14 Jan 2025 12:38AM CUT coverage: 88.557% (+0.01%) from 88.547%
#19639

push

github

web-flow
core: Alternate ipV4 and ipV6 addresses for Happy Eyeballs in PickFirstLeafLoadBalancer  (#11624)

* Interweave ipV4 and ipV6 addresses as per gRFC.

33712 of 38068 relevant lines covered (88.56%)

0.89 hits per line

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

97.69
/../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.Inet4Address;
38
import java.net.InetSocketAddress;
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
final class PickFirstLeafLoadBalancer extends LoadBalancer {
60
  private static final Logger log = Logger.getLogger(PickFirstLeafLoadBalancer.class.getName());
1✔
61
  @VisibleForTesting
62
  static final int CONNECTION_DELAY_INTERVAL_MS = 250;
63
  private final boolean enableHappyEyeballs = !isSerializingRetries()
1✔
64
      && PickFirstLoadBalancerProvider.isEnabledHappyEyeballs();
1✔
65
  private final Helper helper;
66
  private final Map<SocketAddress, SubchannelData> subchannels = new HashMap<>();
1✔
67
  private final Index addressIndex = new Index(ImmutableList.of(), this.enableHappyEyeballs);
1✔
68
  private int numTf = 0;
1✔
69
  private boolean firstPass = true;
1✔
70
  @Nullable
1✔
71
  private ScheduledHandle scheduleConnectionTask = null;
72
  private ConnectivityState rawConnectivityState = IDLE;
1✔
73
  private ConnectivityState concludedState = IDLE;
1✔
74
  private boolean notAPetiolePolicy = true; // means not under a petiole policy
1✔
75
  private final BackoffPolicy.Provider bkoffPolProvider = new ExponentialBackoffPolicy.Provider();
1✔
76
  private BackoffPolicy reconnectPolicy;
77
  @Nullable
1✔
78
  private ScheduledHandle reconnectTask = null;
79
  private final boolean serializingRetries = isSerializingRetries();
1✔
80

81
  PickFirstLeafLoadBalancer(Helper helper) {
1✔
82
    this.helper = checkNotNull(helper, "helper");
1✔
83
  }
1✔
84

85
  static boolean isSerializingRetries() {
86
    return GrpcUtil.getFlag("GRPC_SERIALIZE_RETRIES", false);
1✔
87
  }
88

89
  @Override
90
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
91
    if (rawConnectivityState == SHUTDOWN) {
1✔
92
      return Status.FAILED_PRECONDITION.withDescription("Already shut down");
1✔
93
    }
94

95
    // Cache whether or not this is a petiole policy, which is based off of an address attribute
96
    Boolean isPetiolePolicy = resolvedAddresses.getAttributes().get(IS_PETIOLE_POLICY);
1✔
97
    this.notAPetiolePolicy = isPetiolePolicy == null || !isPetiolePolicy;
1✔
98

99
    List<EquivalentAddressGroup> servers = resolvedAddresses.getAddresses();
1✔
100

101
    // Validate the address list
102
    if (servers.isEmpty()) {
1✔
103
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
1✔
104
              "NameResolver returned no usable address. addrs=" + resolvedAddresses.getAddresses()
1✔
105
                      + ", attrs=" + resolvedAddresses.getAttributes());
1✔
106
      handleNameResolutionError(unavailableStatus);
1✔
107
      return unavailableStatus;
1✔
108
    }
109
    for (EquivalentAddressGroup eag : servers) {
1✔
110
      if (eag == null) {
1✔
111
        Status unavailableStatus = Status.UNAVAILABLE.withDescription(
1✔
112
            "NameResolver returned address list with null endpoint. addrs="
113
                + resolvedAddresses.getAddresses() + ", attrs="
1✔
114
                + resolvedAddresses.getAttributes());
1✔
115
        handleNameResolutionError(unavailableStatus);
1✔
116
        return unavailableStatus;
1✔
117
      }
118
    }
1✔
119

120
    // Since we have a new set of addresses, we are again at first pass
121
    firstPass = true;
1✔
122

123
    List<EquivalentAddressGroup> cleanServers = deDupAddresses(servers);
1✔
124

125
    // We can optionally be configured to shuffle the address list. This can help better distribute
126
    // the load.
127
    if (resolvedAddresses.getLoadBalancingPolicyConfig()
1✔
128
        instanceof PickFirstLeafLoadBalancerConfig) {
129
      PickFirstLeafLoadBalancerConfig config
1✔
130
          = (PickFirstLeafLoadBalancerConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
131
      if (config.shuffleAddressList != null && config.shuffleAddressList) {
1✔
132
        Collections.shuffle(cleanServers,
1✔
133
            config.randomSeed != null ? new Random(config.randomSeed) : new Random());
1✔
134
      }
135
    }
136

137
    final ImmutableList<EquivalentAddressGroup> newImmutableAddressGroups =
138
        ImmutableList.<EquivalentAddressGroup>builder().addAll(cleanServers).build();
1✔
139

140
    if (rawConnectivityState == READY) {
1✔
141
      // If the previous ready subchannel exists in new address list,
142
      // keep this connection and don't create new subchannels
143
      SocketAddress previousAddress = addressIndex.getCurrentAddress();
1✔
144
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
145
      if (addressIndex.seekTo(previousAddress)) {
1✔
146
        SubchannelData subchannelData = subchannels.get(previousAddress);
1✔
147
        subchannelData.getSubchannel().updateAddresses(addressIndex.getCurrentEagAsList());
1✔
148
        return Status.OK;
1✔
149
      }
150
      // Previous ready subchannel not in the new list of addresses
151
    } else {
1✔
152
      addressIndex.updateGroups(newImmutableAddressGroups);
1✔
153
    }
154

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

158
    // Flatten the new EAGs addresses
159
    Set<SocketAddress> newAddrs = new HashSet<>();
1✔
160
    for (EquivalentAddressGroup endpoint : newImmutableAddressGroups) {
1✔
161
      newAddrs.addAll(endpoint.getAddresses());
1✔
162
    }
1✔
163

164
    // Shut them down and remove them
165
    for (SocketAddress oldAddr : oldAddrs) {
1✔
166
      if (!newAddrs.contains(oldAddr)) {
1✔
167
        subchannels.remove(oldAddr).getSubchannel().shutdown();
1✔
168
      }
169
    }
1✔
170

171
    if (oldAddrs.size() == 0) {
1✔
172
      // Make tests happy; they don't properly assume starting in CONNECTING
173
      rawConnectivityState = CONNECTING;
1✔
174
      updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
175
    }
176

177
    if (rawConnectivityState == READY) {
1✔
178
      // connect from beginning when prompted
179
      rawConnectivityState = IDLE;
1✔
180
      updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
181

182
    } else if (rawConnectivityState == CONNECTING || rawConnectivityState == TRANSIENT_FAILURE) {
1✔
183
      // start connection attempt at first address
184
      cancelScheduleTask();
1✔
185
      requestConnection();
1✔
186
    }
187

188
    return Status.OK;
1✔
189
  }
190

191
  private static List<EquivalentAddressGroup> deDupAddresses(List<EquivalentAddressGroup> groups) {
192
    Set<SocketAddress> seenAddresses = new HashSet<>();
1✔
193
    List<EquivalentAddressGroup> newGroups = new ArrayList<>();
1✔
194

195
    for (EquivalentAddressGroup group : groups) {
1✔
196
      List<SocketAddress> addrs = new ArrayList<>();
1✔
197
      for (SocketAddress addr : group.getAddresses()) {
1✔
198
        if (seenAddresses.add(addr)) {
1✔
199
          addrs.add(addr);
1✔
200
        }
201
      }
1✔
202
      if (!addrs.isEmpty()) {
1✔
203
        newGroups.add(new EquivalentAddressGroup(addrs, group.getAttributes()));
1✔
204
      }
205
    }
1✔
206

207
    return newGroups;
1✔
208
  }
209

210
  @Override
211
  public void handleNameResolutionError(Status error) {
212
    if (rawConnectivityState == SHUTDOWN) {
1✔
213
      return;
×
214
    }
215

216
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
217
      subchannelData.getSubchannel().shutdown();
1✔
218
    }
1✔
219
    subchannels.clear();
1✔
220
    addressIndex.updateGroups(ImmutableList.of());
1✔
221
    rawConnectivityState = TRANSIENT_FAILURE;
1✔
222
    updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(error)));
1✔
223
  }
1✔
224

225
  void processSubchannelState(SubchannelData subchannelData, ConnectivityStateInfo stateInfo) {
226
    ConnectivityState newState = stateInfo.getState();
1✔
227

228
    // Shutdown channels/previously relevant subchannels can still callback with state updates.
229
    // To prevent pickers from returning these obsolete subchannels, this logic
230
    // is included to check if the current list of active subchannels includes this subchannel.
231
    if (subchannelData != subchannels.get(getAddress(subchannelData.subchannel))) {
1✔
232
      return;
1✔
233
    }
234

235
    if (newState == SHUTDOWN) {
1✔
236
      return;
1✔
237
    }
238

239
    if (newState == IDLE && subchannelData.state == READY) {
1✔
240
      helper.refreshNameResolution();
1✔
241
    }
242

243
    // If we are transitioning from a TRANSIENT_FAILURE to CONNECTING or IDLE we ignore this state
244
    // transition and still keep the LB in TRANSIENT_FAILURE state. This is referred to as "sticky
245
    // transient failure". Only a subchannel state change to READY will get the LB out of
246
    // TRANSIENT_FAILURE. If the state is IDLE we additionally request a new connection so that we
247
    // keep retrying for a connection.
248

249
    // With the new pick first implementation, individual subchannels will have their own backoff
250
    // on a per-address basis. Thus, iterative requests for connections will not be requested
251
    // once the first pass through is complete.
252
    // However, every time there is an address update, we will perform a pass through for the new
253
    // addresses in the updated list.
254
    subchannelData.updateState(newState);
1✔
255
    if (rawConnectivityState == TRANSIENT_FAILURE || concludedState == TRANSIENT_FAILURE)  {
1✔
256
      if (newState == CONNECTING) {
1✔
257
        // each subchannel is responsible for its own backoff
258
        return;
1✔
259
      } else if (newState == IDLE) {
1✔
260
        requestConnection();
1✔
261
        return;
1✔
262
      }
263
    }
264

265
    switch (newState) {
1✔
266
      case IDLE:
267
        // Shutdown when ready: connect from beginning when prompted
268
        addressIndex.reset();
1✔
269
        rawConnectivityState = IDLE;
1✔
270
        updateBalancingState(IDLE, new RequestConnectionPicker(this));
1✔
271
        break;
1✔
272

273
      case CONNECTING:
274
        rawConnectivityState = CONNECTING;
1✔
275
        updateBalancingState(CONNECTING, new Picker(PickResult.withNoResult()));
1✔
276
        break;
1✔
277

278
      case READY:
279
        shutdownRemaining(subchannelData);
1✔
280
        addressIndex.seekTo(getAddress(subchannelData.subchannel));
1✔
281
        rawConnectivityState = READY;
1✔
282
        updateHealthCheckedState(subchannelData);
1✔
283
        break;
1✔
284

285
      case TRANSIENT_FAILURE:
286
        // If we are looking at current channel, request a connection if possible
287
        if (addressIndex.isValid()
1✔
288
            && subchannels.get(addressIndex.getCurrentAddress()) == subchannelData) {
1✔
289
          if (addressIndex.increment()) {
1✔
290
            cancelScheduleTask();
1✔
291
            requestConnection(); // is recursive so might hit the end of the addresses
1✔
292
          } else {
293
            scheduleBackoff();
1✔
294
          }
295
        }
296

297
        if (isPassComplete()) {
1✔
298
          rawConnectivityState = TRANSIENT_FAILURE;
1✔
299
          updateBalancingState(TRANSIENT_FAILURE,
1✔
300
              new Picker(PickResult.withError(stateInfo.getStatus())));
1✔
301

302
          // Refresh Name Resolution, but only when all 3 conditions are met
303
          // * We are at the end of addressIndex
304
          // * have had status reported for all subchannels.
305
          // * And one of the following conditions:
306
          //    * Have had enough TF reported since we completed first pass
307
          //    * Just completed the first pass
308
          if (++numTf >= addressIndex.size() || firstPass) {
1✔
309
            firstPass = false;
1✔
310
            numTf = 0;
1✔
311
            helper.refreshNameResolution();
1✔
312
          }
313
        }
314
        break;
315

316
      default:
317
        throw new IllegalArgumentException("Unsupported state:" + newState);
×
318
    }
319
  }
1✔
320

321
  /**
322
   * Only called after all addresses attempted and failed (TRANSIENT_FAILURE).
323
   */
324
  private void scheduleBackoff() {
325
    if (!serializingRetries) {
1✔
326
      return;
1✔
327
    }
328

329
    class EndOfCurrentBackoff implements Runnable {
1✔
330
      @Override
331
      public void run() {
332
        reconnectTask = null;
1✔
333
        addressIndex.reset();
1✔
334
        requestConnection();
1✔
335
      }
1✔
336
    }
337

338
    // Just allow the previous one to trigger when ready if we're already in backoff
339
    if (reconnectTask != null) {
1✔
340
      return;
×
341
    }
342

343
    if (reconnectPolicy == null) {
1✔
344
      reconnectPolicy = bkoffPolProvider.get();
1✔
345
    }
346
    long delayNanos = reconnectPolicy.nextBackoffNanos();
1✔
347
    reconnectTask = helper.getSynchronizationContext().schedule(
1✔
348
        new EndOfCurrentBackoff(),
349
        delayNanos,
350
        TimeUnit.NANOSECONDS,
351
        helper.getScheduledExecutorService());
1✔
352
  }
1✔
353

354
  private void updateHealthCheckedState(SubchannelData subchannelData) {
355
    if (subchannelData.state != READY) {
1✔
356
      return;
1✔
357
    }
358

359
    if (notAPetiolePolicy || subchannelData.getHealthState() == READY) {
1✔
360
      updateBalancingState(READY,
1✔
361
          new FixedResultPicker(PickResult.withSubchannel(subchannelData.subchannel)));
1✔
362
    } else if (subchannelData.getHealthState() == TRANSIENT_FAILURE) {
1✔
363
      updateBalancingState(TRANSIENT_FAILURE, new Picker(PickResult.withError(
1✔
364
          subchannelData.healthStateInfo.getStatus())));
1✔
365
    } else if (concludedState != TRANSIENT_FAILURE) {
1✔
366
      updateBalancingState(subchannelData.getHealthState(),
1✔
367
          new Picker(PickResult.withNoResult()));
1✔
368
    }
369
  }
1✔
370

371
  private void updateBalancingState(ConnectivityState state, SubchannelPicker picker) {
372
    // an optimization: de-dup IDLE or CONNECTING notification.
373
    if (state == concludedState && (state == IDLE || state == CONNECTING)) {
1✔
374
      return;
1✔
375
    }
376
    concludedState = state;
1✔
377
    helper.updateBalancingState(state, picker);
1✔
378
  }
1✔
379

380
  @Override
381
  public void shutdown() {
382
    log.log(Level.FINE,
1✔
383
        "Shutting down, currently have {} subchannels created", subchannels.size());
1✔
384
    rawConnectivityState = SHUTDOWN;
1✔
385
    concludedState = SHUTDOWN;
1✔
386
    cancelScheduleTask();
1✔
387
    if (reconnectTask != null) {
1✔
388
      reconnectTask.cancel();
1✔
389
      reconnectTask = null;
1✔
390
    }
391
    reconnectPolicy = null;
1✔
392

393
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
394
      subchannelData.getSubchannel().shutdown();
1✔
395
    }
1✔
396

397
    subchannels.clear();
1✔
398
  }
1✔
399

400
  /**
401
  * Shuts down remaining subchannels. Called when a subchannel becomes ready, which means
402
  * that all other subchannels must be shutdown.
403
  */
404
  private void shutdownRemaining(SubchannelData activeSubchannelData) {
405
    if (reconnectTask != null) {
1✔
406
      reconnectTask.cancel();
1✔
407
      reconnectTask = null;
1✔
408
    }
409
    reconnectPolicy = null;
1✔
410

411
    cancelScheduleTask();
1✔
412
    for (SubchannelData subchannelData : subchannels.values()) {
1✔
413
      if (!subchannelData.getSubchannel().equals(activeSubchannelData.subchannel)) {
1✔
414
        subchannelData.getSubchannel().shutdown();
1✔
415
      }
416
    }
1✔
417
    subchannels.clear();
1✔
418
    activeSubchannelData.updateState(READY);
1✔
419
    subchannels.put(getAddress(activeSubchannelData.subchannel), activeSubchannelData);
1✔
420
  }
1✔
421

422
  /**
423
   * Requests a connection to the next applicable address' subchannel, creating one if necessary.
424
   * Schedules a connection to next address in list as well.
425
   * If the current channel has already attempted a connection, we attempt a connection
426
   * to the next address/subchannel in our list.  We assume that createNewSubchannel will never
427
   * return null.
428
   */
429
  @Override
430
  public void requestConnection() {
431
    if (!addressIndex.isValid() || rawConnectivityState == SHUTDOWN) {
1✔
432
      return;
1✔
433
    }
434

435
    SocketAddress currentAddress = addressIndex.getCurrentAddress();
1✔
436
    SubchannelData subchannelData = subchannels.get(currentAddress);
1✔
437
    if (subchannelData == null) {
1✔
438
      subchannelData = createNewSubchannel(currentAddress, addressIndex.getCurrentEagAttributes());
1✔
439
    }
440

441
    ConnectivityState subchannelState = subchannelData.getState();
1✔
442
    switch (subchannelState) {
1✔
443
      case IDLE:
444
        subchannelData.subchannel.requestConnection();
1✔
445
        subchannelData.updateState(CONNECTING);
1✔
446
        scheduleNextConnection();
1✔
447
        break;
1✔
448
      case CONNECTING:
449
        scheduleNextConnection();
1✔
450
        break;
1✔
451
      case TRANSIENT_FAILURE:
452
        if (!serializingRetries) {
1✔
453
          addressIndex.increment();
1✔
454
          requestConnection();
1✔
455
        } else {
456
          if (!addressIndex.isValid()) {
1✔
457
            scheduleBackoff();
×
458
          } else {
459
            subchannelData.subchannel.requestConnection();
1✔
460
            subchannelData.updateState(CONNECTING);
1✔
461
          }
462
        }
463
        break;
1✔
464
      default:
465
        // Wait for current subchannel to change state
466
    }
467
  }
1✔
468

469

470
  /**
471
  * Happy Eyeballs
472
  * Schedules connection attempt to happen after a delay to the next available address.
473
  */
474
  private void scheduleNextConnection() {
475
    if (!enableHappyEyeballs
1✔
476
        || (scheduleConnectionTask != null && scheduleConnectionTask.isPending())) {
1✔
477
      return;
1✔
478
    }
479

480
    class StartNextConnection implements Runnable {
1✔
481
      @Override
482
      public void run() {
483
        scheduleConnectionTask = null;
1✔
484
        if (addressIndex.increment()) {
1✔
485
          requestConnection();
1✔
486
        }
487
      }
1✔
488
    }
489

490
    scheduleConnectionTask = helper.getSynchronizationContext().schedule(
1✔
491
        new StartNextConnection(),
492
        CONNECTION_DELAY_INTERVAL_MS,
493
        TimeUnit.MILLISECONDS,
494
        helper.getScheduledExecutorService());
1✔
495
  }
1✔
496

497
  private void cancelScheduleTask() {
498
    if (scheduleConnectionTask != null) {
1✔
499
      scheduleConnectionTask.cancel();
1✔
500
      scheduleConnectionTask = null;
1✔
501
    }
502
  }
1✔
503

504
  private SubchannelData createNewSubchannel(SocketAddress addr, Attributes attrs) {
505
    HealthListener hcListener = new HealthListener();
1✔
506
    final Subchannel subchannel = helper.createSubchannel(
1✔
507
        CreateSubchannelArgs.newBuilder()
1✔
508
            .setAddresses(Lists.newArrayList(
1✔
509
                new EquivalentAddressGroup(addr, attrs)))
510
            .addOption(HEALTH_CONSUMER_LISTENER_ARG_KEY, hcListener)
1✔
511
            .addOption(LoadBalancer.DISABLE_SUBCHANNEL_RECONNECT_KEY, serializingRetries)
1✔
512
            .build());
1✔
513
    if (subchannel == null) {
1✔
514
      log.warning("Was not able to create subchannel for " + addr);
×
515
      throw new IllegalStateException("Can't create subchannel");
×
516
    }
517
    SubchannelData subchannelData = new SubchannelData(subchannel, IDLE);
1✔
518
    hcListener.subchannelData = subchannelData;
1✔
519
    subchannels.put(addr, subchannelData);
1✔
520
    Attributes scAttrs = subchannel.getAttributes();
1✔
521
    if (notAPetiolePolicy || scAttrs.get(LoadBalancer.HAS_HEALTH_PRODUCER_LISTENER_KEY) == null) {
1✔
522
      subchannelData.healthStateInfo = ConnectivityStateInfo.forNonError(READY);
1✔
523
    }
524
    subchannel.start(stateInfo -> processSubchannelState(subchannelData, stateInfo));
1✔
525
    return subchannelData;
1✔
526
  }
527

528
  private boolean isPassComplete() {
529
    if (subchannels.size() < addressIndex.size()) {
1✔
530
      return false;
1✔
531
    }
532
    for (SubchannelData sc : subchannels.values()) {
1✔
533
      if (!sc.isCompletedConnectivityAttempt() ) {
1✔
534
        return false;
1✔
535
      }
536
    }
1✔
537
    return true;
1✔
538
  }
539

540
  private final class HealthListener implements SubchannelStateListener {
1✔
541
    private SubchannelData subchannelData;
542

543
    @Override
544
    public void onSubchannelState(ConnectivityStateInfo newState) {
545
      if (notAPetiolePolicy) {
1✔
546
        log.log(Level.WARNING,
1✔
547
            "Ignoring health status {0} for subchannel {1} as this is not under a petiole policy",
548
            new Object[]{newState, subchannelData.subchannel});
1✔
549
        return;
1✔
550
      }
551

552
      log.log(Level.FINE, "Received health status {0} for subchannel {1}",
1✔
553
          new Object[]{newState, subchannelData.subchannel});
1✔
554
      subchannelData.healthStateInfo = newState;
1✔
555
      if (addressIndex.isValid()
1✔
556
          && subchannelData == subchannels.get(addressIndex.getCurrentAddress())) {
1✔
557
        updateHealthCheckedState(subchannelData);
1✔
558
      }
559
    }
1✔
560
  }
561

562
  private SocketAddress getAddress(Subchannel subchannel) {
563
    return subchannel.getAddresses().getAddresses().get(0);
1✔
564
  }
565

566
  @VisibleForTesting
567
  ConnectivityState getConcludedConnectivityState() {
568
    return this.concludedState;
1✔
569
  }
570

571
  /**
572
   * No-op picker which doesn't add any custom picking logic. It just passes already known result
573
   * received in constructor.
574
   */
575
  private static final class Picker extends SubchannelPicker {
576
    private final PickResult result;
577

578
    Picker(PickResult result) {
1✔
579
      this.result = checkNotNull(result, "result");
1✔
580
    }
1✔
581

582
    @Override
583
    public PickResult pickSubchannel(PickSubchannelArgs args) {
584
      return result;
1✔
585
    }
586

587
    @Override
588
    public String toString() {
589
      return MoreObjects.toStringHelper(Picker.class).add("result", result).toString();
×
590
    }
591
  }
592

593
  /**
594
   * Picker that requests connection during the first pick, and returns noResult.
595
   */
596
  private final class RequestConnectionPicker extends SubchannelPicker {
597
    private final PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer;
598
    private final AtomicBoolean connectionRequested = new AtomicBoolean(false);
1✔
599

600
    RequestConnectionPicker(PickFirstLeafLoadBalancer pickFirstLeafLoadBalancer) {
1✔
601
      this.pickFirstLeafLoadBalancer =
1✔
602
          checkNotNull(pickFirstLeafLoadBalancer, "pickFirstLeafLoadBalancer");
1✔
603
    }
1✔
604

605
    @Override
606
    public PickResult pickSubchannel(PickSubchannelArgs args) {
607
      if (connectionRequested.compareAndSet(false, true)) {
1✔
608
        helper.getSynchronizationContext().execute(pickFirstLeafLoadBalancer::requestConnection);
1✔
609
      }
610
      return PickResult.withNoResult();
1✔
611
    }
612
  }
613

614
  /**
615
   * This contains both an ordered list of addresses and a pointer(i.e. index) to the current entry.
616
   * All updates should be done in a synchronization context.
617
   */
618
  @VisibleForTesting
619
  static final class Index {
620
    private List<UnwrappedEag> orderedAddresses;
621
    private int activeElement = 0;
1✔
622
    private boolean enableHappyEyeballs;
623

624
    Index(List<EquivalentAddressGroup> groups, boolean enableHappyEyeballs) {
1✔
625
      this.enableHappyEyeballs = enableHappyEyeballs;
1✔
626
      updateGroups(groups);
1✔
627
    }
1✔
628

629
    public boolean isValid() {
630
      return activeElement < orderedAddresses.size();
1✔
631
    }
632

633
    public boolean isAtBeginning() {
634
      return activeElement == 0;
1✔
635
    }
636

637
    /**
638
     * Move to next address in group.  If last address in group move to first address of next group.
639
     * @return false if went off end of the list, otherwise true
640
     */
641
    public boolean increment() {
642
      if (!isValid()) {
1✔
643
        return false;
1✔
644
      }
645

646
      activeElement++;
1✔
647

648
      return isValid();
1✔
649
    }
650

651
    public void reset() {
652
      activeElement = 0;
1✔
653
    }
1✔
654

655
    public SocketAddress getCurrentAddress() {
656
      if (!isValid()) {
1✔
657
        throw new IllegalStateException("Index is past the end of the address group list");
1✔
658
      }
659
      return orderedAddresses.get(activeElement).address;
1✔
660
    }
661

662
    public Attributes getCurrentEagAttributes() {
663
      if (!isValid()) {
1✔
664
        throw new IllegalStateException("Index is off the end of the address group list");
×
665
      }
666
      return orderedAddresses.get(activeElement).attributes;
1✔
667
    }
668

669
    public List<EquivalentAddressGroup> getCurrentEagAsList() {
670
      return Collections.singletonList(getCurrentEag());
1✔
671
    }
672

673
    private EquivalentAddressGroup getCurrentEag() {
674
      if (!isValid()) {
1✔
675
        throw new IllegalStateException("Index is past the end of the address group list");
×
676
      }
677
      return orderedAddresses.get(activeElement).asEag();
1✔
678
    }
679

680
    /**
681
     * Update to new groups, resetting the current index.
682
     */
683
    public void updateGroups(List<EquivalentAddressGroup> newGroups) {
684
      checkNotNull(newGroups, "newGroups");
1✔
685
      orderedAddresses = enableHappyEyeballs
1✔
686
                             ? updateGroupsHE(newGroups)
1✔
687
                             : updateGroupsNonHE(newGroups);
1✔
688
      reset();
1✔
689
    }
1✔
690

691
    /**
692
     * Returns false if the needle was not found and the current index was left unchanged.
693
     */
694
    public boolean seekTo(SocketAddress needle) {
695
      checkNotNull(needle, "needle");
1✔
696
      for (int i = 0; i < orderedAddresses.size(); i++) {
1✔
697
        if (orderedAddresses.get(i).address.equals(needle)) {
1✔
698
          this.activeElement = i;
1✔
699
          return true;
1✔
700
        }
701
      }
702
      return false;
1✔
703
    }
704

705
    public int size() {
706
      return orderedAddresses.size();
1✔
707
    }
708

709
    private List<UnwrappedEag> updateGroupsNonHE(List<EquivalentAddressGroup> newGroups) {
710
      List<UnwrappedEag> entries = new ArrayList<>();
1✔
711
      for (int g = 0; g < newGroups.size(); g++) {
1✔
712
        EquivalentAddressGroup eag = newGroups.get(g);
1✔
713
        for (int a = 0; a < eag.getAddresses().size(); a++) {
1✔
714
          SocketAddress addr = eag.getAddresses().get(a);
1✔
715
          entries.add(new UnwrappedEag(eag.getAttributes(), addr));
1✔
716
        }
717
      }
718

719
      return entries;
1✔
720
    }
721

722
    private List<UnwrappedEag> updateGroupsHE(List<EquivalentAddressGroup> newGroups) {
723
      Boolean firstIsV6 = null;
1✔
724
      List<UnwrappedEag> v4Entries = new ArrayList<>();
1✔
725
      List<UnwrappedEag> v6Entries = new ArrayList<>();
1✔
726
      for (int g = 0; g <  newGroups.size(); g++) {
1✔
727
        EquivalentAddressGroup eag = newGroups.get(g);
1✔
728
        for (int a = 0; a < eag.getAddresses().size(); a++) {
1✔
729
          SocketAddress addr = eag.getAddresses().get(a);
1✔
730
          boolean isIpV4 = addr instanceof InetSocketAddress
1✔
731
              && ((InetSocketAddress) addr).getAddress() instanceof Inet4Address;
1✔
732
          if (isIpV4) {
1✔
733
            if (firstIsV6 == null) {
1✔
734
              firstIsV6 = false;
1✔
735
            }
736
            v4Entries.add(new UnwrappedEag(eag.getAttributes(), addr));
1✔
737
          } else {
738
            if (firstIsV6 == null) {
1✔
739
              firstIsV6 = true;
1✔
740
            }
741
            v6Entries.add(new UnwrappedEag(eag.getAttributes(), addr));
1✔
742
          }
743
        }
744
      }
745

746
      return firstIsV6 != null && firstIsV6
1✔
747
          ? interleave(v6Entries, v4Entries)
1✔
748
          : interleave(v4Entries, v6Entries);
1✔
749
    }
750

751
    private List<UnwrappedEag> interleave(List<UnwrappedEag> firstFamily,
752
                                          List<UnwrappedEag> secondFamily) {
753
      if (firstFamily.isEmpty()) {
1✔
754
        return secondFamily;
1✔
755
      }
756
      if (secondFamily.isEmpty()) {
1✔
757
        return firstFamily;
1✔
758
      }
759

760
      List<UnwrappedEag> result = new ArrayList<>(firstFamily.size() + secondFamily.size());
1✔
761
      for (int i = 0; i < Math.max(firstFamily.size(), secondFamily.size()); i++) {
1✔
762
        if (i < firstFamily.size()) {
1✔
763
          result.add(firstFamily.get(i));
1✔
764
        }
765
        if (i < secondFamily.size()) {
1✔
766
          result.add(secondFamily.get(i));
1✔
767
        }
768
      }
769
      return result;
1✔
770
    }
771

772
    private static final class UnwrappedEag {
773
      private final Attributes attributes;
774
      private final SocketAddress address;
775

776
      public UnwrappedEag(Attributes attributes, SocketAddress address) {
1✔
777
        this.attributes = attributes;
1✔
778
        this.address = address;
1✔
779
      }
1✔
780

781
      private EquivalentAddressGroup asEag() {
782
        return new EquivalentAddressGroup(address, attributes);
1✔
783
      }
784
    }
785
  }
786

787
  @VisibleForTesting
788
  int getIndexLocation() {
789
    return addressIndex.activeElement;
1✔
790
  }
791

792
  @VisibleForTesting
793
  boolean isIndexValid() {
794
    return addressIndex.isValid();
1✔
795
  }
796

797
  private static final class SubchannelData {
798
    private final Subchannel subchannel;
799
    private ConnectivityState state;
800
    private boolean completedConnectivityAttempt = false;
1✔
801
    private ConnectivityStateInfo healthStateInfo = ConnectivityStateInfo.forNonError(IDLE);
1✔
802

803
    public SubchannelData(Subchannel subchannel, ConnectivityState state) {
1✔
804
      this.subchannel = subchannel;
1✔
805
      this.state = state;
1✔
806
    }
1✔
807

808
    public Subchannel getSubchannel() {
809
      return this.subchannel;
1✔
810
    }
811

812
    public ConnectivityState getState() {
813
      return this.state;
1✔
814
    }
815

816
    public boolean isCompletedConnectivityAttempt() {
817
      return completedConnectivityAttempt;
1✔
818
    }
819

820
    private void updateState(ConnectivityState newState) {
821
      this.state = newState;
1✔
822
      if (newState == READY || newState == TRANSIENT_FAILURE) {
1✔
823
        completedConnectivityAttempt = true;
1✔
824
      } else if (newState == IDLE) {
1✔
825
        completedConnectivityAttempt = false;
1✔
826
      }
827
    }
1✔
828

829
    private ConnectivityState getHealthState() {
830
      return healthStateInfo.getState();
1✔
831
    }
832
  }
833

834
  public static final class PickFirstLeafLoadBalancerConfig {
835

836
    @Nullable
837
    public final Boolean shuffleAddressList;
838

839
    // For testing purposes only, not meant to be parsed from a real config.
840
    @Nullable
841
    final Long randomSeed;
842

843
    public PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList) {
844
      this(shuffleAddressList, null);
1✔
845
    }
1✔
846

847
    PickFirstLeafLoadBalancerConfig(@Nullable Boolean shuffleAddressList,
848
        @Nullable Long randomSeed) {
1✔
849
      this.shuffleAddressList = shuffleAddressList;
1✔
850
      this.randomSeed = randomSeed;
1✔
851
    }
1✔
852
  }
853

854
}
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