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

grpc / grpc-java / #19715

06 Mar 2025 08:10AM UTC coverage: 88.479% (-0.04%) from 88.515%
#19715

push

github

web-flow
xds: xDS-based HTTP CONNECT configuration (#11861)

34489 of 38980 relevant lines covered (88.48%)

0.88 hits per line

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

91.61
/../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(System.getProperty("io.grpc.xds.experimentalEnableLeastRequest"));
1✔
64
  @VisibleForTesting
65
  public static boolean enableSystemRootCerts =
1✔
66
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_SYSTEM_ROOT_CERTS", false);
1✔
67
  static boolean isEnabledXdsHttpConnect =
1✔
68
      GrpcUtil.getFlag("GRPC_EXPERIMENTAL_XDS_HTTP_CONNECT", false);
1✔
69

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

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

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

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

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

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

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

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

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

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

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

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

168
    // Validate the LB config by trying to parse it with the corresponding LB provider.
169
    LbConfig lbConfig = ServiceConfigUtil.unwrapLoadBalancingConfig(lbPolicyConfig);
1✔
170
    NameResolver.ConfigOrError configOrError = loadBalancerRegistry.getProvider(
1✔
171
        lbConfig.getPolicyName()).parseLoadBalancingPolicyConfig(
1✔
172
        lbConfig.getRawConfigValue());
1✔
173
    if (configOrError.getError() != null) {
1✔
174
      throw new ResourceInvalidException(structOrError.getErrorDetail());
×
175
    }
176

177
    updateBuilder.lbPolicyConfig(lbPolicyConfig);
1✔
178
    updateBuilder.filterMetadata(
1✔
179
        ImmutableMap.copyOf(cluster.getMetadata().getFilterMetadataMap()));
1✔
180

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

192
    return updateBuilder.build();
1✔
193
  }
194

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

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

248
    if (hasTransportSocket && !TRANSPORT_SOCKET_NAME_TLS.equals(transportSocket.getName())
1✔
249
        && !(isEnabledXdsHttpConnect
250
        && TRANSPORT_SOCKET_NAME_HTTP11_PROXY.equals(transportSocket.getName()))) {
1✔
251
      return StructOrError.fromError(
1✔
252
          "transport-socket with name " + transportSocket.getName() + " not supported.");
1✔
253
    }
254

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

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

289
    if (cluster.hasOutlierDetection()) {
1✔
290
      try {
291
        outlierDetection = OutlierDetection.fromEnvoyOutlierDetection(
1✔
292
            validateOutlierDetection(cluster.getOutlierDetection()));
1✔
293
      } catch (ResourceInvalidException e) {
1✔
294
        return StructOrError.fromError(
1✔
295
            "Cluster " + clusterName + ": malformed outlier_detection: " + e);
296
      }
1✔
297
    }
298

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

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

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

416
    return outlierDetection;
1✔
417
  }
418

419
  static boolean hasNegativeValues(Duration duration) {
420
    return duration.getSeconds() < 0 || duration.getNanos() < 0;
1✔
421
  }
422

423
  @VisibleForTesting
424
  static io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
425
      validateUpstreamTlsContext(
426
      io.envoyproxy.envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext upstreamTlsContext,
427
      Set<String> certProviderInstances)
428
      throws ResourceInvalidException {
429
    if (upstreamTlsContext.hasCommonTlsContext()) {
1✔
430
      validateCommonTlsContext(upstreamTlsContext.getCommonTlsContext(), certProviderInstances,
1✔
431
          false);
432
    } else {
433
      throw new ResourceInvalidException("common-tls-context is required in upstream-tls-context");
1✔
434
    }
435
    return upstreamTlsContext;
1✔
436
  }
437

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

536
  private static String getIdentityCertInstanceName(CommonTlsContext commonTlsContext) {
537
    if (commonTlsContext.hasTlsCertificateProviderInstance()) {
1✔
538
      return commonTlsContext.getTlsCertificateProviderInstance().getInstanceName();
1✔
539
    } else if (commonTlsContext.hasTlsCertificateCertificateProviderInstance()) {
1✔
540
      return commonTlsContext.getTlsCertificateCertificateProviderInstance().getInstanceName();
1✔
541
    }
542
    return null;
1✔
543
  }
544

545
  private static String getRootCertInstanceName(CommonTlsContext commonTlsContext) {
546
    if (commonTlsContext.hasValidationContext()) {
1✔
547
      if (commonTlsContext.getValidationContext().hasCaCertificateProviderInstance()) {
1✔
548
        return commonTlsContext.getValidationContext().getCaCertificateProviderInstance()
1✔
549
            .getInstanceName();
1✔
550
      }
551
    } else if (commonTlsContext.hasCombinedValidationContext()) {
1✔
552
      CommonTlsContext.CombinedCertificateValidationContext combinedCertificateValidationContext
1✔
553
          = commonTlsContext.getCombinedValidationContext();
1✔
554
      if (combinedCertificateValidationContext.hasDefaultValidationContext()
1✔
555
          && combinedCertificateValidationContext.getDefaultValidationContext()
1✔
556
          .hasCaCertificateProviderInstance()) {
1✔
557
        return combinedCertificateValidationContext.getDefaultValidationContext()
×
558
            .getCaCertificateProviderInstance().getInstanceName();
×
559
      } else if (combinedCertificateValidationContext
1✔
560
          .hasValidationContextCertificateProviderInstance()) {
1✔
561
        return combinedCertificateValidationContext
1✔
562
            .getValidationContextCertificateProviderInstance().getInstanceName();
1✔
563
      }
564
    }
565
    return null;
1✔
566
  }
567

568
  /** xDS resource update for cluster-level configuration. */
569
  @AutoValue
570
  abstract static class CdsUpdate implements ResourceUpdate {
1✔
571
    abstract String clusterName();
572

573
    abstract ClusterType clusterType();
574

575
    abstract ImmutableMap<String, ?> lbPolicyConfig();
576

577
    // Only valid if lbPolicy is "ring_hash_experimental".
578
    abstract long minRingSize();
579

580
    // Only valid if lbPolicy is "ring_hash_experimental".
581
    abstract long maxRingSize();
582

583
    // Only valid if lbPolicy is "least_request_experimental".
584
    abstract int choiceCount();
585

586
    // Alternative resource name to be used in EDS requests.
587
    /// Only valid for EDS cluster.
588
    @Nullable
589
    abstract String edsServiceName();
590

591
    // Corresponding DNS name to be used if upstream endpoints of the cluster is resolvable
592
    // via DNS.
593
    // Only valid for LOGICAL_DNS cluster.
594
    @Nullable
595
    abstract String dnsHostName();
596

597
    // Load report server info for reporting loads via LRS.
598
    // Only valid for EDS or LOGICAL_DNS cluster.
599
    @Nullable
600
    abstract ServerInfo lrsServerInfo();
601

602
    // Max number of concurrent requests can be sent to this cluster.
603
    // Only valid for EDS or LOGICAL_DNS cluster.
604
    @Nullable
605
    abstract Long maxConcurrentRequests();
606

607
    // TLS context used to connect to connect to this cluster.
608
    // Only valid for EDS or LOGICAL_DNS cluster.
609
    @Nullable
610
    abstract UpstreamTlsContext upstreamTlsContext();
611

612
    abstract boolean isHttp11ProxyAvailable();
613

614
    // List of underlying clusters making of this aggregate cluster.
615
    // Only valid for AGGREGATE cluster.
616
    @Nullable
617
    abstract ImmutableList<String> prioritizedClusterNames();
618

619
    // Outlier detection configuration.
620
    @Nullable
621
    abstract OutlierDetection outlierDetection();
622

623
    abstract ImmutableMap<String, Struct> filterMetadata();
624

625
    abstract ImmutableMap<String, Object> parsedMetadata();
626

627
    private static Builder newBuilder(String clusterName) {
628
      return new AutoValue_XdsClusterResource_CdsUpdate.Builder()
1✔
629
          .clusterName(clusterName)
1✔
630
          .minRingSize(0)
1✔
631
          .maxRingSize(0)
1✔
632
          .choiceCount(0)
1✔
633
          .filterMetadata(ImmutableMap.of())
1✔
634
          .parsedMetadata(ImmutableMap.of())
1✔
635
          .isHttp11ProxyAvailable(false);
1✔
636
    }
637

638
    static Builder forAggregate(String clusterName, List<String> prioritizedClusterNames) {
639
      checkNotNull(prioritizedClusterNames, "prioritizedClusterNames");
1✔
640
      return newBuilder(clusterName)
1✔
641
          .clusterType(ClusterType.AGGREGATE)
1✔
642
          .prioritizedClusterNames(ImmutableList.copyOf(prioritizedClusterNames));
1✔
643
    }
644

645
    static Builder forEds(String clusterName, @Nullable String edsServiceName,
646
                          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
647
                          @Nullable UpstreamTlsContext upstreamTlsContext,
648
                          @Nullable OutlierDetection outlierDetection,
649
                          boolean isHttp11ProxyAvailable) {
650
      return newBuilder(clusterName)
1✔
651
          .clusterType(ClusterType.EDS)
1✔
652
          .edsServiceName(edsServiceName)
1✔
653
          .lrsServerInfo(lrsServerInfo)
1✔
654
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
655
          .upstreamTlsContext(upstreamTlsContext)
1✔
656
          .outlierDetection(outlierDetection)
1✔
657
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
658
    }
659

660
    static Builder forLogicalDns(String clusterName, String dnsHostName,
661
                                 @Nullable ServerInfo lrsServerInfo,
662
                                 @Nullable Long maxConcurrentRequests,
663
                                 @Nullable UpstreamTlsContext upstreamTlsContext,
664
                                 boolean isHttp11ProxyAvailable) {
665
      return newBuilder(clusterName)
1✔
666
          .clusterType(ClusterType.LOGICAL_DNS)
1✔
667
          .dnsHostName(dnsHostName)
1✔
668
          .lrsServerInfo(lrsServerInfo)
1✔
669
          .maxConcurrentRequests(maxConcurrentRequests)
1✔
670
          .upstreamTlsContext(upstreamTlsContext)
1✔
671
          .isHttp11ProxyAvailable(isHttp11ProxyAvailable);
1✔
672
    }
673

674
    enum ClusterType {
1✔
675
      EDS, LOGICAL_DNS, AGGREGATE
1✔
676
    }
677

678
    enum LbPolicy {
×
679
      ROUND_ROBIN, RING_HASH, LEAST_REQUEST
×
680
    }
681

682
    // FIXME(chengyuanzhang): delete this after UpstreamTlsContext's toString() is fixed.
683
    @Override
684
    public final String toString() {
685
      return MoreObjects.toStringHelper(this)
1✔
686
          .add("clusterName", clusterName())
1✔
687
          .add("clusterType", clusterType())
1✔
688
          .add("lbPolicyConfig", lbPolicyConfig())
1✔
689
          .add("minRingSize", minRingSize())
1✔
690
          .add("maxRingSize", maxRingSize())
1✔
691
          .add("choiceCount", choiceCount())
1✔
692
          .add("edsServiceName", edsServiceName())
1✔
693
          .add("dnsHostName", dnsHostName())
1✔
694
          .add("lrsServerInfo", lrsServerInfo())
1✔
695
          .add("maxConcurrentRequests", maxConcurrentRequests())
1✔
696
          // Exclude upstreamTlsContext and outlierDetection as their string representations are
697
          // cumbersome.
698
          .add("prioritizedClusterNames", prioritizedClusterNames())
1✔
699
          .toString();
1✔
700
    }
701

702
    @AutoValue.Builder
703
    abstract static class Builder {
1✔
704
      // Private, use one of the static factory methods instead.
705
      protected abstract Builder clusterName(String clusterName);
706

707
      // Private, use one of the static factory methods instead.
708
      protected abstract Builder clusterType(ClusterType clusterType);
709

710
      protected abstract Builder lbPolicyConfig(ImmutableMap<String, ?> lbPolicyConfig);
711

712
      Builder roundRobinLbPolicy() {
713
        return this.lbPolicyConfig(ImmutableMap.of("round_robin", ImmutableMap.of()));
1✔
714
      }
715

716
      Builder ringHashLbPolicy(Long minRingSize, Long maxRingSize) {
717
        return this.lbPolicyConfig(ImmutableMap.of("ring_hash_experimental",
1✔
718
            ImmutableMap.of("minRingSize", minRingSize.doubleValue(), "maxRingSize",
1✔
719
                maxRingSize.doubleValue())));
1✔
720
      }
721

722
      Builder leastRequestLbPolicy(Integer choiceCount) {
723
        return this.lbPolicyConfig(ImmutableMap.of("least_request_experimental",
1✔
724
            ImmutableMap.of("choiceCount", choiceCount.doubleValue())));
1✔
725
      }
726

727
      // Private, use leastRequestLbPolicy(int).
728
      protected abstract Builder choiceCount(int choiceCount);
729

730
      // Private, use ringHashLbPolicy(long, long).
731
      protected abstract Builder minRingSize(long minRingSize);
732

733
      // Private, use ringHashLbPolicy(long, long).
734
      protected abstract Builder maxRingSize(long maxRingSize);
735

736
      // Private, use CdsUpdate.forEds() instead.
737
      protected abstract Builder edsServiceName(String edsServiceName);
738

739
      // Private, use CdsUpdate.forLogicalDns() instead.
740
      protected abstract Builder dnsHostName(String dnsHostName);
741

742
      // Private, use one of the static factory methods instead.
743
      protected abstract Builder lrsServerInfo(ServerInfo lrsServerInfo);
744

745
      // Private, use one of the static factory methods instead.
746
      protected abstract Builder maxConcurrentRequests(Long maxConcurrentRequests);
747

748
      protected abstract Builder isHttp11ProxyAvailable(boolean isHttp11ProxyAvailable);
749

750
      // Private, use one of the static factory methods instead.
751
      protected abstract Builder upstreamTlsContext(UpstreamTlsContext upstreamTlsContext);
752

753
      // Private, use CdsUpdate.forAggregate() instead.
754
      protected abstract Builder prioritizedClusterNames(List<String> prioritizedClusterNames);
755

756
      protected abstract Builder outlierDetection(OutlierDetection outlierDetection);
757

758
      protected abstract Builder filterMetadata(ImmutableMap<String, Struct> filterMetadata);
759

760
      protected abstract Builder parsedMetadata(ImmutableMap<String, Object> parsedMetadata);
761

762
      abstract CdsUpdate build();
763
    }
764
  }
765
}
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