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

grpc / grpc-java / #19535

30 Oct 2024 03:41PM UTC coverage: 84.572% (-0.005%) from 84.577%
#19535

push

github

web-flow
xds: Per-rpc rewriting of the authority header based on the selected route. (#11631)

Implementation of A81.

33970 of 40167 relevant lines covered (84.57%)

0.85 hits per line

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

94.89
/../xds/src/main/java/io/grpc/xds/XdsNameResolver.java
1
/*
2
 * Copyright 2019 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.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21
import static io.grpc.xds.client.Bootstrapper.XDSTP_SCHEME;
22

23
import com.google.common.annotations.VisibleForTesting;
24
import com.google.common.base.Joiner;
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.common.collect.Sets;
29
import com.google.gson.Gson;
30
import com.google.protobuf.util.Durations;
31
import io.grpc.Attributes;
32
import io.grpc.CallOptions;
33
import io.grpc.Channel;
34
import io.grpc.ClientCall;
35
import io.grpc.ClientInterceptor;
36
import io.grpc.ClientInterceptors;
37
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
38
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
39
import io.grpc.InternalConfigSelector;
40
import io.grpc.InternalLogId;
41
import io.grpc.LoadBalancer.PickSubchannelArgs;
42
import io.grpc.Metadata;
43
import io.grpc.MethodDescriptor;
44
import io.grpc.NameResolver;
45
import io.grpc.Status;
46
import io.grpc.Status.Code;
47
import io.grpc.SynchronizationContext;
48
import io.grpc.internal.GrpcUtil;
49
import io.grpc.internal.ObjectPool;
50
import io.grpc.xds.ClusterSpecifierPlugin.PluginConfig;
51
import io.grpc.xds.Filter.ClientInterceptorBuilder;
52
import io.grpc.xds.Filter.FilterConfig;
53
import io.grpc.xds.Filter.NamedFilterConfig;
54
import io.grpc.xds.RouteLookupServiceClusterSpecifierPlugin.RlsPluginConfig;
55
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
56
import io.grpc.xds.VirtualHost.Route;
57
import io.grpc.xds.VirtualHost.Route.RouteAction;
58
import io.grpc.xds.VirtualHost.Route.RouteAction.ClusterWeight;
59
import io.grpc.xds.VirtualHost.Route.RouteAction.HashPolicy;
60
import io.grpc.xds.VirtualHost.Route.RouteAction.RetryPolicy;
61
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
62
import io.grpc.xds.XdsRouteConfigureResource.RdsUpdate;
63
import io.grpc.xds.client.Bootstrapper.AuthorityInfo;
64
import io.grpc.xds.client.Bootstrapper.BootstrapInfo;
65
import io.grpc.xds.client.XdsClient;
66
import io.grpc.xds.client.XdsClient.ResourceWatcher;
67
import io.grpc.xds.client.XdsLogger;
68
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
69
import java.net.URI;
70
import java.util.ArrayList;
71
import java.util.Collections;
72
import java.util.HashMap;
73
import java.util.HashSet;
74
import java.util.List;
75
import java.util.Locale;
76
import java.util.Map;
77
import java.util.Objects;
78
import java.util.Set;
79
import java.util.concurrent.ConcurrentHashMap;
80
import java.util.concurrent.ConcurrentMap;
81
import java.util.concurrent.ScheduledExecutorService;
82
import java.util.concurrent.atomic.AtomicInteger;
83
import javax.annotation.Nullable;
84

85
/**
86
 * A {@link NameResolver} for resolving gRPC target names with "xds:" scheme.
87
 *
88
 * <p>Resolving a gRPC target involves contacting the control plane management server via xDS
89
 * protocol to retrieve service information and produce a service config to the caller.
90
 *
91
 * @see XdsNameResolverProvider
92
 */
93
final class XdsNameResolver extends NameResolver {
94

95
  static final CallOptions.Key<String> CLUSTER_SELECTION_KEY =
1✔
96
      CallOptions.Key.create("io.grpc.xds.CLUSTER_SELECTION_KEY");
1✔
97
  static final CallOptions.Key<Long> RPC_HASH_KEY =
1✔
98
      CallOptions.Key.create("io.grpc.xds.RPC_HASH_KEY");
1✔
99
  static final CallOptions.Key<Boolean> AUTO_HOST_REWRITE_KEY =
1✔
100
      CallOptions.Key.create("io.grpc.xds.AUTO_HOST_REWRITE_KEY");
1✔
101
  @VisibleForTesting
102
  static boolean enableTimeout =
1✔
103
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"))
1✔
104
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"));
1✔
105

106
  private final InternalLogId logId;
107
  private final XdsLogger logger;
108
  @Nullable
109
  private final String targetAuthority;
110
  private final String target;
111
  private final String serviceAuthority;
112
  // Encoded version of the service authority as per 
113
  // https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.
114
  private final String encodedServiceAuthority;
115
  private final String overrideAuthority;
116
  private final ServiceConfigParser serviceConfigParser;
117
  private final SynchronizationContext syncContext;
118
  private final ScheduledExecutorService scheduler;
119
  private final XdsClientPoolFactory xdsClientPoolFactory;
120
  private final ThreadSafeRandom random;
121
  private final FilterRegistry filterRegistry;
122
  private final XxHash64 hashFunc = XxHash64.INSTANCE;
1✔
123
  // Clusters (with reference counts) to which new/existing requests can be/are routed.
124
  // put()/remove() must be called in SyncContext, and get() can be called in any thread.
125
  private final ConcurrentMap<String, ClusterRefState> clusterRefs = new ConcurrentHashMap<>();
1✔
126
  private final ConfigSelector configSelector = new ConfigSelector();
1✔
127
  private final long randomChannelId;
128

129
  private volatile RoutingConfig routingConfig = RoutingConfig.empty;
1✔
130
  private Listener2 listener;
131
  private ObjectPool<XdsClient> xdsClientPool;
132
  private XdsClient xdsClient;
133
  private CallCounterProvider callCounterProvider;
134
  private ResolveState resolveState;
135
  // Workaround for https://github.com/grpc/grpc-java/issues/8886 . This should be handled in
136
  // XdsClient instead of here.
137
  private boolean receivedConfig;
138

139
  XdsNameResolver(
140
      URI targetUri, String name, @Nullable String overrideAuthority,
141
      ServiceConfigParser serviceConfigParser,
142
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
143
      @Nullable Map<String, ?> bootstrapOverride) {
144
    this(targetUri, targetUri.getAuthority(), name, overrideAuthority, serviceConfigParser,
1✔
145
        syncContext, scheduler, SharedXdsClientPoolProvider.getDefaultProvider(),
1✔
146
        ThreadSafeRandomImpl.instance, FilterRegistry.getDefaultRegistry(), bootstrapOverride);
1✔
147
  }
1✔
148

149
  @VisibleForTesting
150
  XdsNameResolver(
151
      URI targetUri, @Nullable String targetAuthority, String name,
152
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
153
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
154
      XdsClientPoolFactory xdsClientPoolFactory, ThreadSafeRandom random,
155
      FilterRegistry filterRegistry, @Nullable Map<String, ?> bootstrapOverride) {
1✔
156
    this.targetAuthority = targetAuthority;
1✔
157
    target = targetUri.toString();
1✔
158

159
    // The name might have multiple slashes so encode it before verifying.
160
    serviceAuthority = checkNotNull(name, "name");
1✔
161
    this.encodedServiceAuthority = 
1✔
162
      GrpcUtil.checkAuthority(GrpcUtil.AuthorityEscaper.encodeAuthority(serviceAuthority));
1✔
163

164
    this.overrideAuthority = overrideAuthority;
1✔
165
    this.serviceConfigParser = checkNotNull(serviceConfigParser, "serviceConfigParser");
1✔
166
    this.syncContext = checkNotNull(syncContext, "syncContext");
1✔
167
    this.scheduler = checkNotNull(scheduler, "scheduler");
1✔
168
    this.xdsClientPoolFactory = bootstrapOverride == null ? checkNotNull(xdsClientPoolFactory,
1✔
169
            "xdsClientPoolFactory") : new SharedXdsClientPoolProvider();
1✔
170
    this.xdsClientPoolFactory.setBootstrapOverride(bootstrapOverride);
1✔
171
    this.random = checkNotNull(random, "random");
1✔
172
    this.filterRegistry = checkNotNull(filterRegistry, "filterRegistry");
1✔
173
    randomChannelId = random.nextLong();
1✔
174
    logId = InternalLogId.allocate("xds-resolver", name);
1✔
175
    logger = XdsLogger.withLogId(logId);
1✔
176
    logger.log(XdsLogLevel.INFO, "Created resolver for {0}", name);
1✔
177
  }
1✔
178

179
  @Override
180
  public String getServiceAuthority() {
181
    return encodedServiceAuthority;
1✔
182
  }
183

184
  @Override
185
  public void start(Listener2 listener) {
186
    this.listener = checkNotNull(listener, "listener");
1✔
187
    try {
188
      xdsClientPool = xdsClientPoolFactory.getOrCreate(target);
1✔
189
    } catch (Exception e) {
1✔
190
      listener.onError(
1✔
191
          Status.UNAVAILABLE.withDescription("Failed to initialize xDS").withCause(e));
1✔
192
      return;
1✔
193
    }
1✔
194
    xdsClient = xdsClientPool.getObject();
1✔
195
    BootstrapInfo bootstrapInfo = xdsClient.getBootstrapInfo();
1✔
196
    String listenerNameTemplate;
197
    if (targetAuthority == null) {
1✔
198
      listenerNameTemplate = bootstrapInfo.clientDefaultListenerResourceNameTemplate();
1✔
199
    } else {
200
      AuthorityInfo authorityInfo = bootstrapInfo.authorities().get(targetAuthority);
1✔
201
      if (authorityInfo == null) {
1✔
202
        listener.onError(Status.INVALID_ARGUMENT.withDescription(
1✔
203
            "invalid target URI: target authority not found in the bootstrap"));
204
        return;
1✔
205
      }
206
      listenerNameTemplate = authorityInfo.clientListenerResourceNameTemplate();
1✔
207
    }
208
    String replacement = serviceAuthority;
1✔
209
    if (listenerNameTemplate.startsWith(XDSTP_SCHEME)) {
1✔
210
      replacement = XdsClient.percentEncodePath(replacement);
1✔
211
    }
212
    String ldsResourceName = expandPercentS(listenerNameTemplate, replacement);
1✔
213
    if (!XdsClient.isResourceNameValid(ldsResourceName, XdsListenerResource.getInstance().typeUrl())
1✔
214
        ) {
215
      listener.onError(Status.INVALID_ARGUMENT.withDescription(
×
216
          "invalid listener resource URI for service authority: " + serviceAuthority));
217
      return;
×
218
    }
219
    ldsResourceName = XdsClient.canonifyResourceName(ldsResourceName);
1✔
220
    callCounterProvider = SharedCallCounterMap.getInstance();
1✔
221
    resolveState = new ResolveState(ldsResourceName);
1✔
222

223
    resolveState.start();
1✔
224
  }
1✔
225

226
  private static String expandPercentS(String template, String replacement) {
227
    return template.replace("%s", replacement);
1✔
228
  }
229

230
  @Override
231
  public void shutdown() {
232
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
233
    if (resolveState != null) {
1✔
234
      resolveState.stop();
1✔
235
    }
236
    if (xdsClient != null) {
1✔
237
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
238
    }
239
  }
1✔
240

241
  @VisibleForTesting
242
  static Map<String, ?> generateServiceConfigWithMethodConfig(
243
      @Nullable Long timeoutNano, @Nullable RetryPolicy retryPolicy) {
244
    if (timeoutNano == null
1✔
245
        && (retryPolicy == null || retryPolicy.retryableStatusCodes().isEmpty())) {
1✔
246
      return Collections.emptyMap();
1✔
247
    }
248
    ImmutableMap.Builder<String, Object> methodConfig = ImmutableMap.builder();
1✔
249
    methodConfig.put(
1✔
250
        "name", Collections.singletonList(Collections.emptyMap()));
1✔
251
    if (retryPolicy != null && !retryPolicy.retryableStatusCodes().isEmpty()) {
1✔
252
      ImmutableMap.Builder<String, Object> rawRetryPolicy = ImmutableMap.builder();
1✔
253
      rawRetryPolicy.put("maxAttempts", (double) retryPolicy.maxAttempts());
1✔
254
      rawRetryPolicy.put("initialBackoff", Durations.toString(retryPolicy.initialBackoff()));
1✔
255
      rawRetryPolicy.put("maxBackoff", Durations.toString(retryPolicy.maxBackoff()));
1✔
256
      rawRetryPolicy.put("backoffMultiplier", 2D);
1✔
257
      List<String> codes = new ArrayList<>(retryPolicy.retryableStatusCodes().size());
1✔
258
      for (Code code : retryPolicy.retryableStatusCodes()) {
1✔
259
        codes.add(code.name());
1✔
260
      }
1✔
261
      rawRetryPolicy.put(
1✔
262
          "retryableStatusCodes", Collections.unmodifiableList(codes));
1✔
263
      if (retryPolicy.perAttemptRecvTimeout() != null) {
1✔
264
        rawRetryPolicy.put(
×
265
            "perAttemptRecvTimeout", Durations.toString(retryPolicy.perAttemptRecvTimeout()));
×
266
      }
267
      methodConfig.put("retryPolicy", rawRetryPolicy.buildOrThrow());
1✔
268
    }
269
    if (timeoutNano != null) {
1✔
270
      String timeout = timeoutNano / 1_000_000_000.0 + "s";
1✔
271
      methodConfig.put("timeout", timeout);
1✔
272
    }
273
    return Collections.singletonMap(
1✔
274
        "methodConfig", Collections.singletonList(methodConfig.buildOrThrow()));
1✔
275
  }
276

277
  @VisibleForTesting
278
  XdsClient getXdsClient() {
279
    return xdsClient;
1✔
280
  }
281

282
  // called in syncContext
283
  private void updateResolutionResult() {
284
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
285

286
    ImmutableMap.Builder<String, Object> childPolicy = new ImmutableMap.Builder<>();
1✔
287
    for (String name : clusterRefs.keySet()) {
1✔
288
      Map<String, ?> lbPolicy = clusterRefs.get(name).toLbPolicy();
1✔
289
      childPolicy.put(name, ImmutableMap.of("lbPolicy", ImmutableList.of(lbPolicy)));
1✔
290
    }
1✔
291
    Map<String, ?> rawServiceConfig = ImmutableMap.of(
1✔
292
        "loadBalancingConfig",
293
        ImmutableList.of(ImmutableMap.of(
1✔
294
            XdsLbPolicies.CLUSTER_MANAGER_POLICY_NAME,
295
            ImmutableMap.of("childPolicy", childPolicy.buildOrThrow()))));
1✔
296

297
    if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
298
      logger.log(
×
299
          XdsLogLevel.INFO, "Generated service config:\n{0}", new Gson().toJson(rawServiceConfig));
×
300
    }
301
    ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
302
    Attributes attrs =
303
        Attributes.newBuilder()
1✔
304
            .set(InternalXdsAttributes.XDS_CLIENT_POOL, xdsClientPool)
1✔
305
            .set(InternalXdsAttributes.CALL_COUNTER_PROVIDER, callCounterProvider)
1✔
306
            .set(InternalConfigSelector.KEY, configSelector)
1✔
307
            .build();
1✔
308
    ResolutionResult result =
309
        ResolutionResult.newBuilder()
1✔
310
            .setAttributes(attrs)
1✔
311
            .setServiceConfig(parsedServiceConfig)
1✔
312
            .build();
1✔
313
    listener.onResult(result);
1✔
314
    receivedConfig = true;
1✔
315
  }
1✔
316

317
  /**
318
   * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern} with
319
   * case-insensitive.
320
   *
321
   * <p>Wildcard pattern rules:
322
   * <ol>
323
   * <li>A single asterisk (*) matches any domain.</li>
324
   * <li>Asterisk (*) is only permitted in the left-most or the right-most part of the pattern,
325
   *     but not both.</li>
326
   * </ol>
327
   */
328
  @VisibleForTesting
329
  static boolean matchHostName(String hostName, String pattern) {
330
    checkArgument(hostName.length() != 0 && !hostName.startsWith(".") && !hostName.endsWith("."),
1✔
331
        "Invalid host name");
332
    checkArgument(pattern.length() != 0 && !pattern.startsWith(".") && !pattern.endsWith("."),
1✔
333
        "Invalid pattern/domain name");
334

335
    hostName = hostName.toLowerCase(Locale.US);
1✔
336
    pattern = pattern.toLowerCase(Locale.US);
1✔
337
    // hostName and pattern are now in lower case -- domain names are case-insensitive.
338

339
    if (!pattern.contains("*")) {
1✔
340
      // Not a wildcard pattern -- hostName and pattern must match exactly.
341
      return hostName.equals(pattern);
1✔
342
    }
343
    // Wildcard pattern
344

345
    if (pattern.length() == 1) {
1✔
346
      return true;
×
347
    }
348

349
    int index = pattern.indexOf('*');
1✔
350

351
    // At most one asterisk (*) is allowed.
352
    if (pattern.indexOf('*', index + 1) != -1) {
1✔
353
      return false;
×
354
    }
355

356
    // Asterisk can only match prefix or suffix.
357
    if (index != 0 && index != pattern.length() - 1) {
1✔
358
      return false;
×
359
    }
360

361
    // HostName must be at least as long as the pattern because asterisk has to
362
    // match one or more characters.
363
    if (hostName.length() < pattern.length()) {
1✔
364
      return false;
1✔
365
    }
366

367
    if (index == 0 && hostName.endsWith(pattern.substring(1))) {
1✔
368
      // Prefix matching fails.
369
      return true;
1✔
370
    }
371

372
    // Pattern matches hostname if suffix matching succeeds.
373
    return index == pattern.length() - 1
1✔
374
        && hostName.startsWith(pattern.substring(0, pattern.length() - 1));
1✔
375
  }
376

377
  private final class ConfigSelector extends InternalConfigSelector {
1✔
378
    @Override
379
    public Result selectConfig(PickSubchannelArgs args) {
380
      String cluster = null;
1✔
381
      Route selectedRoute = null;
1✔
382
      RoutingConfig routingCfg;
383
      Map<String, FilterConfig> selectedOverrideConfigs;
384
      List<ClientInterceptor> filterInterceptors = new ArrayList<>();
1✔
385
      Metadata headers = args.getHeaders();
1✔
386
      do {
387
        routingCfg = routingConfig;
1✔
388
        selectedOverrideConfigs = new HashMap<>(routingCfg.virtualHostOverrideConfig);
1✔
389
        for (Route route : routingCfg.routes) {
1✔
390
          if (RoutingUtils.matchRoute(
1✔
391
                  route.routeMatch(), "/" + args.getMethodDescriptor().getFullMethodName(),
1✔
392
              headers, random)) {
1✔
393
            selectedRoute = route;
1✔
394
            selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
395
            break;
1✔
396
          }
397
        }
1✔
398
        if (selectedRoute == null) {
1✔
399
          return Result.forError(
1✔
400
              Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"));
1✔
401
        }
402
        if (selectedRoute.routeAction() == null) {
1✔
403
          return Result.forError(Status.UNAVAILABLE.withDescription(
1✔
404
              "Could not route RPC to Route with non-forwarding action"));
405
        }
406
        RouteAction action = selectedRoute.routeAction();
1✔
407
        if (action.cluster() != null) {
1✔
408
          cluster = prefixedClusterName(action.cluster());
1✔
409
        } else if (action.weightedClusters() != null) {
1✔
410
          long totalWeight = 0;
1✔
411
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
412
            totalWeight += weightedCluster.weight();
1✔
413
          }
1✔
414
          long select = random.nextLong(totalWeight);
1✔
415
          long accumulator = 0;
1✔
416
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
417
            accumulator += weightedCluster.weight();
1✔
418
            if (select < accumulator) {
1✔
419
              cluster = prefixedClusterName(weightedCluster.name());
1✔
420
              selectedOverrideConfigs.putAll(weightedCluster.filterConfigOverrides());
1✔
421
              break;
1✔
422
            }
423
          }
1✔
424
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
425
          cluster =
1✔
426
              prefixedClusterSpecifierPluginName(action.namedClusterSpecifierPluginConfig().name());
1✔
427
        }
428
      } while (!retainCluster(cluster));
1✔
429
      Long timeoutNanos = null;
1✔
430
      if (enableTimeout) {
1✔
431
        if (selectedRoute != null) {
1✔
432
          timeoutNanos = selectedRoute.routeAction().timeoutNano();
1✔
433
        }
434
        if (timeoutNanos == null) {
1✔
435
          timeoutNanos = routingCfg.fallbackTimeoutNano;
1✔
436
        }
437
        if (timeoutNanos <= 0) {
1✔
438
          timeoutNanos = null;
1✔
439
        }
440
      }
441
      RetryPolicy retryPolicy =
442
          selectedRoute == null ? null : selectedRoute.routeAction().retryPolicy();
1✔
443
      // TODO(chengyuanzhang): avoid service config generation and parsing for each call.
444
      Map<String, ?> rawServiceConfig =
1✔
445
          generateServiceConfigWithMethodConfig(timeoutNanos, retryPolicy);
1✔
446
      ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
447
      Object config = parsedServiceConfig.getConfig();
1✔
448
      if (config == null) {
1✔
449
        releaseCluster(cluster);
×
450
        return Result.forError(
×
451
            parsedServiceConfig.getError().augmentDescription(
×
452
                "Failed to parse service config (method config)"));
453
      }
454
      if (routingCfg.filterChain != null) {
1✔
455
        for (NamedFilterConfig namedFilter : routingCfg.filterChain) {
1✔
456
          FilterConfig filterConfig = namedFilter.filterConfig;
1✔
457
          Filter filter = filterRegistry.get(filterConfig.typeUrl());
1✔
458
          if (filter instanceof ClientInterceptorBuilder) {
1✔
459
            ClientInterceptor interceptor = ((ClientInterceptorBuilder) filter)
1✔
460
                .buildClientInterceptor(
1✔
461
                    filterConfig, selectedOverrideConfigs.get(namedFilter.name),
1✔
462
                    args, scheduler);
1✔
463
            if (interceptor != null) {
1✔
464
              filterInterceptors.add(interceptor);
1✔
465
            }
466
          }
467
        }
1✔
468
      }
469
      final String finalCluster = cluster;
1✔
470
      final long hash = generateHash(selectedRoute.routeAction().hashPolicies(), headers);
1✔
471
      Route finalSelectedRoute = selectedRoute;
1✔
472
      class ClusterSelectionInterceptor implements ClientInterceptor {
1✔
473
        @Override
474
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
475
            final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
476
            final Channel next) {
477
          CallOptions callOptionsForCluster =
1✔
478
              callOptions.withOption(CLUSTER_SELECTION_KEY, finalCluster)
1✔
479
                  .withOption(RPC_HASH_KEY, hash);
1✔
480
          if (finalSelectedRoute.routeAction().autoHostRewrite()) {
1✔
481
            callOptionsForCluster = callOptionsForCluster.withOption(AUTO_HOST_REWRITE_KEY, true);
1✔
482
          }
483
          return new SimpleForwardingClientCall<ReqT, RespT>(
1✔
484
              next.newCall(method, callOptionsForCluster)) {
1✔
485
            @Override
486
            public void start(Listener<RespT> listener, Metadata headers) {
487
              listener = new SimpleForwardingClientCallListener<RespT>(listener) {
1✔
488
                boolean committed;
489

490
                @Override
491
                public void onHeaders(Metadata headers) {
492
                  committed = true;
1✔
493
                  releaseCluster(finalCluster);
1✔
494
                  delegate().onHeaders(headers);
1✔
495
                }
1✔
496

497
                @Override
498
                public void onClose(Status status, Metadata trailers) {
499
                  if (!committed) {
1✔
500
                    releaseCluster(finalCluster);
1✔
501
                  }
502
                  delegate().onClose(status, trailers);
1✔
503
                }
1✔
504
              };
505
              delegate().start(listener, headers);
1✔
506
            }
1✔
507
          };
508
        }
509
      }
510

511
      filterInterceptors.add(new ClusterSelectionInterceptor());
1✔
512
      return
1✔
513
          Result.newBuilder()
1✔
514
              .setConfig(config)
1✔
515
              .setInterceptor(combineInterceptors(filterInterceptors))
1✔
516
              .build();
1✔
517
    }
518

519
    private boolean retainCluster(String cluster) {
520
      ClusterRefState clusterRefState = clusterRefs.get(cluster);
1✔
521
      if (clusterRefState == null) {
1✔
522
        return false;
×
523
      }
524
      AtomicInteger refCount = clusterRefState.refCount;
1✔
525
      int count;
526
      do {
527
        count = refCount.get();
1✔
528
        if (count == 0) {
1✔
529
          return false;
×
530
        }
531
      } while (!refCount.compareAndSet(count, count + 1));
1✔
532
      return true;
1✔
533
    }
534

535
    private void releaseCluster(final String cluster) {
536
      int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
537
      if (count == 0) {
1✔
538
        syncContext.execute(new Runnable() {
1✔
539
          @Override
540
          public void run() {
541
            if (clusterRefs.get(cluster).refCount.get() == 0) {
1✔
542
              clusterRefs.remove(cluster);
1✔
543
              updateResolutionResult();
1✔
544
            }
545
          }
1✔
546
        });
547
      }
548
    }
1✔
549

550
    private long generateHash(List<HashPolicy> hashPolicies, Metadata headers) {
551
      Long hash = null;
1✔
552
      for (HashPolicy policy : hashPolicies) {
1✔
553
        Long newHash = null;
1✔
554
        if (policy.type() == HashPolicy.Type.HEADER) {
1✔
555
          String value = getHeaderValue(headers, policy.headerName());
1✔
556
          if (value != null) {
1✔
557
            if (policy.regEx() != null && policy.regExSubstitution() != null) {
1✔
558
              value = policy.regEx().matcher(value).replaceAll(policy.regExSubstitution());
1✔
559
            }
560
            newHash = hashFunc.hashAsciiString(value);
1✔
561
          }
562
        } else if (policy.type() == HashPolicy.Type.CHANNEL_ID) {
1✔
563
          newHash = hashFunc.hashLong(randomChannelId);
1✔
564
        }
565
        if (newHash != null ) {
1✔
566
          // Rotating the old value prevents duplicate hash rules from cancelling each other out
567
          // and preserves all of the entropy.
568
          long oldHash = hash != null ? ((hash << 1L) | (hash >> 63L)) : 0;
1✔
569
          hash = oldHash ^ newHash;
1✔
570
        }
571
        // If the policy is a terminal policy and a hash has been generated, ignore
572
        // the rest of the hash policies.
573
        if (policy.isTerminal() && hash != null) {
1✔
574
          break;
×
575
        }
576
      }
1✔
577
      return hash == null ? random.nextLong() : hash;
1✔
578
    }
579
  }
580

581
  private static ClientInterceptor combineInterceptors(final List<ClientInterceptor> interceptors) {
582
    checkArgument(!interceptors.isEmpty(), "empty interceptors");
1✔
583
    if (interceptors.size() == 1) {
1✔
584
      return interceptors.get(0);
1✔
585
    }
586
    return new ClientInterceptor() {
1✔
587
      @Override
588
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
589
          MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
590
        next = ClientInterceptors.interceptForward(next, interceptors);
1✔
591
        return next.newCall(method, callOptions);
1✔
592
      }
593
    };
594
  }
595

596
  @Nullable
597
  private static String getHeaderValue(Metadata headers, String headerName) {
598
    if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
1✔
599
      return null;
×
600
    }
601
    if (headerName.equals("content-type")) {
1✔
602
      return "application/grpc";
×
603
    }
604
    Metadata.Key<String> key;
605
    try {
606
      key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
1✔
607
    } catch (IllegalArgumentException e) {
×
608
      return null;
×
609
    }
1✔
610
    Iterable<String> values = headers.getAll(key);
1✔
611
    return values == null ? null : Joiner.on(",").join(values);
1✔
612
  }
613

614
  private static String prefixedClusterName(String name) {
615
    return "cluster:" + name;
1✔
616
  }
617

618
  private static String prefixedClusterSpecifierPluginName(String pluginName) {
619
    return "cluster_specifier_plugin:" + pluginName;
1✔
620
  }
621

622
  private static final class FailingConfigSelector extends InternalConfigSelector {
623
    private final Result result;
624

625
    public FailingConfigSelector(Status error) {
1✔
626
      this.result = Result.forError(error);
1✔
627
    }
1✔
628

629
    @Override
630
    public Result selectConfig(PickSubchannelArgs args) {
631
      return result;
1✔
632
    }
633
  }
634

635
  private class ResolveState implements ResourceWatcher<XdsListenerResource.LdsUpdate> {
636
    private final ConfigOrError emptyServiceConfig =
1✔
637
        serviceConfigParser.parseServiceConfig(Collections.<String, Object>emptyMap());
1✔
638
    private final String ldsResourceName;
639
    private boolean stopped;
640
    @Nullable
641
    private Set<String> existingClusters;  // clusters to which new requests can be routed
642
    @Nullable
643
    private RouteDiscoveryState routeDiscoveryState;
644

645
    ResolveState(String ldsResourceName) {
1✔
646
      this.ldsResourceName = ldsResourceName;
1✔
647
    }
1✔
648

649
    @Override
650
    public void onChanged(final XdsListenerResource.LdsUpdate update) {
651
      if (stopped) {
1✔
652
        return;
×
653
      }
654
      logger.log(XdsLogLevel.INFO, "Receive LDS resource update: {0}", update);
1✔
655
      HttpConnectionManager httpConnectionManager = update.httpConnectionManager();
1✔
656
      List<VirtualHost> virtualHosts = httpConnectionManager.virtualHosts();
1✔
657
      String rdsName = httpConnectionManager.rdsName();
1✔
658
      cleanUpRouteDiscoveryState();
1✔
659
      if (virtualHosts != null) {
1✔
660
        updateRoutes(virtualHosts, httpConnectionManager.httpMaxStreamDurationNano(),
1✔
661
            httpConnectionManager.httpFilterConfigs());
1✔
662
      } else {
663
        routeDiscoveryState = new RouteDiscoveryState(
1✔
664
            rdsName, httpConnectionManager.httpMaxStreamDurationNano(),
1✔
665
            httpConnectionManager.httpFilterConfigs());
1✔
666
        logger.log(XdsLogLevel.INFO, "Start watching RDS resource {0}", rdsName);
1✔
667
        xdsClient.watchXdsResource(XdsRouteConfigureResource.getInstance(),
1✔
668
            rdsName, routeDiscoveryState, syncContext);
1✔
669
      }
670
    }
1✔
671

672
    @Override
673
    public void onError(final Status error) {
674
      if (stopped || receivedConfig) {
1✔
675
        return;
×
676
      }
677
      listener.onError(Status.UNAVAILABLE.withCause(error.getCause()).withDescription(
1✔
678
          String.format("Unable to load LDS %s. xDS server returned: %s: %s",
1✔
679
          ldsResourceName, error.getCode(), error.getDescription())));
1✔
680
    }
1✔
681

682
    @Override
683
    public void onResourceDoesNotExist(final String resourceName) {
684
      if (stopped) {
1✔
685
        return;
×
686
      }
687
      String error = "LDS resource does not exist: " + resourceName;
1✔
688
      logger.log(XdsLogLevel.INFO, error);
1✔
689
      cleanUpRouteDiscoveryState();
1✔
690
      cleanUpRoutes(error);
1✔
691
    }
1✔
692

693
    private void start() {
694
      logger.log(XdsLogLevel.INFO, "Start watching LDS resource {0}", ldsResourceName);
1✔
695
      xdsClient.watchXdsResource(XdsListenerResource.getInstance(),
1✔
696
          ldsResourceName, this, syncContext);
1✔
697
    }
1✔
698

699
    private void stop() {
700
      logger.log(XdsLogLevel.INFO, "Stop watching LDS resource {0}", ldsResourceName);
1✔
701
      stopped = true;
1✔
702
      cleanUpRouteDiscoveryState();
1✔
703
      xdsClient.cancelXdsResourceWatch(XdsListenerResource.getInstance(), ldsResourceName, this);
1✔
704
    }
1✔
705

706
    // called in syncContext
707
    private void updateRoutes(List<VirtualHost> virtualHosts, long httpMaxStreamDurationNano,
708
        @Nullable List<NamedFilterConfig> filterConfigs) {
709
      String authority = overrideAuthority != null ? overrideAuthority : encodedServiceAuthority;
1✔
710
      VirtualHost virtualHost = RoutingUtils.findVirtualHostForHostName(virtualHosts, authority);
1✔
711
      if (virtualHost == null) {
1✔
712
        String error = "Failed to find virtual host matching hostname: " + authority;
1✔
713
        logger.log(XdsLogLevel.WARNING, error);
1✔
714
        cleanUpRoutes(error);
1✔
715
        return;
1✔
716
      }
717

718
      List<Route> routes = virtualHost.routes();
1✔
719

720
      // Populate all clusters to which requests can be routed to through the virtual host.
721
      Set<String> clusters = new HashSet<>();
1✔
722
      // uniqueName -> clusterName
723
      Map<String, String> clusterNameMap = new HashMap<>();
1✔
724
      // uniqueName -> pluginConfig
725
      Map<String, RlsPluginConfig> rlsPluginConfigMap = new HashMap<>();
1✔
726
      for (Route route : routes) {
1✔
727
        RouteAction action = route.routeAction();
1✔
728
        String prefixedName;
729
        if (action != null) {
1✔
730
          if (action.cluster() != null) {
1✔
731
            prefixedName = prefixedClusterName(action.cluster());
1✔
732
            clusters.add(prefixedName);
1✔
733
            clusterNameMap.put(prefixedName, action.cluster());
1✔
734
          } else if (action.weightedClusters() != null) {
1✔
735
            for (ClusterWeight weighedCluster : action.weightedClusters()) {
1✔
736
              prefixedName = prefixedClusterName(weighedCluster.name());
1✔
737
              clusters.add(prefixedName);
1✔
738
              clusterNameMap.put(prefixedName, weighedCluster.name());
1✔
739
            }
1✔
740
          } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
741
            PluginConfig pluginConfig = action.namedClusterSpecifierPluginConfig().config();
1✔
742
            if (pluginConfig instanceof RlsPluginConfig) {
1✔
743
              prefixedName = prefixedClusterSpecifierPluginName(
1✔
744
                  action.namedClusterSpecifierPluginConfig().name());
1✔
745
              clusters.add(prefixedName);
1✔
746
              rlsPluginConfigMap.put(prefixedName, (RlsPluginConfig) pluginConfig);
1✔
747
            }
748
          }
749
        }
750
      }
1✔
751

752
      // Updates channel's load balancing config whenever the set of selectable clusters changes.
753
      boolean shouldUpdateResult = existingClusters == null;
1✔
754
      Set<String> addedClusters =
755
          existingClusters == null ? clusters : Sets.difference(clusters, existingClusters);
1✔
756
      Set<String> deletedClusters =
757
          existingClusters == null
1✔
758
              ? Collections.emptySet() : Sets.difference(existingClusters, clusters);
1✔
759
      existingClusters = clusters;
1✔
760
      for (String cluster : addedClusters) {
1✔
761
        if (clusterRefs.containsKey(cluster)) {
1✔
762
          clusterRefs.get(cluster).refCount.incrementAndGet();
1✔
763
        } else {
764
          if (clusterNameMap.containsKey(cluster)) {
1✔
765
            clusterRefs.put(
1✔
766
                cluster,
767
                ClusterRefState.forCluster(new AtomicInteger(1), clusterNameMap.get(cluster)));
1✔
768
          }
769
          if (rlsPluginConfigMap.containsKey(cluster)) {
1✔
770
            clusterRefs.put(
1✔
771
                cluster,
772
                ClusterRefState.forRlsPlugin(
1✔
773
                    new AtomicInteger(1), rlsPluginConfigMap.get(cluster)));
1✔
774
          }
775
          shouldUpdateResult = true;
1✔
776
        }
777
      }
1✔
778
      for (String cluster : clusters) {
1✔
779
        RlsPluginConfig rlsPluginConfig = rlsPluginConfigMap.get(cluster);
1✔
780
        if (!Objects.equals(rlsPluginConfig, clusterRefs.get(cluster).rlsPluginConfig)) {
1✔
781
          ClusterRefState newClusterRefState =
1✔
782
              ClusterRefState.forRlsPlugin(clusterRefs.get(cluster).refCount, rlsPluginConfig);
1✔
783
          clusterRefs.put(cluster, newClusterRefState);
1✔
784
          shouldUpdateResult = true;
1✔
785
        }
786
      }
1✔
787
      // Update service config to include newly added clusters.
788
      if (shouldUpdateResult) {
1✔
789
        updateResolutionResult();
1✔
790
      }
791
      // Make newly added clusters selectable by config selector and deleted clusters no longer
792
      // selectable.
793
      routingConfig =
1✔
794
          new RoutingConfig(
795
              httpMaxStreamDurationNano, routes, filterConfigs,
796
              virtualHost.filterConfigOverrides());
1✔
797
      shouldUpdateResult = false;
1✔
798
      for (String cluster : deletedClusters) {
1✔
799
        int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
800
        if (count == 0) {
1✔
801
          clusterRefs.remove(cluster);
1✔
802
          shouldUpdateResult = true;
1✔
803
        }
804
      }
1✔
805
      if (shouldUpdateResult) {
1✔
806
        updateResolutionResult();
1✔
807
      }
808
    }
1✔
809

810
    private void cleanUpRoutes(String error) {
811
      if (existingClusters != null) {
1✔
812
        for (String cluster : existingClusters) {
1✔
813
          int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
814
          if (count == 0) {
1✔
815
            clusterRefs.remove(cluster);
1✔
816
          }
817
        }
1✔
818
        existingClusters = null;
1✔
819
      }
820
      routingConfig = RoutingConfig.empty;
1✔
821
      // Without addresses the default LB (normally pick_first) should become TRANSIENT_FAILURE, and
822
      // the config selector handles the error message itself. Once the LB API allows providing
823
      // failure information for addresses yet still providing a service config, the config seector
824
      // could be avoided.
825
      String errorWithNodeId =
1✔
826
          error + ", xDS node ID: " + xdsClient.getBootstrapInfo().node().getId();
1✔
827
      listener.onResult(ResolutionResult.newBuilder()
1✔
828
          .setAttributes(Attributes.newBuilder()
1✔
829
            .set(InternalConfigSelector.KEY,
1✔
830
              new FailingConfigSelector(Status.UNAVAILABLE.withDescription(errorWithNodeId)))
1✔
831
            .build())
1✔
832
          .setServiceConfig(emptyServiceConfig)
1✔
833
          .build());
1✔
834
      receivedConfig = true;
1✔
835
    }
1✔
836

837
    private void cleanUpRouteDiscoveryState() {
838
      if (routeDiscoveryState != null) {
1✔
839
        String rdsName = routeDiscoveryState.resourceName;
1✔
840
        logger.log(XdsLogLevel.INFO, "Stop watching RDS resource {0}", rdsName);
1✔
841
        xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(), rdsName,
1✔
842
            routeDiscoveryState);
843
        routeDiscoveryState = null;
1✔
844
      }
845
    }
1✔
846

847
    /**
848
     * Discovery state for RouteConfiguration resource. One instance for each Listener resource
849
     * update.
850
     */
851
    private class RouteDiscoveryState implements ResourceWatcher<RdsUpdate> {
852
      private final String resourceName;
853
      private final long httpMaxStreamDurationNano;
854
      @Nullable
855
      private final List<NamedFilterConfig> filterConfigs;
856

857
      private RouteDiscoveryState(String resourceName, long httpMaxStreamDurationNano,
858
          @Nullable List<NamedFilterConfig> filterConfigs) {
1✔
859
        this.resourceName = resourceName;
1✔
860
        this.httpMaxStreamDurationNano = httpMaxStreamDurationNano;
1✔
861
        this.filterConfigs = filterConfigs;
1✔
862
      }
1✔
863

864
      @Override
865
      public void onChanged(final RdsUpdate update) {
866
        if (RouteDiscoveryState.this != routeDiscoveryState) {
1✔
867
          return;
×
868
        }
869
        logger.log(XdsLogLevel.INFO, "Received RDS resource update: {0}", update);
1✔
870
        updateRoutes(update.virtualHosts, httpMaxStreamDurationNano, filterConfigs);
1✔
871
      }
1✔
872

873
      @Override
874
      public void onError(final Status error) {
875
        if (RouteDiscoveryState.this != routeDiscoveryState || receivedConfig) {
1✔
876
          return;
×
877
        }
878
        listener.onError(Status.UNAVAILABLE.withCause(error.getCause()).withDescription(
1✔
879
            String.format("Unable to load RDS %s. xDS server returned: %s: %s",
1✔
880
            resourceName, error.getCode(), error.getDescription())));
1✔
881
      }
1✔
882

883
      @Override
884
      public void onResourceDoesNotExist(final String resourceName) {
885
        if (RouteDiscoveryState.this != routeDiscoveryState) {
1✔
886
          return;
×
887
        }
888
        String error = "RDS resource does not exist: " + resourceName;
1✔
889
        logger.log(XdsLogLevel.INFO, error);
1✔
890
        cleanUpRoutes(error);
1✔
891
      }
1✔
892
    }
893
  }
894

895
  /**
896
   * VirtualHost-level configuration for request routing.
897
   */
898
  private static class RoutingConfig {
899
    private final long fallbackTimeoutNano;
900
    final List<Route> routes;
901
    // Null if HttpFilter is not supported.
902
    @Nullable final List<NamedFilterConfig> filterChain;
903
    final Map<String, FilterConfig> virtualHostOverrideConfig;
904

905
    private static RoutingConfig empty = new RoutingConfig(
1✔
906
        0, Collections.emptyList(), null, Collections.emptyMap());
1✔
907

908
    private RoutingConfig(
909
        long fallbackTimeoutNano, List<Route> routes, @Nullable List<NamedFilterConfig> filterChain,
910
        Map<String, FilterConfig> virtualHostOverrideConfig) {
1✔
911
      this.fallbackTimeoutNano = fallbackTimeoutNano;
1✔
912
      this.routes = routes;
1✔
913
      checkArgument(filterChain == null || !filterChain.isEmpty(), "filterChain is empty");
1✔
914
      this.filterChain = filterChain == null ? null : Collections.unmodifiableList(filterChain);
1✔
915
      this.virtualHostOverrideConfig = Collections.unmodifiableMap(virtualHostOverrideConfig);
1✔
916
    }
1✔
917
  }
918

919
  private static class ClusterRefState {
920
    final AtomicInteger refCount;
921
    @Nullable
922
    final String traditionalCluster;
923
    @Nullable
924
    final RlsPluginConfig rlsPluginConfig;
925

926
    private ClusterRefState(
927
        AtomicInteger refCount, @Nullable String traditionalCluster,
928
        @Nullable RlsPluginConfig rlsPluginConfig) {
1✔
929
      this.refCount = refCount;
1✔
930
      checkArgument(traditionalCluster == null ^ rlsPluginConfig == null,
1✔
931
          "There must be exactly one non-null value in traditionalCluster and pluginConfig");
932
      this.traditionalCluster = traditionalCluster;
1✔
933
      this.rlsPluginConfig = rlsPluginConfig;
1✔
934
    }
1✔
935

936
    private Map<String, ?> toLbPolicy() {
937
      if (traditionalCluster != null) {
1✔
938
        return ImmutableMap.of(
1✔
939
            XdsLbPolicies.CDS_POLICY_NAME,
940
            ImmutableMap.of("cluster", traditionalCluster));
1✔
941
      } else {
942
        ImmutableMap<String, ?> rlsConfig = new ImmutableMap.Builder<String, Object>()
1✔
943
            .put("routeLookupConfig", rlsPluginConfig.config())
1✔
944
            .put(
1✔
945
                "childPolicy",
946
                ImmutableList.of(ImmutableMap.of(XdsLbPolicies.CDS_POLICY_NAME, ImmutableMap.of())))
1✔
947
            .put("childPolicyConfigTargetFieldName", "cluster")
1✔
948
            .buildOrThrow();
1✔
949
        return ImmutableMap.of("rls_experimental", rlsConfig);
1✔
950
      }
951
    }
952

953
    static ClusterRefState forCluster(AtomicInteger refCount, String name) {
954
      return new ClusterRefState(refCount, name, null);
1✔
955
    }
956

957
    static ClusterRefState forRlsPlugin(AtomicInteger refCount, RlsPluginConfig rlsPluginConfig) {
958
      return new ClusterRefState(refCount, null, rlsPluginConfig);
1✔
959
    }
960
  }
961
}
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