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

grpc / grpc-java / #20096

26 Nov 2025 06:57PM UTC coverage: 88.595% (-0.002%) from 88.597%
#20096

push

github

ejona86
xds: Use separate key for ATTR_ADDRESS_NAME on a subchannel

XdsInternalAttributes.ATTR_ADDRESS_NAME is annotated with
`@EquivalentAddressGroup.Attr`, so it should only be used in the EAG.

35120 of 39641 relevant lines covered (88.6%)

0.89 hits per line

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

95.08
/../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
    childSwitchLb.handleResolvedAddresses(
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
    return Status.OK;
1✔
163
  }
164

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

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

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

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

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

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

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

255
      return new ForwardingSubchannel() {
1✔
256
        @Override
257
        public void start(SubchannelStateListener listener) {
258
          delegate().start(new SubchannelStateListener() {
1✔
259
            @Override
260
            public void onSubchannelState(ConnectivityStateInfo newState) {
261
              // Do nothing if LB has been shutdown
262
              if (xdsClient != null && newState.getState().equals(ConnectivityState.READY)) {
1✔
263
                // Get locality based on the connected address attributes
264
                ClusterLocality updatedClusterLocality = createClusterLocalityFromAttributes(
1✔
265
                    subchannel.getConnectedAddressAttributes());
1✔
266
                ClusterLocality oldClusterLocality = localityAtomicReference
1✔
267
                    .getAndSet(updatedClusterLocality);
1✔
268
                oldClusterLocality.release();
1✔
269
              }
270
              listener.onSubchannelState(newState);
1✔
271
            }
1✔
272
          });
273
        }
1✔
274

275
        @Override
276
        public void shutdown() {
277
          localityAtomicReference.get().release();
1✔
278
          delegate().shutdown();
1✔
279
        }
1✔
280

281
        @Override
282
        public void updateAddresses(List<EquivalentAddressGroup> addresses) {
283
          delegate().updateAddresses(withAdditionalAttributes(addresses));
1✔
284
        }
1✔
285

286
        @Override
287
        protected Subchannel delegate() {
288
          return subchannel;
1✔
289
        }
290
      };
291
    }
292

293
    private List<EquivalentAddressGroup> withAdditionalAttributes(
294
        List<EquivalentAddressGroup> addresses) {
295
      List<EquivalentAddressGroup> newAddresses = new ArrayList<>();
1✔
296
      for (EquivalentAddressGroup eag : addresses) {
1✔
297
        Attributes.Builder attrBuilder = eag.getAttributes().toBuilder().set(
1✔
298
            io.grpc.xds.XdsAttributes.ATTR_CLUSTER_NAME, cluster);
1✔
299
        if (sslContextProviderSupplier != null) {
1✔
300
          attrBuilder.set(
1✔
301
              SecurityProtocolNegotiators.ATTR_SSL_CONTEXT_PROVIDER_SUPPLIER,
302
              sslContextProviderSupplier);
303
        }
304
        newAddresses.add(new EquivalentAddressGroup(eag.getAddresses(), attrBuilder.build()));
1✔
305
      }
1✔
306
      return newAddresses;
1✔
307
    }
308

309
    private ClusterLocality createClusterLocalityFromAttributes(Attributes addressAttributes) {
310
      Locality locality = addressAttributes.get(io.grpc.xds.XdsAttributes.ATTR_LOCALITY);
1✔
311
      String localityName = addressAttributes.get(EquivalentAddressGroup.ATTR_LOCALITY_NAME);
1✔
312

313
      // Endpoint addresses resolved by ClusterResolverLoadBalancer should always contain
314
      // attributes with its locality, including endpoints in LOGICAL_DNS clusters.
315
      // In case of not (which really shouldn't), loads are aggregated under an empty
316
      // locality.
317
      if (locality == null) {
1✔
318
        locality = Locality.create("", "", "");
×
319
        localityName = "";
×
320
      }
321

322
      final ClusterLocalityStats localityStats =
323
          (lrsServerInfo == null)
1✔
324
              ? null
1✔
325
              : xdsClient.addClusterLocalityStats(lrsServerInfo, cluster,
1✔
326
                  edsServiceName, locality, backendMetricPropagation);
1✔
327

328
      return new ClusterLocality(localityStats, localityName);
1✔
329
    }
330

331
    @Override
332
    protected Helper delegate()  {
333
      return helper;
1✔
334
    }
335

336
    private void updateDropPolicies(List<DropOverload> dropOverloads) {
337
      if (!dropPolicies.equals(dropOverloads)) {
1✔
338
        dropPolicies = dropOverloads;
1✔
339
        updateBalancingState(currentState, currentPicker);
1✔
340
      }
341
    }
1✔
342

343
    private void updateMaxConcurrentRequests(@Nullable Long maxConcurrentRequests) {
344
      if (Objects.equals(this.maxConcurrentRequests, maxConcurrentRequests)) {
1✔
345
        return;
×
346
      }
347
      this.maxConcurrentRequests =
1✔
348
          maxConcurrentRequests != null
1✔
349
              ? maxConcurrentRequests
1✔
350
              : DEFAULT_PER_CLUSTER_MAX_CONCURRENT_REQUESTS;
1✔
351
      updateBalancingState(currentState, currentPicker);
1✔
352
    }
1✔
353

354
    private void updateSslContextProviderSupplier(@Nullable UpstreamTlsContext tlsContext) {
355
      UpstreamTlsContext currentTlsContext =
356
          sslContextProviderSupplier != null
1✔
357
              ? (UpstreamTlsContext)sslContextProviderSupplier.getTlsContext()
1✔
358
              : null;
1✔
359
      if (Objects.equals(currentTlsContext,  tlsContext)) {
1✔
360
        return;
1✔
361
      }
362
      if (sslContextProviderSupplier != null) {
1✔
363
        sslContextProviderSupplier.close();
1✔
364
      }
365
      sslContextProviderSupplier =
1✔
366
          tlsContext != null
1✔
367
              ? new SslContextProviderSupplier(tlsContext,
1✔
368
                                               (TlsContextManager) xdsClient.getSecurityConfig())
1✔
369
              : null;
1✔
370
    }
1✔
371

372
    private void updateFilterMetadata(Map<String, Struct> filterMetadata) {
373
      this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
374
    }
1✔
375

376
    private void updateBackendMetricPropagation(
377
        @Nullable BackendMetricPropagation backendMetricPropagation) {
378
      this.backendMetricPropagation = backendMetricPropagation;
1✔
379
    }
1✔
380

381
    private class RequestLimitingSubchannelPicker extends SubchannelPicker {
382
      private final SubchannelPicker delegate;
383
      private final List<DropOverload> dropPolicies;
384
      private final long maxConcurrentRequests;
385
      private final Map<String, Struct> filterMetadata;
386

387
      private RequestLimitingSubchannelPicker(SubchannelPicker delegate,
388
          List<DropOverload> dropPolicies, long maxConcurrentRequests,
389
          Map<String, Struct> filterMetadata) {
1✔
390
        this.delegate = delegate;
1✔
391
        this.dropPolicies = dropPolicies;
1✔
392
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
393
        this.filterMetadata = checkNotNull(filterMetadata, "filterMetadata");
1✔
394
      }
1✔
395

396
      @Override
397
      public PickResult pickSubchannel(PickSubchannelArgs args) {
398
        args.getCallOptions().getOption(ClusterImplLoadBalancerProvider.FILTER_METADATA_CONSUMER)
1✔
399
            .accept(filterMetadata);
1✔
400
        args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.backend_service", cluster);
1✔
401
        for (DropOverload dropOverload : dropPolicies) {
1✔
402
          int rand = random.nextInt(1_000_000);
1✔
403
          if (rand < dropOverload.dropsPerMillion()) {
1✔
404
            logger.log(XdsLogLevel.INFO, "Drop request with category: {0}",
1✔
405
                dropOverload.category());
1✔
406
            if (dropStats != null) {
1✔
407
              dropStats.recordDroppedRequest(dropOverload.category());
1✔
408
            }
409
            return PickResult.withDrop(
1✔
410
                Status.UNAVAILABLE.withDescription("Dropped: " + dropOverload.category()));
1✔
411
          }
412
        }
1✔
413
        PickResult result = delegate.pickSubchannel(args);
1✔
414
        if (result.getStatus().isOk() && result.getSubchannel() != null) {
1✔
415
          if (enableCircuitBreaking) {
1✔
416
            if (inFlights.get() >= maxConcurrentRequests) {
1✔
417
              if (dropStats != null) {
1✔
418
                dropStats.recordDroppedRequest();
1✔
419
              }
420
              return PickResult.withDrop(Status.UNAVAILABLE.withDescription(
1✔
421
                  String.format(Locale.US, "Cluster max concurrent requests limit of %d exceeded",
1✔
422
                      maxConcurrentRequests)));
1✔
423
            }
424
          }
425
          final AtomicReference<ClusterLocality> clusterLocality =
1✔
426
              result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY);
1✔
427

428
          if (clusterLocality != null) {
1✔
429
            ClusterLocalityStats stats = clusterLocality.get().getClusterLocalityStats();
1✔
430
            if (stats != null) {
1✔
431
              String localityName =
1✔
432
                  result.getSubchannel().getAttributes().get(ATTR_CLUSTER_LOCALITY).get()
1✔
433
                      .getClusterLocalityName();
1✔
434
              args.getPickDetailsConsumer().addOptionalLabel("grpc.lb.locality", localityName);
1✔
435

436
              ClientStreamTracer.Factory tracerFactory = new CountingStreamTracerFactory(
1✔
437
                  stats, inFlights, result.getStreamTracerFactory());
1✔
438
              ClientStreamTracer.Factory orcaTracerFactory = OrcaPerRequestUtil.getInstance()
1✔
439
                  .newOrcaClientStreamTracerFactory(tracerFactory, new OrcaPerRpcListener(stats));
1✔
440
              result = PickResult.withSubchannel(result.getSubchannel(),
1✔
441
                  orcaTracerFactory);
442
            }
443
          }
444
          if (args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY) != null
1✔
445
              && args.getCallOptions().getOption(XdsNameResolver.AUTO_HOST_REWRITE_KEY)) {
1✔
446
            result = PickResult.withSubchannel(result.getSubchannel(),
1✔
447
                result.getStreamTracerFactory(),
1✔
448
                result.getSubchannel().getAttributes().get(ATTR_SUBCHANNEL_ADDRESS_NAME));
1✔
449
          }
450
        }
451
        return result;
1✔
452
      }
453

454
      @Override
455
      public String toString() {
456
        return MoreObjects.toStringHelper(this).add("delegate", delegate).toString();
×
457
      }
458
    }
459
  }
460

461
  private static final class CountingStreamTracerFactory extends
462
      ClientStreamTracer.Factory {
463
    private final ClusterLocalityStats stats;
464
    private final AtomicLong inFlights;
465
    @Nullable
466
    private final ClientStreamTracer.Factory delegate;
467

468
    private CountingStreamTracerFactory(
469
        ClusterLocalityStats stats, AtomicLong inFlights,
470
        @Nullable ClientStreamTracer.Factory delegate) {
1✔
471
      this.stats = checkNotNull(stats, "stats");
1✔
472
      this.inFlights = checkNotNull(inFlights, "inFlights");
1✔
473
      this.delegate = delegate;
1✔
474
    }
1✔
475

476
    @Override
477
    public ClientStreamTracer newClientStreamTracer(StreamInfo info, Metadata headers) {
478
      stats.recordCallStarted();
1✔
479
      inFlights.incrementAndGet();
1✔
480
      if (delegate == null) {
1✔
481
        return new ClientStreamTracer() {
1✔
482
          @Override
483
          public void streamClosed(Status status) {
484
            stats.recordCallFinished(status);
1✔
485
            inFlights.decrementAndGet();
1✔
486
          }
1✔
487
        };
488
      }
489
      final ClientStreamTracer delegatedTracer = delegate.newClientStreamTracer(info, headers);
×
490
      return new ForwardingClientStreamTracer() {
×
491
        @Override
492
        protected ClientStreamTracer delegate() {
493
          return delegatedTracer;
×
494
        }
495

496
        @Override
497
        public void streamClosed(Status status) {
498
          stats.recordCallFinished(status);
×
499
          inFlights.decrementAndGet();
×
500
          delegate().streamClosed(status);
×
501
        }
×
502
      };
503
    }
504
  }
505

506
  private static final class OrcaPerRpcListener implements OrcaPerRequestReportListener {
507

508
    private final ClusterLocalityStats stats;
509

510
    private OrcaPerRpcListener(ClusterLocalityStats stats) {
1✔
511
      this.stats = checkNotNull(stats, "stats");
1✔
512
    }
1✔
513

514
    /**
515
     * Copies ORCA metrics from {@link MetricReport} to {@link ClusterLocalityStats}
516
     * such that they are included in the snapshot for the LRS report sent to the LRS server.
517
     * This includes both top-level metrics (CPU, memory, application utilization) and named
518
     * metrics, filtered according to the backend metric propagation configuration.
519
     */
520
    @Override
521
    public void onLoadReport(MetricReport report) {
522
      if (isEnabledOrcaLrsPropagation) {
1✔
523
        stats.recordTopLevelMetrics(
1✔
524
            report.getCpuUtilization(),
1✔
525
            report.getMemoryUtilization(),
1✔
526
            report.getApplicationUtilization());
1✔
527
      }
528
      stats.recordBackendLoadMetricStats(report.getNamedMetrics());
1✔
529
    }
1✔
530
  }
531

532
  /**
533
   * Represents the {@link ClusterLocalityStats} and network locality name of a cluster.
534
   */
535
  static final class ClusterLocality {
536
    private final ClusterLocalityStats clusterLocalityStats;
537
    private final String clusterLocalityName;
538

539
    @VisibleForTesting
540
    ClusterLocality(ClusterLocalityStats localityStats, String localityName) {
1✔
541
      this.clusterLocalityStats = localityStats;
1✔
542
      this.clusterLocalityName = localityName;
1✔
543
    }
1✔
544

545
    ClusterLocalityStats getClusterLocalityStats() {
546
      return clusterLocalityStats;
1✔
547
    }
548

549
    String getClusterLocalityName() {
550
      return clusterLocalityName;
1✔
551
    }
552

553
    @VisibleForTesting
554
    void release() {
555
      if (clusterLocalityStats != null) {
1✔
556
        clusterLocalityStats.release();
1✔
557
      }
558
    }
1✔
559
  }
560
}
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