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

grpc / grpc-java / #19858

11 Jun 2025 07:19PM UTC coverage: 88.606% (-0.007%) from 88.613%
#19858

push

github

web-flow
google-java-format a line that was too long (#12147)

34613 of 39064 relevant lines covered (88.61%)

0.89 hits per line

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

90.79
/../xds/src/main/java/io/grpc/xds/XdsClusterResource.java
1
/*
2
 * Copyright 2022 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.Bootstrapper.ServerInfo;
21

22
import com.google.auto.value.AutoValue;
23
import com.google.common.annotations.VisibleForTesting;
24
import com.google.common.base.MoreObjects;
25
import com.google.common.base.Strings;
26
import com.google.common.collect.ImmutableList;
27
import com.google.common.collect.ImmutableMap;
28
import com.google.protobuf.Duration;
29
import com.google.protobuf.InvalidProtocolBufferException;
30
import com.google.protobuf.Message;
31
import com.google.protobuf.Struct;
32
import com.google.protobuf.util.Durations;
33
import io.envoyproxy.envoy.config.cluster.v3.CircuitBreakers.Thresholds;
34
import io.envoyproxy.envoy.config.cluster.v3.Cluster;
35
import io.envoyproxy.envoy.config.core.v3.RoutingPriority;
36
import io.envoyproxy.envoy.config.core.v3.SocketAddress;
37
import io.envoyproxy.envoy.config.core.v3.TransportSocket;
38
import io.envoyproxy.envoy.config.endpoint.v3.ClusterLoadAssignment;
39
import io.envoyproxy.envoy.extensions.transport_sockets.http_11_proxy.v3.Http11ProxyUpstreamTransport;
40
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CertificateValidationContext;
41
import io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.CommonTlsContext;
42
import io.grpc.LoadBalancerRegistry;
43
import io.grpc.NameResolver;
44
import io.grpc.internal.GrpcUtil;
45
import io.grpc.internal.ServiceConfigUtil;
46
import io.grpc.internal.ServiceConfigUtil.LbConfig;
47
import io.grpc.xds.EnvoyServerProtoData.OutlierDetection;
48
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
49
import io.grpc.xds.XdsClusterResource.CdsUpdate;
50
import io.grpc.xds.client.XdsClient.ResourceUpdate;
51
import io.grpc.xds.client.XdsResourceType;
52
import io.grpc.xds.internal.security.CommonTlsContextUtil;
53
import java.util.List;
54
import java.util.Locale;
55
import java.util.Set;
56
import javax.annotation.Nullable;
57

58
class XdsClusterResource extends XdsResourceType<CdsUpdate> {
1✔
59
  @VisibleForTesting
60
  static boolean enableLeastRequest =
61
      !Strings.isNullOrEmpty(System.getenv("GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST"))
1✔
62
          ? Boolean.parseBoolean(System.getenv("GRPC_EXPERIMENTAL_ENABLE_LEAST_REQUEST"))
×
63
          : Boolean.parseBoolean(
1✔
64
              System.getProperty("io.grpc.xds.experimentalEnableLeastRequest", "true"));
1✔
65
  @VisibleForTesting
66
  public static boolean enableSystemRootCerts =
1✔
67
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_SYSTEM_ROOT_CERTS", false);
1✔
68
  static boolean isEnabledXdsHttpConnect =
1✔
69
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_HTTP_CONNECT", false);
1✔
70

71
  @VisibleForTesting
72
  static final String AGGREGATE_CLUSTER_TYPE_NAME = "envoy.clusters.aggregate";
73
  static final String ADS_TYPE_URL_CDS =
74
      "type.googleapis.com/envoy.config.cluster.v3.Cluster";
75
  private static final String TYPE_URL_CLUSTER_CONFIG =
76
      "type.googleapis.com/envoy.extensions.clusters.aggregate.v3.ClusterConfig";
77
  private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT =
78
      "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext";
79
  private static final String TYPE_URL_UPSTREAM_TLS_CONTEXT_V2 =
80
      "type.googleapis.com/envoy.api.v2.auth.UpstreamTlsContext";
81
  static final String TRANSPORT_SOCKET_NAME_HTTP11_PROXY =
82
      "type.googleapis.com/envoy.extensions.transport_sockets.http_11_proxy.v3"
83
          + ".Http11ProxyUpstreamTransport";
84
  private final LoadBalancerRegistry loadBalancerRegistry
1✔
85
      = LoadBalancerRegistry.getDefaultRegistry();
1✔
86

87
  private static final XdsClusterResource instance = new XdsClusterResource();
1✔
88

89
  public static XdsClusterResource getInstance() {
90
    return instance;
1✔
91
  }
92

93
  @Override
94
  @Nullable
95
  protected String extractResourceName(Message unpackedResource) {
96
    if (!(unpackedResource instanceof Cluster)) {
1✔
97
      return null;
×
98
    }
99
    return ((Cluster) unpackedResource).getName();
1✔
100
  }
101

102
  @Override
103
  public String typeName() {
104
    return "CDS";
1✔
105
  }
106

107
  @Override
108
  public String typeUrl() {
109
    return ADS_TYPE_URL_CDS;
1✔
110
  }
111

112
  @Override
113
  public boolean shouldRetrieveResourceKeysForArgs() {
114
    return true;
1✔
115
  }
116

117
  @Override
118
  protected boolean isFullStateOfTheWorld() {
119
    return true;
1✔
120
  }
121

122
  @Override
123
  @SuppressWarnings("unchecked")
124
  protected Class<Cluster> unpackedClassName() {
125
    return Cluster.class;
1✔
126
  }
127

128
  @Override
129
  protected CdsUpdate doParse(Args args, Message unpackedMessage) throws ResourceInvalidException {
130
    if (!(unpackedMessage instanceof Cluster)) {
1✔
131
      throw new ResourceInvalidException("Invalid message type: " + unpackedMessage.getClass());
×
132
    }
133
    Set<String> certProviderInstances = null;
1✔
134
    if (args.getBootstrapInfo() != null && args.getBootstrapInfo().certProviders() != null) {
1✔
135
      certProviderInstances = args.getBootstrapInfo().certProviders().keySet();
1✔
136
    }
137
    return processCluster((Cluster) unpackedMessage, certProviderInstances,
1✔
138
        args.getServerInfo(), loadBalancerRegistry);
1✔
139
  }
140

141
  @VisibleForTesting
142
  static CdsUpdate processCluster(Cluster cluster,
143
                                  Set<String> certProviderInstances,
144
                                  ServerInfo serverInfo,
145
                                  LoadBalancerRegistry loadBalancerRegistry)
146
      throws ResourceInvalidException {
147
    StructOrError<CdsUpdate.Builder> structOrError;
148
    switch (cluster.getClusterDiscoveryTypeCase()) {
1✔
149
      case TYPE:
150
        structOrError = parseNonAggregateCluster(cluster,
1✔
151
            certProviderInstances, serverInfo);
152
        break;
1✔
153
      case CLUSTER_TYPE:
154
        structOrError = parseAggregateCluster(cluster);
1✔
155
        break;
1✔
156
      case CLUSTERDISCOVERYTYPE_NOT_SET:
157
      default:
158
        throw new ResourceInvalidException(
1✔
159
            "Cluster " + cluster.getName() + ": unspecified cluster discovery type");
1✔
160
    }
161
    if (structOrError.getErrorDetail() != null) {
1✔
162
      throw new ResourceInvalidException(structOrError.getErrorDetail());
1✔
163
    }
164
    CdsUpdate.Builder updateBuilder = structOrError.getStruct();
1✔
165

166
    ImmutableMap<String, ?> lbPolicyConfig = LoadBalancerConfigFactory.newConfig(cluster,
1✔
167
        enableLeastRequest);
168

169
    // Validate the LB config by trying to parse it with the corresponding LB provider.
170
    LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(lbPolicyConfig);
1✔
171
    NameResolver.ConfigOrError configOrError = loadBalancerRegistry.getProvider(
1✔
172
        lbConfig.getPolicyName()).parseLoadBalancingPolicyConfig(
1✔
173
        lbConfig.getRawConfigValue());
1✔
174
    if (configOrError.getError() != null) {
1✔
175
      throw new ResourceInvalidException(
1✔
176
          "Failed to parse lb config for cluster '" + cluster.getName() + "': "
1✔
177
          + configOrError.getError());
1✔
178
    }
179

180
    updateBuilder.lbPolicyConfig(lbPolicyConfig);
1✔
181
    updateBuilder.filterMetadata(
1✔
182
        ImmutableMap.copyOf(cluster.getMetadata().getFilterMetadataMap()));
1✔
183

184
    try {
185
      MetadataRegistry registry = MetadataRegistry.getInstance();
1✔
186
      ImmutableMap<String, Object> parsedFilterMetadata =
1✔
187
          registry.parseMetadata(cluster.getMetadata());
1✔
188
      updateBuilder.parsedMetadata(parsedFilterMetadata);
1✔
189
    } catch (ResourceInvalidException e) {
×
190
      throw new ResourceInvalidException(
×
191
          "Failed to parse xDS filter metadata for cluster '" + cluster.getName() + "': "
×
192
              + e.getMessage(), e);
×
193
    }
1✔
194

195
    return updateBuilder.build();
1✔
196
  }
197

198
  private static StructOrError<CdsUpdate.Builder> parseAggregateCluster(Cluster cluster) {
199
    String clusterName = cluster.getName();
1✔
200
    Cluster.CustomClusterType customType = cluster.getClusterType();
1✔
201
    String typeName = customType.getName();
1✔
202
    if (!typeName.equals(AGGREGATE_CLUSTER_TYPE_NAME)) {
1✔
203
      return StructOrError.fromError(
×
204
          "Cluster " + clusterName + ": unsupported custom cluster type: " + typeName);
205
    }
206
    io.envoyproxy.envoy.extensions.clusters.aggregate.v3.ClusterConfig clusterConfig;
207
    try {
208
      clusterConfig = unpackCompatibleType(customType.getTypedConfig(),
1✔
209
          io.envoyproxy.envoy.extensions.clusters.aggregate.v3.ClusterConfig.class,
210
          TYPE_URL_CLUSTER_CONFIG, null);
211
    } catch (InvalidProtocolBufferException e) {
×
212
      return StructOrError.fromError("Cluster " + clusterName + ": malformed ClusterConfig: " + e);
×
213
    }
1✔
214
    if (clusterConfig.getClustersList().isEmpty()) {
1✔
215
      return StructOrError.fromError("Cluster " + clusterName
1✔
216
          + ": aggregate ClusterConfig.clusters must not be empty");
217
    }
218
    return StructOrError.fromStruct(CdsUpdate.forAggregate(
1✔
219
        clusterName, clusterConfig.getClustersList()));
1✔
220
  }
221

222
  private static StructOrError<CdsUpdate.Builder> parseNonAggregateCluster(
223
      Cluster cluster, Set<String> certProviderInstances, ServerInfo serverInfo) {
224
    String clusterName = cluster.getName();
1✔
225
    ServerInfo lrsServerInfo = null;
1✔
226
    Long maxConcurrentRequests = null;
1✔
227
    UpstreamTlsContext upstreamTlsContext = null;
1✔
228
    OutlierDetection outlierDetection = null;
1✔
229
    boolean isHttp11ProxyAvailable = false;
1✔
230
    if (cluster.hasLrsServer()) {
1✔
231
      if (!cluster.getLrsServer().hasSelf()) {
1✔
232
        return StructOrError.fromError(
×
233
            "Cluster " + clusterName + ": only support LRS for the same management server");
234
      }
235
      lrsServerInfo = serverInfo;
1✔
236
    }
237
    if (cluster.hasCircuitBreakers()) {
1✔
238
      List<Thresholds> thresholds = cluster.getCircuitBreakers().getThresholdsList();
1✔
239
      for (Thresholds threshold : thresholds) {
1✔
240
        if (threshold.getPriority() != RoutingPriority.DEFAULT) {
1✔
241
          continue;
1✔
242
        }
243
        if (threshold.hasMaxRequests()) {
1✔
244
          maxConcurrentRequests = Integer.toUnsignedLong(threshold.getMaxRequests().getValue());
1✔
245
        }
246
      }
1✔
247
    }
248
    if (cluster.getTransportSocketMatchesCount() > 0) {
1✔
249
      return StructOrError.fromError("Cluster " + clusterName
1✔
250
          + ": transport-socket-matches not supported.");
251
    }
252
    boolean hasTransportSocket = cluster.hasTransportSocket();
1✔
253
    TransportSocket transportSocket = cluster.getTransportSocket();
1✔
254

255
    if (hasTransportSocket && !TRANSPORT_SOCKET_NAME_TLS.equals(transportSocket.getName())
1✔
256
        && !(isEnabledXdsHttpConnect
257
        && TRANSPORT_SOCKET_NAME_HTTP11_PROXY.equals(transportSocket.getName()))) {
1✔
258
      return StructOrError.fromError(
1✔
259
          "transport-socket with name " + transportSocket.getName() + " not supported.");
1✔
260
    }
261

262
    if (hasTransportSocket && isEnabledXdsHttpConnect
1✔
263
        && TRANSPORT_SOCKET_NAME_HTTP11_PROXY.equals(transportSocket.getName())) {
1✔
264
      isHttp11ProxyAvailable = true;
1✔
265
      try {
266
        Http11ProxyUpstreamTransport wrappedTransportSocket = transportSocket
1✔
267
            .getTypedConfig().unpack(io.envoyproxy.envoy.extensions.transport_sockets
1✔
268
                .http_11_proxy.v3.Http11ProxyUpstreamTransport.class);
269
        hasTransportSocket = wrappedTransportSocket.hasTransportSocket();
1✔
270
        transportSocket = wrappedTransportSocket.getTransportSocket();
1✔
271
      } catch (InvalidProtocolBufferException e) {
×
272
        return StructOrError.fromError(
×
273
            "Cluster " + clusterName + ": malformed Http11ProxyUpstreamTransport: " + e);
274
      } catch (ClassCastException e) {
×
275
        return StructOrError.fromError(
×
276
            "Cluster " + clusterName
277
                + ": invalid transport_socket type in Http11ProxyUpstreamTransport");
278
      }
1✔
279
    }
280

281
    if (hasTransportSocket && TRANSPORT_SOCKET_NAME_TLS.equals(transportSocket.getName())) {
1✔
282
      try {
283
        upstreamTlsContext = UpstreamTlsContext.fromEnvoyProtoUpstreamTlsContext(
1✔
284
            validateUpstreamTlsContext(
1✔
285
                unpackCompatibleType(transportSocket.getTypedConfig(),
1✔
286
                    io.envoyproxy.envoy.extensions
287
                        .transport_sockets.tls.v3.UpstreamTlsContext.class,
288
                    TYPE_URL_UPSTREAM_TLS_CONTEXT, TYPE_URL_UPSTREAM_TLS_CONTEXT_V2),
289
                certProviderInstances));
290
      } catch (InvalidProtocolBufferException | ResourceInvalidException e) {
1✔
291
        return StructOrError.fromError(
1✔
292
            "Cluster " + clusterName + ": malformed UpstreamTlsContext: " + e);
293
      }
1✔
294
    }
295

296
    if (cluster.hasOutlierDetection()) {
1✔
297
      try {
298
        outlierDetection = OutlierDetection.fromEnvoyOutlierDetection(
1✔
299
            validateOutlierDetection(cluster.getOutlierDetection()));
1✔
300
      } catch (ResourceInvalidException e) {
1✔
301
        return StructOrError.fromError(
1✔
302
            "Cluster " + clusterName + ": malformed outlier_detection: " + e);
303
      }
1✔
304
    }
305

306
    Cluster.DiscoveryType type = cluster.getType();
1✔
307
    if (type == Cluster.DiscoveryType.EDS) {
1✔
308
      String edsServiceName = null;
1✔
309
      io.envoyproxy.envoy.config.cluster.v3.Cluster.EdsClusterConfig edsClusterConfig =
1✔
310
          cluster.getEdsClusterConfig();
1✔
311
      if (!edsClusterConfig.getEdsConfig().hasAds()
1✔
312
          && ! edsClusterConfig.getEdsConfig().hasSelf()) {
1✔
313
        return StructOrError.fromError(
1✔
314
            "Cluster " + clusterName + ": field eds_cluster_config must be set to indicate to use"
315
                + " EDS over ADS or self ConfigSource");
316
      }
317
      // If the service_name field is set, that value will be used for the EDS request.
318
      if (!edsClusterConfig.getServiceName().isEmpty()) {
1✔
319
        edsServiceName = edsClusterConfig.getServiceName();
1✔
320
      }
321
      // edsServiceName is required if the CDS resource has an xdstp name.
322
      if ((edsServiceName == null) && clusterName.toLowerCase(Locale.ROOT).startsWith("xdstp:")) {
1✔
323
        return StructOrError.fromError(
1✔
324
            "EDS service_name must be set when Cluster resource has an xdstp name");
325
      }
326

327
      return StructOrError.fromStruct(CdsUpdate.forEds(
1✔
328
          clusterName, edsServiceName, lrsServerInfo, maxConcurrentRequests, upstreamTlsContext,
329
          outlierDetection, isHttp11ProxyAvailable));
330
    } else if (type.equals(Cluster.DiscoveryType.LOGICAL_DNS)) {
1✔
331
      if (!cluster.hasLoadAssignment()) {
1✔
332
        return StructOrError.fromError(
×
333
            "Cluster " + clusterName + ": LOGICAL_DNS clusters must have a single host");
334
      }
335
      ClusterLoadAssignment assignment = cluster.getLoadAssignment();
1✔
336
      if (assignment.getEndpointsCount() != 1
1✔
337
          || assignment.getEndpoints(0).getLbEndpointsCount() != 1) {
1✔
338
        return StructOrError.fromError(
×
339
            "Cluster " + clusterName + ": LOGICAL_DNS clusters must have a single "
340
                + "locality_lb_endpoint and a single lb_endpoint");
341
      }
342
      io.envoyproxy.envoy.config.endpoint.v3.LbEndpoint lbEndpoint =
1✔
343
          assignment.getEndpoints(0).getLbEndpoints(0);
1✔
344
      if (!lbEndpoint.hasEndpoint() || !lbEndpoint.getEndpoint().hasAddress()
1✔
345
          || !lbEndpoint.getEndpoint().getAddress().hasSocketAddress()) {
1✔
346
        return StructOrError.fromError(
×
347
            "Cluster " + clusterName
348
                + ": LOGICAL_DNS clusters must have an endpoint with address and socket_address");
349
      }
350
      SocketAddress socketAddress = lbEndpoint.getEndpoint().getAddress().getSocketAddress();
1✔
351
      if (!socketAddress.getResolverName().isEmpty()) {
1✔
352
        return StructOrError.fromError(
×
353
            "Cluster " + clusterName
354
                + ": LOGICAL DNS clusters must NOT have a custom resolver name set");
355
      }
356
      if (socketAddress.getPortSpecifierCase() != SocketAddress.PortSpecifierCase.PORT_VALUE) {
1✔
357
        return StructOrError.fromError(
×
358
            "Cluster " + clusterName
359
                + ": LOGICAL DNS clusters socket_address must have port_value");
360
      }
361
      String dnsHostName = String.format(
1✔
362
          Locale.US, "%s:%d", socketAddress.getAddress(), socketAddress.getPortValue());
1✔
363
      return StructOrError.fromStruct(CdsUpdate.forLogicalDns(
1✔
364
          clusterName, dnsHostName, lrsServerInfo, maxConcurrentRequests,
365
          upstreamTlsContext, isHttp11ProxyAvailable));
366
    }
367
    return StructOrError.fromError(
×
368
        "Cluster " + clusterName + ": unsupported built-in discovery type: " + type);
369
  }
370

371
  static io.envoyproxy.envoy.config.cluster.v3.OutlierDetection validateOutlierDetection(
372
      io.envoyproxy.envoy.config.cluster.v3.OutlierDetection outlierDetection)
373
      throws ResourceInvalidException {
374
    if (outlierDetection.hasInterval()) {
1✔
375
      if (!Durations.isValid(outlierDetection.getInterval())) {
1✔
376
        throw new ResourceInvalidException("outlier_detection interval is not a valid Duration");
1✔
377
      }
378
      if (hasNegativeValues(outlierDetection.getInterval())) {
1✔
379
        throw new ResourceInvalidException("outlier_detection interval has a negative value");
1✔
380
      }
381
    }
382
    if (outlierDetection.hasBaseEjectionTime()) {
1✔
383
      if (!Durations.isValid(outlierDetection.getBaseEjectionTime())) {
1✔
384
        throw new ResourceInvalidException(
1✔
385
            "outlier_detection base_ejection_time is not a valid Duration");
386
      }
387
      if (hasNegativeValues(outlierDetection.getBaseEjectionTime())) {
1✔
388
        throw new ResourceInvalidException(
1✔
389
            "outlier_detection base_ejection_time has a negative value");
390
      }
391
    }
392
    if (outlierDetection.hasMaxEjectionTime()) {
1✔
393
      if (!Durations.isValid(outlierDetection.getMaxEjectionTime())) {
1✔
394
        throw new ResourceInvalidException(
1✔
395
            "outlier_detection max_ejection_time is not a valid Duration");
396
      }
397
      if (hasNegativeValues(outlierDetection.getMaxEjectionTime())) {
1✔
398
        throw new ResourceInvalidException(
1✔
399
            "outlier_detection max_ejection_time has a negative value");
400
      }
401
    }
402
    if (outlierDetection.hasMaxEjectionPercent()
1✔
403
        && outlierDetection.getMaxEjectionPercent().getValue() > 100) {
1✔
404
      throw new ResourceInvalidException(
1✔
405
          "outlier_detection max_ejection_percent is > 100");
406
    }
407
    if (outlierDetection.hasEnforcingSuccessRate()
1✔
408
        && outlierDetection.getEnforcingSuccessRate().getValue() > 100) {
1✔
409
      throw new ResourceInvalidException(
1✔
410
          "outlier_detection enforcing_success_rate is > 100");
411
    }
412
    if (outlierDetection.hasFailurePercentageThreshold()
1✔
413
        && outlierDetection.getFailurePercentageThreshold().getValue() > 100) {
1✔
414
      throw new ResourceInvalidException(
1✔
415
          "outlier_detection failure_percentage_threshold is > 100");
416
    }
417
    if (outlierDetection.hasEnforcingFailurePercentage()
1✔
418
        && outlierDetection.getEnforcingFailurePercentage().getValue() > 100) {
1✔
419
      throw new ResourceInvalidException(
1✔
420
          "outlier_detection enforcing_failure_percentage is > 100");
421
    }
422

423
    return outlierDetection;
1✔
424
  }
425

426
  static boolean hasNegativeValues(Duration duration) {
427
    return duration.getSeconds() < 0 || duration.getNanos() < 0;
1✔
428
  }
429

430
  @VisibleForTesting
431
  static io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
432
      validateUpstreamTlsContext(
433
      io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext upstreamTlsContext,
434
      Set<String> certProviderInstances)
435
      throws ResourceInvalidException {
436
    if (upstreamTlsContext.hasCommonTlsContext()) {
1✔
437
      validateCommonTlsContext(upstreamTlsContext.getCommonTlsContext(), certProviderInstances,
1✔
438
          false);
439
    } else {
440
      throw new ResourceInvalidException("common-tls-context is required in upstream-tls-context");
1✔
441
    }
442
    return upstreamTlsContext;
1✔
443
  }
444

445
  @VisibleForTesting
446
  static void validateCommonTlsContext(
447
      CommonTlsContext commonTlsContext, Set<String> certProviderInstances, boolean server)
448
      throws ResourceInvalidException {
449
    if (commonTlsContext.hasCustomHandshaker()) {
1✔
450
      throw new ResourceInvalidException(
1✔
451
          "common-tls-context with custom_handshaker is not supported");
452
    }
453
    if (commonTlsContext.hasTlsParams()) {
1✔
454
      throw new ResourceInvalidException("common-tls-context with tls_params is not supported");
1✔
455
    }
456
    if (commonTlsContext.hasValidationContextSdsSecretConfig()) {
1✔
457
      throw new ResourceInvalidException(
1✔
458
          "common-tls-context with validation_context_sds_secret_config is not supported");
459
    }
460
    String certInstanceName = getIdentityCertInstanceName(commonTlsContext);
1✔
461
    if (certInstanceName == null) {
1✔
462
      if (server) {
1✔
463
        throw new ResourceInvalidException(
1✔
464
            "tls_certificate_provider_instance is required in downstream-tls-context");
465
      }
466
      if (commonTlsContext.getTlsCertificatesCount() > 0) {
1✔
467
        throw new ResourceInvalidException(
1✔
468
            "tls_certificate_provider_instance is unset");
469
      }
470
      if (commonTlsContext.getTlsCertificateSdsSecretConfigsCount() > 0) {
1✔
471
        throw new ResourceInvalidException(
1✔
472
            "tls_certificate_provider_instance is unset");
473
      }
474
    } else if (certProviderInstances == null || !certProviderInstances.contains(certInstanceName)) {
1✔
475
      throw new ResourceInvalidException(
1✔
476
          "CertificateProvider instance name '" + certInstanceName
477
              + "' not defined in the bootstrap file.");
478
    }
479
    String rootCaInstanceName = getRootCertInstanceName(commonTlsContext);
1✔
480
    if (rootCaInstanceName == null) {
1✔
481
      if (!server && (!enableSystemRootCerts
1✔
482
          || !CommonTlsContextUtil.isUsingSystemRootCerts(commonTlsContext))) {
1✔
483
        throw new ResourceInvalidException(
1✔
484
            "ca_certificate_provider_instance or system_root_certs is required in "
485
                + "upstream-tls-context");
486
      }
487
    } else {
488
      if (certProviderInstances == null || !certProviderInstances.contains(rootCaInstanceName)) {
1✔
489
        throw new ResourceInvalidException(
1✔
490
            "ca_certificate_provider_instance name '" + rootCaInstanceName
491
                + "' not defined in the bootstrap file.");
492
      }
493
      CertificateValidationContext certificateValidationContext = null;
1✔
494
      if (commonTlsContext.hasValidationContext()) {
1✔
495
        certificateValidationContext = commonTlsContext.getValidationContext();
1✔
496
      } else if (commonTlsContext.hasCombinedValidationContext() && commonTlsContext
1✔
497
          .getCombinedValidationContext().hasDefaultValidationContext()) {
1✔
498
        certificateValidationContext = commonTlsContext.getCombinedValidationContext()
1✔
499
            .getDefaultValidationContext();
1✔
500
      }
501
      if (certificateValidationContext != null) {
1✔
502
        @SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
503
        int matchSubjectAltNamesCount = certificateValidationContext.getMatchSubjectAltNamesCount();
1✔
504
        if (matchSubjectAltNamesCount > 0 && server) {
1✔
505
          throw new ResourceInvalidException(
1✔
506
              "match_subject_alt_names only allowed in upstream_tls_context");
507
        }
508
        if (certificateValidationContext.getVerifyCertificateSpkiCount() > 0) {
1✔
509
          throw new ResourceInvalidException(
1✔
510
              "verify_certificate_spki in default_validation_context is not supported");
511
        }
512
        if (certificateValidationContext.getVerifyCertificateHashCount() > 0) {
1✔
513
          throw new ResourceInvalidException(
1✔
514
              "verify_certificate_hash in default_validation_context is not supported");
515
        }
516
        if (certificateValidationContext.hasRequireSignedCertificateTimestamp()) {
1✔
517
          throw new ResourceInvalidException(
1✔
518
              "require_signed_certificate_timestamp in default_validation_context is not "
519
                  + "supported");
520
        }
521
        if (certificateValidationContext.hasCrl()) {
1✔
522
          throw new ResourceInvalidException("crl in default_validation_context is not supported");
1✔
523
        }
524
        if (certificateValidationContext.hasCustomValidatorConfig()) {
1✔
525
          throw new ResourceInvalidException(
1✔
526
              "custom_validator_config in default_validation_context is not supported");
527
        }
528
      }
529
    }
530
  }
1✔
531

532
  private static String getIdentityCertInstanceName(CommonTlsContext commonTlsContext) {
533
    if (commonTlsContext.hasTlsCertificateProviderInstance()) {
1✔
534
      return commonTlsContext.getTlsCertificateProviderInstance().getInstanceName();
1✔
535
    }
536
    return null;
1✔
537
  }
538

539
  private static String getRootCertInstanceName(CommonTlsContext commonTlsContext) {
540
    if (commonTlsContext.hasValidationContext()) {
1✔
541
      if (commonTlsContext.getValidationContext().hasCaCertificateProviderInstance()) {
1✔
542
        return commonTlsContext.getValidationContext().getCaCertificateProviderInstance()
1✔
543
            .getInstanceName();
1✔
544
      }
545
    } else if (commonTlsContext.hasCombinedValidationContext()) {
1✔
546
      CommonTlsContext.CombinedCertificateValidationContext combinedCertificateValidationContext
1✔
547
          = commonTlsContext.getCombinedValidationContext();
1✔
548
      if (combinedCertificateValidationContext.hasDefaultValidationContext()
1✔
549
          && combinedCertificateValidationContext.getDefaultValidationContext()
1✔
550
          .hasCaCertificateProviderInstance()) {
1✔
551
        return combinedCertificateValidationContext.getDefaultValidationContext()
1✔
552
            .getCaCertificateProviderInstance().getInstanceName();
1✔
553
      }
554
    }
555
    return null;
1✔
556
  }
557

558
  /** xDS resource update for cluster-level configuration. */
559
  @AutoValue
560
  abstract static class CdsUpdate implements ResourceUpdate {
1✔
561
    abstract String clusterName();
562

563
    abstract ClusterType clusterType();
564

565
    abstract ImmutableMap<String, ?> lbPolicyConfig();
566

567
    // Only valid if lbPolicy is "ring_hash_experimental".
568
    abstract long minRingSize();
569

570
    // Only valid if lbPolicy is "ring_hash_experimental".
571
    abstract long maxRingSize();
572

573
    // Only valid if lbPolicy is "least_request_experimental".
574
    abstract int choiceCount();
575

576
    // Alternative resource name to be used in EDS requests.
577
    /// Only valid for EDS cluster.
578
    @Nullable
579
    abstract String edsServiceName();
580

581
    // Corresponding DNS name to be used if upstream endpoints of the cluster is resolvable
582
    // via DNS.
583
    // Only valid for LOGICAL_DNS cluster.
584
    @Nullable
585
    abstract String dnsHostName();
586

587
    // Load report server info for reporting loads via LRS.
588
    // Only valid for EDS or LOGICAL_DNS cluster.
589
    @Nullable
590
    abstract ServerInfo lrsServerInfo();
591

592
    // Max number of concurrent requests can be sent to this cluster.
593
    // Only valid for EDS or LOGICAL_DNS cluster.
594
    @Nullable
595
    abstract Long maxConcurrentRequests();
596

597
    // TLS context used to connect to connect to this cluster.
598
    // Only valid for EDS or LOGICAL_DNS cluster.
599
    @Nullable
600
    abstract UpstreamTlsContext upstreamTlsContext();
601

602
    abstract boolean isHttp11ProxyAvailable();
603

604
    // List of underlying clusters making of this aggregate cluster.
605
    // Only valid for AGGREGATE cluster.
606
    @Nullable
607
    abstract ImmutableList<String> prioritizedClusterNames();
608

609
    // Outlier detection configuration.
610
    @Nullable
611
    abstract OutlierDetection outlierDetection();
612

613
    abstract ImmutableMap<String, Struct> filterMetadata();
614

615
    abstract ImmutableMap<String, Object> parsedMetadata();
616

617
    private static Builder newBuilder(String clusterName) {
618
      return new AutoValue_XdsClusterResource_CdsUpdate.Builder()
1✔
619
          .clusterName(clusterName)
1✔
620
          .minRingSize(0)
1✔
621
          .maxRingSize(0)
1✔
622
          .choiceCount(0)
1✔
623
          .filterMetadata(ImmutableMap.of())
1✔
624
          .parsedMetadata(ImmutableMap.of())
1✔
625
          .isHttp11ProxyAvailable(false);
1✔
626
    }
627

628
    static Builder forAggregate(String clusterName, List<String> prioritizedClusterNames) {
629
      checkNotNull(prioritizedClusterNames, "prioritizedClusterNames");
1✔
630
      return newBuilder(clusterName)
1✔
631
          .clusterType(ClusterType.AGGREGATE)
1✔
632
          .prioritizedClusterNames(ImmutableList.copyOf(prioritizedClusterNames));
1✔
633
    }
634

635
    static Builder forEds(String clusterName, @Nullable String edsServiceName,
636
                          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
637
                          @Nullable UpstreamTlsContext upstreamTlsContext,
638
                          @Nullable OutlierDetection outlierDetection,
639
                          boolean isHttp11ProxyAvailable) {
640
      return newBuilder(clusterName)
1✔
641
          .clusterType(ClusterType.EDS)
1✔
642
          .edsServiceName(edsServiceName)
1✔
643
          .lrsServerInfo(lrsServerInfo)
1✔
644
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
645
          .upstreamTlsContext(upstreamTlsContext)
1✔
646
          .outlierDetection(outlierDetection)
1✔
647
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
648
    }
649

650
    static Builder forLogicalDns(String clusterName, String dnsHostName,
651
                                 @Nullable ServerInfo lrsServerInfo,
652
                                 @Nullable Long maxConcurrentRequests,
653
                                 @Nullable UpstreamTlsContext upstreamTlsContext,
654
                                 boolean isHttp11ProxyAvailable) {
655
      return newBuilder(clusterName)
1✔
656
          .clusterType(ClusterType.LOGICAL_DNS)
1✔
657
          .dnsHostName(dnsHostName)
1✔
658
          .lrsServerInfo(lrsServerInfo)
1✔
659
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
660
          .upstreamTlsContext(upstreamTlsContext)
1✔
661
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
662
    }
663

664
    enum ClusterType {
1✔
665
      EDS, LOGICAL_DNS, AGGREGATE
1✔
666
    }
667

668
    enum LbPolicy {
×
669
      ROUND_ROBIN, RING_HASH, LEAST_REQUEST
×
670
    }
671

672
    // FIXME(chengyuanzhang): delete this after UpstreamTlsContext's toString() is fixed.
673
    @Override
674
    public final String toString() {
675
      return MoreObjects.toStringHelper(this)
1✔
676
          .add("clusterName", clusterName())
1✔
677
          .add("clusterType", clusterType())
1✔
678
          .add("lbPolicyConfig", lbPolicyConfig())
1✔
679
          .add("minRingSize", minRingSize())
1✔
680
          .add("maxRingSize", maxRingSize())
1✔
681
          .add("choiceCount", choiceCount())
1✔
682
          .add("edsServiceName", edsServiceName())
1✔
683
          .add("dnsHostName", dnsHostName())
1✔
684
          .add("lrsServerInfo", lrsServerInfo())
1✔
685
          .add("maxConcurrentRequests", maxConcurrentRequests())
1✔
686
          // Exclude upstreamTlsContext and outlierDetection as their string representations are
687
          // cumbersome.
688
          .add("prioritizedClusterNames", prioritizedClusterNames())
1✔
689
          .toString();
1✔
690
    }
691

692
    @AutoValue.Builder
693
    abstract static class Builder {
1✔
694
      // Private, use one of the static factory methods instead.
695
      protected abstract Builder clusterName(String clusterName);
696

697
      // Private, use one of the static factory methods instead.
698
      protected abstract Builder clusterType(ClusterType clusterType);
699

700
      protected abstract Builder lbPolicyConfig(ImmutableMap<String, ?> lbPolicyConfig);
701

702
      Builder roundRobinLbPolicy() {
703
        return this.lbPolicyConfig(ImmutableMap.of("round_robin", ImmutableMap.of()));
1✔
704
      }
705

706
      Builder ringHashLbPolicy(Long minRingSize, Long maxRingSize) {
707
        return this.lbPolicyConfig(ImmutableMap.of("ring_hash_experimental",
×
708
            ImmutableMap.of("minRingSize", minRingSize.doubleValue(), "maxRingSize",
×
709
                maxRingSize.doubleValue())));
×
710
      }
711

712
      Builder leastRequestLbPolicy(Integer choiceCount) {
713
        return this.lbPolicyConfig(ImmutableMap.of("least_request_experimental",
×
714
            ImmutableMap.of("choiceCount", choiceCount.doubleValue())));
×
715
      }
716

717
      // Private, use leastRequestLbPolicy(int).
718
      protected abstract Builder choiceCount(int choiceCount);
719

720
      // Private, use ringHashLbPolicy(long, long).
721
      protected abstract Builder minRingSize(long minRingSize);
722

723
      // Private, use ringHashLbPolicy(long, long).
724
      protected abstract Builder maxRingSize(long maxRingSize);
725

726
      // Private, use CdsUpdate.forEds() instead.
727
      protected abstract Builder edsServiceName(String edsServiceName);
728

729
      // Private, use CdsUpdate.forLogicalDns() instead.
730
      protected abstract Builder dnsHostName(String dnsHostName);
731

732
      // Private, use one of the static factory methods instead.
733
      protected abstract Builder lrsServerInfo(ServerInfo lrsServerInfo);
734

735
      // Private, use one of the static factory methods instead.
736
      protected abstract Builder maxConcurrentRequests(Long maxConcurrentRequests);
737

738
      protected abstract Builder isHttp11ProxyAvailable(boolean isHttp11ProxyAvailable);
739

740
      // Private, use one of the static factory methods instead.
741
      protected abstract Builder upstreamTlsContext(UpstreamTlsContext upstreamTlsContext);
742

743
      // Private, use CdsUpdate.forAggregate() instead.
744
      protected abstract Builder prioritizedClusterNames(List<String> prioritizedClusterNames);
745

746
      protected abstract Builder outlierDetection(OutlierDetection outlierDetection);
747

748
      protected abstract Builder filterMetadata(ImmutableMap<String, Struct> filterMetadata);
749

750
      protected abstract Builder parsedMetadata(ImmutableMap<String, Object> parsedMetadata);
751

752
      abstract CdsUpdate build();
753
    }
754
  }
755
}
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