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

grpc / grpc-java / #20220

25 Mar 2026 06:04AM UTC coverage: 88.693%. Remained the same
#20220

push

github

web-flow
api: Deprecate LoadBalancer.handleResolvedAddresses() (#11623)

Also deprecate its companion
canHandleEmptyAddressListFromNameResolution().
Also fixup the Javadoc to align with the arguments/return values, so
that people would have a better idea of how to use it.

Fixes #11194

---------

Co-authored-by: MV Shiva Prasad <okshiva@google.com>
Co-authored-by: Eric Anderson <ejona@google.com>

35486 of 40010 relevant lines covered (88.69%)

0.89 hits per line

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

95.26
/../xds/src/main/java/io/grpc/xds/ClusterImplLoadBalancer.java
1
/*
2
 * Copyright 2020 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.xds;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20
import static io.grpc.xds.client.LoadStatsManager2.isEnabledOrcaLrsPropagation;
21

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.MoreObjects;
24
import com.google.common.base.Strings;
25
import com.google.common.collect.ImmutableMap;
26
import com.google.protobuf.Struct;
27
import io.grpc.Attributes;
28
import io.grpc.ClientStreamTracer;
29
import io.grpc.ClientStreamTracer.StreamInfo;
30
import io.grpc.ConnectivityState;
31
import io.grpc.ConnectivityStateInfo;
32
import io.grpc.EquivalentAddressGroup;
33
import io.grpc.InternalLogId;
34
import io.grpc.LoadBalancer;
35
import io.grpc.Metadata;
36
import io.grpc.NameResolver;
37
import io.grpc.Status;
38
import io.grpc.internal.ForwardingClientStreamTracer;
39
import io.grpc.internal.GrpcUtil;
40
import io.grpc.services.MetricReport;
41
import io.grpc.util.ForwardingLoadBalancerHelper;
42
import io.grpc.util.ForwardingSubchannel;
43
import io.grpc.util.GracefulSwitchLoadBalancer;
44
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
45
import io.grpc.xds.Endpoints.DropOverload;
46
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
47
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
48
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
49
import io.grpc.xds.client.BackendMetricPropagation;
50
import io.grpc.xds.client.Bootstrapper.ServerInfo;
51
import io.grpc.xds.client.LoadStatsManager2.ClusterDropStats;
52
import io.grpc.xds.client.LoadStatsManager2.ClusterLocalityStats;
53
import io.grpc.xds.client.Locality;
54
import io.grpc.xds.client.XdsClient;
55
import io.grpc.xds.client.XdsLogger;
56
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
57
import io.grpc.xds.internal.XdsInternalAttributes;
58
import io.grpc.xds.internal.security.SecurityProtocolNegotiators;
59
import io.grpc.xds.internal.security.SslContextProviderSupplier;
60
import io.grpc.xds.orca.OrcaPerRequestUtil;
61
import io.grpc.xds.orca.OrcaPerRequestUtil.OrcaPerRequestReportListener;
62
import java.util.ArrayList;
63
import java.util.Collections;
64
import java.util.List;
65
import java.util.Locale;
66
import java.util.Map;
67
import java.util.Objects;
68
import java.util.concurrent.atomic.AtomicLong;
69
import java.util.concurrent.atomic.AtomicReference;
70
import javax.annotation.Nullable;
71

72
/**
73
 * Load balancer for cluster_impl_experimental LB policy. This LB policy is the child LB policy of
74
 * the priority_experimental LB policy and the parent LB policy of the weighted_target_experimental
75
 * LB policy in the xDS load balancing hierarchy. This LB policy applies cluster-level
76
 * configurations to requests sent to the corresponding cluster, such as drop policies, circuit
77
 * breakers.
78
 */
79
final class ClusterImplLoadBalancer extends LoadBalancer {
80

81
  @VisibleForTesting
82
  static final long DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS = 1024L;
83
  @VisibleForTesting
84
  static boolean enableCircuitBreaking =
1✔
85
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"))
1✔
86
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_CIRCUIT_BREAKING"));
1✔
87

88
  private static final Attributes.Key<AtomicReference<ClusterLocality>> ATTR_CLUSTER_LOCALITY =
1✔
89
      Attributes.Key.create("io.grpc.xds.ClusterImplLoadBalancer.clusterLocality");
1✔
90
  @VisibleForTesting
91
  static final Attributes.Key<String> ATTR_SUBCHANNEL_ADDRESS_NAME =
1✔
92
      Attributes.Key.create("io.grpc.xds.ClusterImplLoadBalancer.addressName");
1✔
93

94
  private final XdsLogger logger;
95
  private final Helper helper;
96
  private final ThreadSafeRandom random;
97
  // The following fields are effectively final.
98
  private String cluster;
99
  @Nullable
100
  private String edsServiceName;
101
  private XdsClient xdsClient;
102
  private CallCounterProvider callCounterProvider;
103
  private ClusterDropStats dropStats;
104
  private ClusterImplLbHelper childLbHelper;
105
  private GracefulSwitchLoadBalancer childSwitchLb;
106

107
  ClusterImplLoadBalancer(Helper helper) {
108
    this(helper, ThreadSafeRandomImpl.instance);
1✔
109
  }
1✔
110

111
  ClusterImplLoadBalancer(Helper helper, ThreadSafeRandom random) {
1✔
112
    this.helper = checkNotNull(helper, "helper");
1✔
113
    this.random = checkNotNull(random, "random");
1✔
114
    InternalLogId logId = InternalLogId.allocate("cluster-impl-lb", helper.getAuthority());
1✔
115
    logger = XdsLogger.withLogId(logId);
1✔
116
    logger.log(XdsLogLevel.INFO, "Created");
1✔
117
  }
1✔
118

119
  @Override
120
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
121
    logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
1✔
122
    Attributes attributes = resolvedAddresses.getAttributes();
1✔
123
    if (xdsClient == null) {
1✔
124
      xdsClient = checkNotNull(attributes.get(io.grpc.xds.XdsAttributes.XDS_CLIENT), "xdsClient");
1✔
125
    }
126
    if (callCounterProvider == null) {
1✔
127
      callCounterProvider = attributes.get(io.grpc.xds.XdsAttributes.CALL_COUNTER_PROVIDER);
1✔
128
    }
129

130
    ClusterImplConfig config =
1✔
131
        (ClusterImplConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
132
    if (config == null) {
1✔
133
      return Status.INTERNAL.withDescription("No cluster configuration found");
×
134
    }
135

136
    if (cluster == null) {
1✔
137
      cluster = config.cluster;
1✔
138
      edsServiceName = config.edsServiceName;
1✔
139
      childLbHelper = new ClusterImplLbHelper(
1✔
140
          callCounterProvider.getOrCreate(config.cluster, config.edsServiceName),
1✔
141
          config.lrsServerInfo);
142
      childSwitchLb = new GracefulSwitchLoadBalancer(childLbHelper);
1✔
143
      // Assume load report server does not change throughout cluster lifetime.
144
      if (config.lrsServerInfo != null) {
1✔
145
        dropStats = xdsClient.addClusterDropStats(config.lrsServerInfo, cluster, edsServiceName);
1✔
146
      }
147
    }
148

149
    childLbHelper.updateDropPolicies(config.dropCategories);
1✔
150
    childLbHelper.updateMaxConcurrentRequests(config.maxConcurrentRequests);
1✔
151
    childLbHelper.updateSslContextProviderSupplier(config.tlsContext);
1✔
152
    childLbHelper.updateFilterMetadata(config.filterMetadata);
1✔
153
    childLbHelper.updateBackendMetricPropagation(config.backendMetricPropagation);
1✔
154

155
    return childSwitchLb.acceptResolvedAddresses(
1✔
156
        resolvedAddresses.toBuilder()
1✔
157
            .setAttributes(attributes.toBuilder()
1✔
158
              .set(NameResolver.ATTR_BACKEND_SERVICE, cluster)
1✔
159
              .build())
1✔
160
            .setLoadBalancingPolicyConfig(config.childConfig)
1✔
161
            .build());
1✔
162
  }
163

164
  @Override
165
  public void handleNameResolutionError(Status error) {
166
    if (childSwitchLb != null) {
1✔
167
      childSwitchLb.handleNameResolutionError(error);
1✔
168
    } else {
169
      helper.updateBalancingState(
1✔
170
          ConnectivityState.TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(error)));
1✔
171
    }
172
  }
1✔
173

174
  @Override
175
  public void requestConnection() {
176
    if (childSwitchLb != null) {
1✔
177
      childSwitchLb.requestConnection();
1✔
178
    }
179
  }
1✔
180

181
  @Override
182
  public void shutdown() {
183
    if (dropStats != null) {
1✔
184
      dropStats.release();
1✔
185
    }
186
    if (childSwitchLb != null) {
1✔
187
      childSwitchLb.shutdown();
1✔
188
      if (childLbHelper != null) {
1✔
189
        childLbHelper.updateSslContextProviderSupplier(null);
1✔
190
        childLbHelper = null;
1✔
191
      }
192
    }
193
    xdsClient = null;
1✔
194
  }
1✔
195

196
  /**
197
   * A decorated {@link LoadBalancer.Helper} that applies configurations for connections
198
   * or requests to endpoints in the cluster.
199
   */
200
  private final class ClusterImplLbHelper extends ForwardingLoadBalancerHelper {
201
    private final AtomicLong inFlights;
202
    private ConnectivityState currentState = ConnectivityState.IDLE;
1✔
203
    private SubchannelPicker currentPicker = new FixedResultPicker(PickResult.withNoResult());
1✔
204
    private List<DropOverload> dropPolicies = Collections.emptyList();
1✔
205
    private long maxConcurrentRequests = DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
206
    @Nullable
207
    private SslContextProviderSupplier sslContextProviderSupplier;
208
    private Map<String, Struct> filterMetadata = ImmutableMap.of();
1✔
209
    @Nullable
210
    private final ServerInfo lrsServerInfo;
211
    @Nullable
212
    private BackendMetricPropagation backendMetricPropagation;
213

214
    private ClusterImplLbHelper(AtomicLong inFlights, @Nullable ServerInfo lrsServerInfo) {
1✔
215
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
216
      this.lrsServerInfo = lrsServerInfo;
1✔
217
    }
1✔
218

219
    @Override
220
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
221
      currentState = newState;
1✔
222
      currentPicker =  newPicker;
1✔
223
      SubchannelPicker picker = new RequestLimitingSubchannelPicker(
1✔
224
          newPicker, dropPolicies, maxConcurrentRequests, filterMetadata);
225
      delegate().updateBalancingState(newState, picker);
1✔
226
    }
1✔
227

228
    @Override
229
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
230
      List<EquivalentAddressGroup> addresses = withAdditionalAttributes(args.getAddresses());
1✔
231
      // This value for  ClusterLocality is not recommended for general use.
232
      // Currently, we extract locality data from the first address, even before the subchannel is
233
      // READY.
234
      // This is mainly to accommodate scenarios where a Load Balancing API (like "pick first")
235
      // might return the subchannel before it is READY. Typically, we wouldn't report load for such
236
      // selections because the channel will disregard the chosen (not-ready) subchannel.
237
      // However, we needed to ensure this case is handled.
238
      ClusterLocality clusterLocality = createClusterLocalityFromAttributes(
1✔
239
          args.getAddresses().get(0).getAttributes());
1✔
240
      AtomicReference<ClusterLocality> localityAtomicReference = new AtomicReference<>(
1✔
241
          clusterLocality);
242
      Attributes.Builder attrsBuilder = args.getAttributes().toBuilder()
1✔
243
          .set(ATTR_CLUSTER_LOCALITY, localityAtomicReference);
1✔
244
      if (GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE", false)) {
1✔
245
        String hostname = args.getAddresses().get(0).getAttributes()
1✔
246
            .get(XdsInternalAttributes.ATTR_ADDRESS_NAME);
1✔
247
        if (hostname != null) {
1✔
248
          attrsBuilder.set(ATTR_SUBCHANNEL_ADDRESS_NAME, hostname);
1✔
249
        }
250
      }
251
      args = args.toBuilder().setAddresses(addresses).setAttributes(attrsBuilder.build()).build();
1✔
252
      final Subchannel subchannel = delegate().createSubchannel(args);
1✔
253

254
      return new ClusterImplSubchannel(subchannel, localityAtomicReference);
1✔
255
    }
256

257
    private final class ClusterImplSubchannel extends ForwardingSubchannel {
258
      private final Subchannel delegate;
259
      private final AtomicReference<ClusterLocality> localityAtomicReference;
260

261
      private ClusterImplSubchannel(
262
          Subchannel delegate, AtomicReference<ClusterLocality> localityAtomicReference) {
1✔
263
        this.delegate = delegate;
1✔
264
        this.localityAtomicReference = localityAtomicReference;
1✔
265
      }
1✔
266

267
      @Override
268
      public void start(SubchannelStateListener listener) {
269
        delegate().start(
1✔
270
            new SubchannelStateListener() {
1✔
271
              @Override
272
              public void onSubchannelState(ConnectivityStateInfo newState) {
273
                // Do nothing if LB has been shutdown
274
                if (xdsClient != null && newState.getState().equals(ConnectivityState.READY)) {
1✔
275
                  // Get locality based on the connected address attributes
276
                  ClusterLocality updatedClusterLocality =
1✔
277
                      createClusterLocalityFromAttributes(
1✔
278
                          delegate.getConnectedAddressAttributes());
1✔
279
                  ClusterLocality oldClusterLocality =
1✔
280
                      localityAtomicReference.getAndSet(updatedClusterLocality);
1✔
281
                  oldClusterLocality.release();
1✔
282
                }
283
                listener.onSubchannelState(newState);
1✔
284
              }
1✔
285
            });
286
      }
1✔
287

288
      @Override
289
      public void shutdown() {
290
        localityAtomicReference.get().release();
1✔
291
        delegate().shutdown();
1✔
292
      }
1✔
293

294
      @Override
295
      public void updateAddresses(List<EquivalentAddressGroup> addresses) {
296
        delegate().updateAddresses(withAdditionalAttributes(addresses));
1✔
297
      }
1✔
298

299
      @Override
300
      protected Subchannel delegate() {
301
        return delegate;
1✔
302
      }
303
    }
304

305
    private List<EquivalentAddressGroup> withAdditionalAttributes(
306
        List<EquivalentAddressGroup> addresses) {
307
      List<EquivalentAddressGroup> newAddresses = new ArrayList<>();
1✔
308
      for (EquivalentAddressGroup eag : addresses) {
1✔
309
        Attributes.Builder attrBuilder = eag.getAttributes().toBuilder().set(
1✔
310
            io.grpc.xds.XdsAttributes.ATTR_CLUSTER_NAME, cluster);
1✔
311
        if (sslContextProviderSupplier != null) {
1✔
312
          attrBuilder.set(
1✔
313
              SecurityProtocolNegotiators.ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER,
314
              sslContextProviderSupplier);
315
        }
316
        newAddresses.add(new EquivalentAddressGroup(eag.getAddresses(), attrBuilder.build()));
1✔
317
      }
1✔
318
      return newAddresses;
1✔
319
    }
320

321
    private ClusterLocality createClusterLocalityFromAttributes(Attributes addressAttributes) {
322
      Locality locality = addressAttributes.get(io.grpc.xds.XdsAttributes.ATTR_LOCALITY);
1✔
323
      String localityName = addressAttributes.get(EquivalentAddressGroup.ATTR_LOCALITY_NAME);
1✔
324

325
      // Endpoint addresses resolved by ClusterResolverLoadBalancer should always contain
326
      // attributes with its locality, including endpoints in LOGICAL_DNS clusters.
327
      // In case of not (which really shouldn't), loads are aggregated under an empty
328
      // locality.
329
      if (locality == null) {
1✔
330
        locality = Locality.create("", "", "");
×
331
        localityName = "";
×
332
      }
333

334
      final ClusterLocalityStats localityStats =
335
          (lrsServerInfo == null)
1✔
336
              ? null
1✔
337
              : xdsClient.addClusterLocalityStats(lrsServerInfo, cluster,
1✔
338
                  edsServiceName, locality, backendMetricPropagation);
1✔
339

340
      return new ClusterLocality(localityStats, localityName);
1✔
341
    }
342

343
    @Override
344
    protected Helper delegate()  {
345
      return helper;
1✔
346
    }
347

348
    private void updateDropPolicies(List<DropOverload> dropOverloads) {
349
      if (!dropPolicies.equals(dropOverloads)) {
1✔
350
        dropPolicies = dropOverloads;
1✔
351
        updateBalancingState(currentState, currentPicker);
1✔
352
      }
353
    }
1✔
354

355
    private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
356
      if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
1✔
357
        return;
×
358
      }
359
      this.maxConcurrentRequests =
1✔
360
          maxConcurrentRequests != null
1✔
361
              ? maxConcurrentRequests
1✔
362
              : DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
363
      updateBalancingState(currentState, currentPicker);
1✔
364
    }
1✔
365

366
    private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
367
      UpstreamTlsContext currentTlsContext =
368
          sslContextProviderSupplier != null
1✔
369
              ? (UpstreamTlsContext)sslContextProviderSupplier.getTlsContext()
1✔
370
              : null;
1✔
371
      if (Objects.equals(currentTlsContext,  tlsContext)) {
1✔
372
        return;
1✔
373
      }
374
      if (sslContextProviderSupplier != null) {
1✔
375
        sslContextProviderSupplier.close();
1✔
376
      }
377
      sslContextProviderSupplier =
1✔
378
          tlsContext != null
1✔
379
              ? new SslContextProviderSupplier(tlsContext,
1✔
380
                                               (TlsContextManager) xdsClient.getSecurityConfig())
1✔
381
              : null;
1✔
382
    }
1✔
383

384
    private void updateFilterMetadata(Map<String, Struct> filterMetadata) {
385
      this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
386
    }
1✔
387

388
    private void updateBackendMetricPropagation(
389
        @Nullable BackendMetricPropagation backendMetricPropagation) {
390
      this.backendMetricPropagation = backendMetricPropagation;
1✔
391
    }
1✔
392

393
    private class RequestLimitingSubchannelPicker extends SubchannelPicker {
394
      private final SubchannelPicker delegate;
395
      private final List<DropOverload> dropPolicies;
396
      private final long maxConcurrentRequests;
397
      private final Map<String, Struct> filterMetadata;
398

399
      private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
400
          List<DropOverload> dropPolicies, long maxConcurrentRequests,
401
          Map<String, Struct> filterMetadata) {
1✔
402
        this.delegate = delegate;
1✔
403
        this.dropPolicies = dropPolicies;
1✔
404
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
405
        this.filterMetadata = checkNotNull(filterMetadata, "filterMetadata");
1✔
406
      }
1✔
407

408
      @Override
409
      public PickResult pickSubchannel(PickSubchannelArgs args) {
410
        args.getCallOptions().getOption(ClusterImplLoadBalancerProvider.FILTER_METADATA_CONSUMER)
1✔
411
            .accept(filterMetadata);
1✔
412
        args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.backend_service", cluster);
1✔
413
        for (DropOverload dropOverload : dropPolicies) {
1✔
414
          int rand = random.nextInt(1_000_000);
1✔
415
          if (rand < dropOverload.dropsPerMillion()) {
1✔
416
            logger.log(XdsLogLevel.INFO, "Drop request with category: {0}",
1✔
417
                dropOverload.category());
1✔
418
            if (dropStats != null) {
1✔
419
              dropStats.recordDroppedRequest(dropOverload.category());
1✔
420
            }
421
            return PickResult.withDrop(
1✔
422
                Status.UNAVAILABLE.withDescription("Dropped: " + dropOverload.category()));
1✔
423
          }
424
        }
1✔
425
        PickResult result = delegate.pickSubchannel(args);
1✔
426
        if (result.getStatus().isOk() && result.getSubchannel() != null) {
1✔
427
          Subchannel subchannel = result.getSubchannel();
1✔
428
          if (subchannel instanceof ClusterImplLbHelper.ClusterImplSubchannel) {
1✔
429
            subchannel = ((ClusterImplLbHelper.ClusterImplSubchannel) subchannel).delegate();
1✔
430
            result = result.copyWithSubchannel(subchannel);
1✔
431
          }
432
          if (enableCircuitBreaking) {
1✔
433
            if (inFlights.get() >= maxConcurrentRequests) {
1✔
434
              if (dropStats != null) {
1✔
435
                dropStats.recordDroppedRequest();
1✔
436
              }
437
              return PickResult.withDrop(Status.UNAVAILABLE.withDescription(
1✔
438
                  String.format(Locale.US, "Cluster max concurrent requests limit of %d exceeded",
1✔
439
                      maxConcurrentRequests)));
1✔
440
            }
441
          }
442
          final AtomicReference<ClusterLocality> clusterLocality =
1✔
443
              result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY);
1✔
444

445
          if (clusterLocality != null) {
1✔
446
            ClusterLocalityStats stats = clusterLocality.get().getClusterLocalityStats();
1✔
447
            if (stats != null) {
1✔
448
              String localityName =
1✔
449
                  result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY).get()
1✔
450
                      .getClusterLocalityName();
1✔
451
              args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.locality", localityName);
1✔
452

453
              ClientStreamTracer.Factory tracerFactory = new CountingStreamTracerFactory(
1✔
454
                  stats, inFlights, result.getStreamTracerFactory());
1✔
455
              ClientStreamTracer.Factory orcaTracerFactory = OrcaPerRequestUtil.getInstance()
1✔
456
                  .newOrcaClientStreamTracerFactory(tracerFactory, new OrcaPerRpcListener(stats));
1✔
457
              result = result.copyWithStreamTracerFactory(orcaTracerFactory);
1✔
458
            }
459
          }
460
          if (args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY) != null
1✔
461
              && args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY)) {
1✔
462
            result = PickResult.withSubchannel(result.getSubchannel(),
1✔
463
                result.getStreamTracerFactory(),
1✔
464
                result.getSubchannel().getAttributes().get(ATTR_SUBCHANNEL_ADDRESS_NAME));
1✔
465
          }
466
        }
467
        return result;
1✔
468
      }
469

470
      @Override
471
      public String toString() {
472
        return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
×
473
      }
474
    }
475
  }
476

477
  private static final class CountingStreamTracerFactory extends
478
      ClientStreamTracer.Factory {
479
    private final ClusterLocalityStats stats;
480
    private final AtomicLong inFlights;
481
    @Nullable
482
    private final ClientStreamTracer.Factory delegate;
483

484
    private CountingStreamTracerFactory(
485
        ClusterLocalityStats stats, AtomicLong inFlights,
486
        @Nullable ClientStreamTracer.Factory delegate) {
1✔
487
      this.stats = checkNotNull(stats, "stats");
1✔
488
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
489
      this.delegate = delegate;
1✔
490
    }
1✔
491

492
    @Override
493
    public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
494
      stats.recordCallStarted();
1✔
495
      inFlights.incrementAndGet();
1✔
496
      if (delegate == null) {
1✔
497
        return new ClientStreamTracer() {
1✔
498
          @Override
499
          public void streamClosed(Status status) {
500
            stats.recordCallFinished(status);
1✔
501
            inFlights.decrementAndGet();
1✔
502
          }
1✔
503
        };
504
      }
505
      final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
×
506
      return new ForwardingClientStreamTracer() {
×
507
        @Override
508
        protected ClientStreamTracer delegate() {
509
          return delegatedTracer;
×
510
        }
511

512
        @Override
513
        public void streamClosed(Status status) {
514
          stats.recordCallFinished(status);
×
515
          inFlights.decrementAndGet();
×
516
          delegate().streamClosed(status);
×
517
        }
×
518
      };
519
    }
520
  }
521

522
  private static final class OrcaPerRpcListener implements OrcaPerRequestReportListener {
523

524
    private final ClusterLocalityStats stats;
525

526
    private OrcaPerRpcListener(ClusterLocalityStats stats) {
1✔
527
      this.stats = checkNotNull(stats, "stats");
1✔
528
    }
1✔
529

530
    /**
531
     * Copies ORCA metrics from {@link MetricReport} to {@link ClusterLocalityStats}
532
     * such that they are included in the snapshot for the LRS report sent to the LRS server.
533
     * This includes both top-level metrics (CPU, memory, application utilization) and named
534
     * metrics, filtered according to the backend metric propagation configuration.
535
     */
536
    @Override
537
    public void onLoadReport(MetricReport report) {
538
      if (isEnabledOrcaLrsPropagation) {
1✔
539
        stats.recordTopLevelMetrics(
1✔
540
            report.getCpuUtilization(),
1✔
541
            report.getMemoryUtilization(),
1✔
542
            report.getApplicationUtilization());
1✔
543
      }
544
      stats.recordBackendLoadMetricStats(report.getNamedMetrics());
1✔
545
    }
1✔
546
  }
547

548
  /**
549
   * Represents the {@link ClusterLocalityStats} and network locality name of a cluster.
550
   */
551
  static final class ClusterLocality {
552
    private final ClusterLocalityStats clusterLocalityStats;
553
    private final String clusterLocalityName;
554

555
    @VisibleForTesting
556
    ClusterLocality(ClusterLocalityStats localityStats, String localityName) {
1✔
557
      this.clusterLocalityStats = localityStats;
1✔
558
      this.clusterLocalityName = localityName;
1✔
559
    }
1✔
560

561
    ClusterLocalityStats getClusterLocalityStats() {
562
      return clusterLocalityStats;
1✔
563
    }
564

565
    String getClusterLocalityName() {
566
      return clusterLocalityName;
1✔
567
    }
568

569
    @VisibleForTesting
570
    void release() {
571
      if (clusterLocalityStats != null) {
1✔
572
        clusterLocalityStats.release();
1✔
573
      }
574
    }
1✔
575
  }
576
}
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

© 2026 Coveralls, Inc