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

grpc / grpc-java / #19986

18 Sep 2025 06:08PM UTC coverage: 88.539% (-0.008%) from 88.547%
#19986

push

github

web-flow
xds: Convert ClusterResolverLb to XdsDepManager

No longer need to hard-code pick_first because of gRFC A61.
https://github.com/grpc/proposal/pull/477

34664 of 39151 relevant lines covered (88.54%)

0.89 hits per line

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

93.35
/../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.MetricRecorder;
45
import io.grpc.NameResolver;
46
import io.grpc.Status;
47
import io.grpc.Status.Code;
48
import io.grpc.StatusOr;
49
import io.grpc.SynchronizationContext;
50
import io.grpc.internal.GrpcUtil;
51
import io.grpc.internal.ObjectPool;
52
import io.grpc.xds.ClusterSpecifierPlugin.PluginConfig;
53
import io.grpc.xds.Filter.FilterConfig;
54
import io.grpc.xds.Filter.NamedFilterConfig;
55
import io.grpc.xds.RouteLookupServiceClusterSpecifierPlugin.RlsPluginConfig;
56
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
57
import io.grpc.xds.VirtualHost.Route;
58
import io.grpc.xds.VirtualHost.Route.RouteAction;
59
import io.grpc.xds.VirtualHost.Route.RouteAction.ClusterWeight;
60
import io.grpc.xds.VirtualHost.Route.RouteAction.HashPolicy;
61
import io.grpc.xds.VirtualHost.Route.RouteAction.RetryPolicy;
62
import io.grpc.xds.VirtualHost.Route.RouteMatch;
63
import io.grpc.xds.XdsNameResolverProvider.CallCounterProvider;
64
import io.grpc.xds.client.Bootstrapper.AuthorityInfo;
65
import io.grpc.xds.client.Bootstrapper.BootstrapInfo;
66
import io.grpc.xds.client.XdsClient;
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<XdsConfig> XDS_CONFIG_CALL_OPTION_KEY =
1✔
98
      CallOptions.Key.create("io.grpc.xds.XDS_CONFIG_CALL_OPTION_KEY");
1✔
99
  static final CallOptions.Key<Long> RPC_HASH_KEY =
1✔
100
      CallOptions.Key.create("io.grpc.xds.RPC_HASH_KEY");
1✔
101
  static final CallOptions.Key<Boolean> AUTO_HOST_REWRITE_KEY =
1✔
102
      CallOptions.Key.create("io.grpc.xds.AUTO_HOST_REWRITE_KEY");
1✔
103
  @VisibleForTesting
104
  static boolean enableTimeout =
1✔
105
      Strings.isNullOrEmpty(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"))
1✔
106
          || Boolean.parseBoolean(System.getenv("GRPC_XDS_EXPERIMENTAL_ENABLE_TIMEOUT"));
1✔
107

108
  private final InternalLogId logId;
109
  private final XdsLogger logger;
110
  @Nullable
111
  private final String targetAuthority;
112
  private final String target;
113
  private final String serviceAuthority;
114
  // Encoded version of the service authority as per 
115
  // https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.
116
  private final String encodedServiceAuthority;
117
  private final String overrideAuthority;
118
  private final ServiceConfigParser serviceConfigParser;
119
  private final SynchronizationContext syncContext;
120
  private final ScheduledExecutorService scheduler;
121
  private final XdsClientPoolFactory xdsClientPoolFactory;
122
  private final ThreadSafeRandom random;
123
  private final FilterRegistry filterRegistry;
124
  private final XxHash64 hashFunc = XxHash64.INSTANCE;
1✔
125
  // Clusters (with reference counts) to which new/existing requests can be/are routed.
126
  // put()/remove() must be called in SyncContext, and get() can be called in any thread.
127
  private final ConcurrentMap<String, ClusterRefState> clusterRefs = new ConcurrentHashMap<>();
1✔
128
  private final ConfigSelector configSelector = new ConfigSelector();
1✔
129
  private final long randomChannelId;
130
  private final MetricRecorder metricRecorder;
131
  private final Args nameResolverArgs;
132
  // Must be accessed in syncContext.
133
  // Filter instances are unique per channel, and per filter (name+typeUrl).
134
  // NamedFilterConfig.filterStateKey -> filter_instance.
135
  private final HashMap<String, Filter> activeFilters = new HashMap<>();
1✔
136

137
  private volatile RoutingConfig routingConfig;
138
  private Listener2 listener;
139
  private ObjectPool<XdsClient> xdsClientPool;
140
  private XdsClient xdsClient;
141
  private CallCounterProvider callCounterProvider;
142
  private ResolveState resolveState;
143

144
  XdsNameResolver(
145
      URI targetUri, String name, @Nullable String overrideAuthority,
146
      ServiceConfigParser serviceConfigParser,
147
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
148
      @Nullable Map<String, ?> bootstrapOverride,
149
      MetricRecorder metricRecorder, Args nameResolverArgs) {
150
    this(targetUri, targetUri.getAuthority(), name, overrideAuthority, serviceConfigParser,
1✔
151
        syncContext, scheduler, SharedXdsClientPoolProvider.getDefaultProvider(),
1✔
152
        ThreadSafeRandomImpl.instance, FilterRegistry.getDefaultRegistry(), bootstrapOverride,
1✔
153
        metricRecorder, nameResolverArgs);
154
  }
1✔
155

156
  @VisibleForTesting
157
  XdsNameResolver(
158
      URI targetUri, @Nullable String targetAuthority, String name,
159
      @Nullable String overrideAuthority, ServiceConfigParser serviceConfigParser,
160
      SynchronizationContext syncContext, ScheduledExecutorService scheduler,
161
      XdsClientPoolFactory xdsClientPoolFactory, ThreadSafeRandom random,
162
      FilterRegistry filterRegistry, @Nullable Map<String, ?> bootstrapOverride,
163
      MetricRecorder metricRecorder, Args nameResolverArgs) {
1✔
164
    this.targetAuthority = targetAuthority;
1✔
165
    target = targetUri.toString();
1✔
166

167
    // The name might have multiple slashes so encode it before verifying.
168
    serviceAuthority = checkNotNull(name, "name");
1✔
169
    this.encodedServiceAuthority = 
1✔
170
      GrpcUtil.checkAuthority(GrpcUtil.AuthorityEscaper.encodeAuthority(serviceAuthority));
1✔
171

172
    this.overrideAuthority = overrideAuthority;
1✔
173
    this.serviceConfigParser = checkNotNull(serviceConfigParser, "serviceConfigParser");
1✔
174
    this.syncContext = checkNotNull(syncContext, "syncContext");
1✔
175
    this.scheduler = checkNotNull(scheduler, "scheduler");
1✔
176
    this.xdsClientPoolFactory = bootstrapOverride == null ? checkNotNull(xdsClientPoolFactory,
1✔
177
            "xdsClientPoolFactory") : new SharedXdsClientPoolProvider();
1✔
178
    this.xdsClientPoolFactory.setBootstrapOverride(bootstrapOverride);
1✔
179
    this.random = checkNotNull(random, "random");
1✔
180
    this.filterRegistry = checkNotNull(filterRegistry, "filterRegistry");
1✔
181
    this.metricRecorder = metricRecorder;
1✔
182
    this.nameResolverArgs = checkNotNull(nameResolverArgs, "nameResolverArgs");
1✔
183

184
    randomChannelId = random.nextLong();
1✔
185
    logId = InternalLogId.allocate("xds-resolver", name);
1✔
186
    logger = XdsLogger.withLogId(logId);
1✔
187
    logger.log(XdsLogLevel.INFO, "Created resolver for {0}", name);
1✔
188
  }
1✔
189

190
  @Override
191
  public String getServiceAuthority() {
192
    return encodedServiceAuthority;
1✔
193
  }
194

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

233
    resolveState = new ResolveState(ldsResourceName);
1✔
234
    resolveState.start();
1✔
235
  }
1✔
236

237
  @Override
238
  public void refresh() {
239
    if (resolveState != null) {
×
240
      resolveState.refresh();
×
241
    }
242
  }
×
243

244
  private static String expandPercentS(String template, String replacement) {
245
    return template.replace("%s", replacement);
1✔
246
  }
247

248
  @Override
249
  public void shutdown() {
250
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
251
    if (resolveState != null) {
1✔
252
      resolveState.shutdown();
1✔
253
    }
254
    if (xdsClient != null) {
1✔
255
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
256
    }
257
  }
1✔
258

259
  @VisibleForTesting
260
  static Map<String, ?> generateServiceConfigWithMethodConfig(
261
      @Nullable Long timeoutNano, @Nullable RetryPolicy retryPolicy) {
262
    if (timeoutNano == null
1✔
263
        && (retryPolicy == null || retryPolicy.retryableStatusCodes().isEmpty())) {
1✔
264
      return Collections.emptyMap();
1✔
265
    }
266
    ImmutableMap.Builder<String, Object> methodConfig = ImmutableMap.builder();
1✔
267
    methodConfig.put(
1✔
268
        "name", Collections.singletonList(Collections.emptyMap()));
1✔
269
    if (retryPolicy != null && !retryPolicy.retryableStatusCodes().isEmpty()) {
1✔
270
      ImmutableMap.Builder<String, Object> rawRetryPolicy = ImmutableMap.builder();
1✔
271
      rawRetryPolicy.put("maxAttempts", (double) retryPolicy.maxAttempts());
1✔
272
      rawRetryPolicy.put("initialBackoff", Durations.toString(retryPolicy.initialBackoff()));
1✔
273
      rawRetryPolicy.put("maxBackoff", Durations.toString(retryPolicy.maxBackoff()));
1✔
274
      rawRetryPolicy.put("backoffMultiplier", 2D);
1✔
275
      List<String> codes = new ArrayList<>(retryPolicy.retryableStatusCodes().size());
1✔
276
      for (Code code : retryPolicy.retryableStatusCodes()) {
1✔
277
        codes.add(code.name());
1✔
278
      }
1✔
279
      rawRetryPolicy.put(
1✔
280
          "retryableStatusCodes", Collections.unmodifiableList(codes));
1✔
281
      if (retryPolicy.perAttemptRecvTimeout() != null) {
1✔
282
        rawRetryPolicy.put(
×
283
            "perAttemptRecvTimeout", Durations.toString(retryPolicy.perAttemptRecvTimeout()));
×
284
      }
285
      methodConfig.put("retryPolicy", rawRetryPolicy.buildOrThrow());
1✔
286
    }
287
    if (timeoutNano != null) {
1✔
288
      String timeout = timeoutNano / 1_000_000_000.0 + "s";
1✔
289
      methodConfig.put("timeout", timeout);
1✔
290
    }
291
    return Collections.singletonMap(
1✔
292
        "methodConfig", Collections.singletonList(methodConfig.buildOrThrow()));
1✔
293
  }
294

295
  @VisibleForTesting
296
  XdsClient getXdsClient() {
297
    return xdsClient;
1✔
298
  }
299

300
  // called in syncContext
301
  private void updateResolutionResult(XdsConfig xdsConfig) {
302
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
303

304
    ImmutableMap.Builder<String, Object> childPolicy = new ImmutableMap.Builder<>();
1✔
305
    for (String name : clusterRefs.keySet()) {
1✔
306
      Map<String, ?> lbPolicy = clusterRefs.get(name).toLbPolicy();
1✔
307
      childPolicy.put(name, ImmutableMap.of("lbPolicy", ImmutableList.of(lbPolicy)));
1✔
308
    }
1✔
309
    Map<String, ?> rawServiceConfig = ImmutableMap.of(
1✔
310
        "loadBalancingConfig",
311
        ImmutableList.of(ImmutableMap.of(
1✔
312
            XdsLbPolicies.CLUSTER_MANAGER_POLICY_NAME,
313
            ImmutableMap.of("childPolicy", childPolicy.buildOrThrow()))));
1✔
314

315
    if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
316
      logger.log(
×
317
          XdsLogLevel.INFO, "Generated service config: {0}", new Gson().toJson(rawServiceConfig));
×
318
    }
319
    ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
320
    Attributes attrs =
321
        Attributes.newBuilder()
1✔
322
            .set(XdsAttributes.XDS_CLIENT_POOL, xdsClientPool)
1✔
323
            .set(XdsAttributes.XDS_CONFIG, xdsConfig)
1✔
324
            .set(XdsAttributes.XDS_CLUSTER_SUBSCRIPT_REGISTRY, resolveState.xdsDependencyManager)
1✔
325
            .set(XdsAttributes.CALL_COUNTER_PROVIDER, callCounterProvider)
1✔
326
            .set(InternalConfigSelector.KEY, configSelector)
1✔
327
            .build();
1✔
328
    ResolutionResult result =
329
        ResolutionResult.newBuilder()
1✔
330
            .setAttributes(attrs)
1✔
331
            .setServiceConfig(parsedServiceConfig)
1✔
332
            .build();
1✔
333
    if (!listener.onResult2(result).isOk()) {
1✔
334
      // TODO: check if this is right
335
      resolveState.xdsDependencyManager.requestReresolution();
×
336
    }
337
  }
1✔
338

339
  /**
340
   * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern} with
341
   * case-insensitive.
342
   *
343
   * <p>Wildcard pattern rules:
344
   * <ol>
345
   * <li>A single asterisk (*) matches any domain.</li>
346
   * <li>Asterisk (*) is only permitted in the left-most or the right-most part of the pattern,
347
   *     but not both.</li>
348
   * </ol>
349
   */
350
  @VisibleForTesting
351
  static boolean matchHostName(String hostName, String pattern) {
352
    checkArgument(hostName.length() != 0 && !hostName.startsWith(".") && !hostName.endsWith("."),
1✔
353
        "Invalid host name");
354
    checkArgument(pattern.length() != 0 && !pattern.startsWith(".") && !pattern.endsWith("."),
1✔
355
        "Invalid pattern/domain name");
356

357
    hostName = hostName.toLowerCase(Locale.US);
1✔
358
    pattern = pattern.toLowerCase(Locale.US);
1✔
359
    // hostName and pattern are now in lower case -- domain names are case-insensitive.
360

361
    if (!pattern.contains("*")) {
1✔
362
      // Not a wildcard pattern -- hostName and pattern must match exactly.
363
      return hostName.equals(pattern);
1✔
364
    }
365
    // Wildcard pattern
366

367
    if (pattern.length() == 1) {
1✔
368
      return true;
×
369
    }
370

371
    int index = pattern.indexOf('*');
1✔
372

373
    // At most one asterisk (*) is allowed.
374
    if (pattern.indexOf('*', index + 1) != -1) {
1✔
375
      return false;
×
376
    }
377

378
    // Asterisk can only match prefix or suffix.
379
    if (index != 0 && index != pattern.length() - 1) {
1✔
380
      return false;
×
381
    }
382

383
    // HostName must be at least as long as the pattern because asterisk has to
384
    // match one or more characters.
385
    if (hostName.length() < pattern.length()) {
1✔
386
      return false;
1✔
387
    }
388

389
    if (index == 0 && hostName.endsWith(pattern.substring(1))) {
1✔
390
      // Prefix matching fails.
391
      return true;
1✔
392
    }
393

394
    // Pattern matches hostname if suffix matching succeeds.
395
    return index == pattern.length() - 1
1✔
396
        && hostName.startsWith(pattern.substring(0, pattern.length() - 1));
1✔
397
  }
398

399
  private final class ConfigSelector extends InternalConfigSelector {
1✔
400
    @Override
401
    public Result selectConfig(PickSubchannelArgs args) {
402
      RoutingConfig routingCfg;
403
      RouteData selectedRoute;
404
      String cluster;
405
      ClientInterceptor filters;
406
      Metadata headers = args.getHeaders();
1✔
407
      String path = "/" + args.getMethodDescriptor().getFullMethodName();
1✔
408
      do {
409
        routingCfg = routingConfig;
1✔
410
        if (routingCfg.errorStatus != null) {
1✔
411
          return Result.forError(routingCfg.errorStatus);
1✔
412
        }
413
        selectedRoute = null;
1✔
414
        for (RouteData route : routingCfg.routes) {
1✔
415
          if (RoutingUtils.matchRoute(route.routeMatch, path, headers, random)) {
1✔
416
            selectedRoute = route;
1✔
417
            break;
1✔
418
          }
419
        }
1✔
420
        if (selectedRoute == null) {
1✔
421
          return Result.forError(
1✔
422
              Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"));
1✔
423
        }
424
        if (selectedRoute.routeAction == null) {
1✔
425
          return Result.forError(Status.UNAVAILABLE.withDescription(
1✔
426
              "Could not route RPC to Route with non-forwarding action"));
427
        }
428
        RouteAction action = selectedRoute.routeAction;
1✔
429
        if (action.cluster() != null) {
1✔
430
          cluster = prefixedClusterName(action.cluster());
1✔
431
          filters = selectedRoute.filterChoices.get(0);
1✔
432
        } else if (action.weightedClusters() != null) {
1✔
433
          // XdsRouteConfigureResource verifies the total weight will not be 0 or exceed uint32
434
          long totalWeight = 0;
1✔
435
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
436
            totalWeight += weightedCluster.weight();
1✔
437
          }
1✔
438
          long select = random.nextLong(totalWeight);
1✔
439
          long accumulator = 0;
1✔
440
          for (int i = 0; ; i++) {
1✔
441
            ClusterWeight weightedCluster = action.weightedClusters().get(i);
1✔
442
            accumulator += weightedCluster.weight();
1✔
443
            if (select < accumulator) {
1✔
444
              cluster = prefixedClusterName(weightedCluster.name());
1✔
445
              filters = selectedRoute.filterChoices.get(i);
1✔
446
              break;
1✔
447
            }
448
          }
449
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
450
          cluster =
1✔
451
              prefixedClusterSpecifierPluginName(action.namedClusterSpecifierPluginConfig().name());
1✔
452
          filters = selectedRoute.filterChoices.get(0);
1✔
453
        } else {
454
          // updateRoutes() discards routes with unknown actions
455
          throw new AssertionError();
×
456
        }
457
      } while (!retainCluster(cluster));
1✔
458

459
      final RouteAction routeAction = selectedRoute.routeAction;
1✔
460
      Long timeoutNanos = null;
1✔
461
      if (enableTimeout) {
1✔
462
        timeoutNanos = routeAction.timeoutNano();
1✔
463
        if (timeoutNanos == null) {
1✔
464
          timeoutNanos = routingCfg.fallbackTimeoutNano;
1✔
465
        }
466
        if (timeoutNanos <= 0) {
1✔
467
          timeoutNanos = null;
1✔
468
        }
469
      }
470
      RetryPolicy retryPolicy = routeAction.retryPolicy();
1✔
471
      // TODO(chengyuanzhang): avoid service config generation and parsing for each call.
472
      Map<String, ?> rawServiceConfig =
1✔
473
          generateServiceConfigWithMethodConfig(timeoutNanos, retryPolicy);
1✔
474
      ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
475
      Object config = parsedServiceConfig.getConfig();
1✔
476
      if (config == null) {
1✔
477
        releaseCluster(cluster);
×
478
        return Result.forError(
×
479
            parsedServiceConfig.getError().augmentDescription(
×
480
                "Failed to parse service config (method config)"));
481
      }
482
      final String finalCluster = cluster;
1✔
483
      final XdsConfig xdsConfig = routingCfg.xdsConfig;
1✔
484
      final long hash = generateHash(routeAction.hashPolicies(), headers);
1✔
485
      class ClusterSelectionInterceptor implements ClientInterceptor {
1✔
486
        @Override
487
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
488
            final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
489
            final Channel next) {
490
          CallOptions callOptionsForCluster =
1✔
491
              callOptions.withOption(CLUSTER_SELECTION_KEY, finalCluster)
1✔
492
                  .withOption(XDS_CONFIG_CALL_OPTION_KEY, xdsConfig)
1✔
493
                  .withOption(RPC_HASH_KEY, hash);
1✔
494
          if (routeAction.autoHostRewrite()) {
1✔
495
            callOptionsForCluster = callOptionsForCluster.withOption(AUTO_HOST_REWRITE_KEY, true);
1✔
496
          }
497
          return new SimpleForwardingClientCall<ReqT, RespT>(
1✔
498
              next.newCall(method, callOptionsForCluster)) {
1✔
499
            @Override
500
            public void start(Listener<RespT> listener, Metadata headers) {
501
              listener = new SimpleForwardingClientCallListener<RespT>(listener) {
1✔
502
                boolean committed;
503

504
                @Override
505
                public void onHeaders(Metadata headers) {
506
                  committed = true;
1✔
507
                  releaseCluster(finalCluster);
1✔
508
                  delegate().onHeaders(headers);
1✔
509
                }
1✔
510

511
                @Override
512
                public void onClose(Status status, Metadata trailers) {
513
                  if (!committed) {
1✔
514
                    releaseCluster(finalCluster);
1✔
515
                  }
516
                  delegate().onClose(status, trailers);
1✔
517
                }
1✔
518
              };
519
              delegate().start(listener, headers);
1✔
520
            }
1✔
521
          };
522
        }
523
      }
524

525
      return
1✔
526
          Result.newBuilder()
1✔
527
              .setConfig(config)
1✔
528
              .setInterceptor(combineInterceptors(
1✔
529
                  ImmutableList.of(filters, new ClusterSelectionInterceptor())))
1✔
530
              .build();
1✔
531
    }
532

533
    private boolean retainCluster(String cluster) {
534
      ClusterRefState clusterRefState = clusterRefs.get(cluster);
1✔
535
      if (clusterRefState == null) {
1✔
536
        return false;
×
537
      }
538
      AtomicInteger refCount = clusterRefState.refCount;
1✔
539
      int count;
540
      do {
541
        count = refCount.get();
1✔
542
        if (count == 0) {
1✔
543
          return false;
×
544
        }
545
      } while (!refCount.compareAndSet(count, count + 1));
1✔
546
      return true;
1✔
547
    }
548

549
    private void releaseCluster(final String cluster) {
550
      int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
551
      if (count < 0) {
1✔
552
        throw new AssertionError();
×
553
      }
554
      if (count == 0) {
1✔
555
        syncContext.execute(new Runnable() {
1✔
556
          @Override
557
          public void run() {
558
            if (clusterRefs.get(cluster).refCount.get() != 0) {
1✔
559
              throw new AssertionError();
×
560
            }
561
            clusterRefs.remove(cluster).close();
1✔
562
            if (resolveState.lastConfigOrStatus.hasValue()) {
1✔
563
              updateResolutionResult(resolveState.lastConfigOrStatus.getValue());
1✔
564
            } else {
565
              resolveState.cleanUpRoutes(resolveState.lastConfigOrStatus.getStatus());
×
566
            }
567
          }
1✔
568
        });
569
      }
570
    }
1✔
571

572
    private long generateHash(List<HashPolicy> hashPolicies, Metadata headers) {
573
      Long hash = null;
1✔
574
      for (HashPolicy policy : hashPolicies) {
1✔
575
        Long newHash = null;
1✔
576
        if (policy.type() == HashPolicy.Type.HEADER) {
1✔
577
          String value = getHeaderValue(headers, policy.headerName());
1✔
578
          if (value != null) {
1✔
579
            if (policy.regEx() != null && policy.regExSubstitution() != null) {
1✔
580
              value = policy.regEx().matcher(value).replaceAll(policy.regExSubstitution());
1✔
581
            }
582
            newHash = hashFunc.hashAsciiString(value);
1✔
583
          }
584
        } else if (policy.type() == HashPolicy.Type.CHANNEL_ID) {
1✔
585
          newHash = hashFunc.hashLong(randomChannelId);
1✔
586
        }
587
        if (newHash != null ) {
1✔
588
          // Rotating the old value prevents duplicate hash rules from cancelling each other out
589
          // and preserves all of the entropy.
590
          long oldHash = hash != null ? ((hash << 1L) | (hash >> 63L)) : 0;
1✔
591
          hash = oldHash ^ newHash;
1✔
592
        }
593
        // If the policy is a terminal policy and a hash has been generated, ignore
594
        // the rest of the hash policies.
595
        if (policy.isTerminal() && hash != null) {
1✔
596
          break;
×
597
        }
598
      }
1✔
599
      return hash == null ? random.nextLong() : hash;
1✔
600
    }
601
  }
602

603
  static final class PassthroughClientInterceptor implements ClientInterceptor {
1✔
604
    @Override
605
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
606
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
607
      return next.newCall(method, callOptions);
1✔
608
    }
609
  }
610

611
  private static ClientInterceptor combineInterceptors(final List<ClientInterceptor> interceptors) {
612
    if (interceptors.size() == 0) {
1✔
613
      return new PassthroughClientInterceptor();
1✔
614
    }
615
    if (interceptors.size() == 1) {
1✔
616
      return interceptors.get(0);
1✔
617
    }
618
    return new ClientInterceptor() {
1✔
619
      @Override
620
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
621
          MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
622
        next = ClientInterceptors.interceptForward(next, interceptors);
1✔
623
        return next.newCall(method, callOptions);
1✔
624
      }
625
    };
626
  }
627

628
  @Nullable
629
  private static String getHeaderValue(Metadata headers, String headerName) {
630
    if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
1✔
631
      return null;
×
632
    }
633
    if (headerName.equals("content-type")) {
1✔
634
      return "application/grpc";
×
635
    }
636
    Metadata.Key<String> key;
637
    try {
638
      key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
1✔
639
    } catch (IllegalArgumentException e) {
×
640
      return null;
×
641
    }
1✔
642
    Iterable<String> values = headers.getAll(key);
1✔
643
    return values == null ? null : Joiner.on(",").join(values);
1✔
644
  }
645

646
  private static String prefixedClusterName(String name) {
647
    return "cluster:" + name;
1✔
648
  }
649

650
  private static String prefixedClusterSpecifierPluginName(String pluginName) {
651
    return "cluster_specifier_plugin:" + pluginName;
1✔
652
  }
653

654
  class ResolveState implements XdsDependencyManager.XdsConfigWatcher {
1✔
655
    private final ConfigOrError emptyServiceConfig =
1✔
656
        serviceConfigParser.parseServiceConfig(Collections.<String, Object>emptyMap());
1✔
657
    private final String authority;
658
    private final XdsDependencyManager xdsDependencyManager;
659
    private boolean stopped;
660
    @Nullable
661
    private Set<String> existingClusters;  // clusters to which new requests can be routed
662
    private StatusOr<XdsConfig> lastConfigOrStatus;
663

664
    private ResolveState(String ldsResourceName) {
1✔
665
      authority = overrideAuthority != null ? overrideAuthority : encodedServiceAuthority;
1✔
666
      xdsDependencyManager =
1✔
667
          new XdsDependencyManager(xdsClient, syncContext, authority, ldsResourceName,
1✔
668
              nameResolverArgs);
1✔
669
    }
1✔
670

671
    void start() {
672
      xdsDependencyManager.start(this);
1✔
673
    }
1✔
674

675
    void refresh() {
676
      xdsDependencyManager.requestReresolution();
×
677
    }
×
678

679
    private void shutdown() {
680
      if (stopped) {
1✔
681
        return;
×
682
      }
683

684
      stopped = true;
1✔
685
      xdsDependencyManager.shutdown();
1✔
686
      updateActiveFilters(null);
1✔
687
    }
1✔
688

689
    @Override
690
    public void onUpdate(StatusOr<XdsConfig> updateOrStatus) {
691
      if (stopped) {
1✔
692
        return;
×
693
      }
694
      logger.log(XdsLogLevel.INFO, "Receive XDS resource update: {0}", updateOrStatus);
1✔
695

696
      lastConfigOrStatus = updateOrStatus;
1✔
697
      if (!updateOrStatus.hasValue()) {
1✔
698
        updateActiveFilters(null);
1✔
699
        cleanUpRoutes(updateOrStatus.getStatus());
1✔
700
        return;
1✔
701
      }
702

703
      // Process Route
704
      XdsConfig update = updateOrStatus.getValue();
1✔
705
      HttpConnectionManager httpConnectionManager = update.getListener().httpConnectionManager();
1✔
706
      if (httpConnectionManager == null) {
1✔
707
        logger.log(XdsLogLevel.INFO, "API Listener: httpConnectionManager does not exist.");
×
708
        updateActiveFilters(null);
×
709
        cleanUpRoutes(updateOrStatus.getStatus());
×
710
        return;
×
711
      }
712

713
      VirtualHost virtualHost = update.getVirtualHost();
1✔
714
      ImmutableList<NamedFilterConfig> filterConfigs = httpConnectionManager.httpFilterConfigs();
1✔
715
      long streamDurationNano = httpConnectionManager.httpMaxStreamDurationNano();
1✔
716

717
      updateActiveFilters(filterConfigs);
1✔
718
      updateRoutes(update, virtualHost, streamDurationNano, filterConfigs);
1✔
719
    }
1✔
720

721
    // called in syncContext
722
    private void updateActiveFilters(@Nullable List<NamedFilterConfig> filterConfigs) {
723
      if (filterConfigs == null) {
1✔
724
        filterConfigs = ImmutableList.of();
1✔
725
      }
726
      Set<String> filtersToShutdown = new HashSet<>(activeFilters.keySet());
1✔
727
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
728
        String typeUrl = namedFilter.filterConfig.typeUrl();
1✔
729
        String filterKey = namedFilter.filterStateKey();
1✔
730

731
        Filter.Provider provider = filterRegistry.get(typeUrl);
1✔
732
        checkNotNull(provider, "provider %s", typeUrl);
1✔
733
        Filter filter = activeFilters.computeIfAbsent(
1✔
734
            filterKey, k -> provider.newInstance(namedFilter.name));
1✔
735
        checkNotNull(filter, "filter %s", filterKey);
1✔
736
        filtersToShutdown.remove(filterKey);
1✔
737
      }
1✔
738

739
      // Shutdown filters not present in current HCM.
740
      for (String filterKey : filtersToShutdown) {
1✔
741
        Filter filterToShutdown = activeFilters.remove(filterKey);
1✔
742
        checkNotNull(filterToShutdown, "filterToShutdown %s", filterKey);
1✔
743
        filterToShutdown.close();
1✔
744
      }
1✔
745
    }
1✔
746

747
    private void updateRoutes(
748
        XdsConfig xdsConfig,
749
        @Nullable VirtualHost virtualHost,
750
        long httpMaxStreamDurationNano,
751
        @Nullable List<NamedFilterConfig> filterConfigs) {
752
      List<Route> routes = virtualHost.routes();
1✔
753
      ImmutableList.Builder<RouteData> routesData = ImmutableList.builder();
1✔
754

755
      // Populate all clusters to which requests can be routed to through the virtual host.
756
      Set<String> clusters = new HashSet<>();
1✔
757
      // uniqueName -> clusterName
758
      Map<String, String> clusterNameMap = new HashMap<>();
1✔
759
      // uniqueName -> pluginConfig
760
      Map<String, RlsPluginConfig> rlsPluginConfigMap = new HashMap<>();
1✔
761
      for (Route route : routes) {
1✔
762
        RouteAction action = route.routeAction();
1✔
763
        String prefixedName;
764
        if (action == null) {
1✔
765
          routesData.add(new RouteData(route.routeMatch(), null, ImmutableList.of()));
1✔
766
        } else if (action.cluster() != null) {
1✔
767
          prefixedName = prefixedClusterName(action.cluster());
1✔
768
          clusters.add(prefixedName);
1✔
769
          clusterNameMap.put(prefixedName, action.cluster());
1✔
770
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
771
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
772
        } else if (action.weightedClusters() != null) {
1✔
773
          ImmutableList.Builder<ClientInterceptor> filterList = ImmutableList.builder();
1✔
774
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
775
            prefixedName = prefixedClusterName(weightedCluster.name());
1✔
776
            clusters.add(prefixedName);
1✔
777
            clusterNameMap.put(prefixedName, weightedCluster.name());
1✔
778
            filterList.add(createFilters(filterConfigs, virtualHost, route, weightedCluster));
1✔
779
          }
1✔
780
          routesData.add(
1✔
781
              new RouteData(route.routeMatch(), route.routeAction(), filterList.build()));
1✔
782
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
783
          PluginConfig pluginConfig = action.namedClusterSpecifierPluginConfig().config();
1✔
784
          if (pluginConfig instanceof RlsPluginConfig) {
1✔
785
            prefixedName = prefixedClusterSpecifierPluginName(
1✔
786
                action.namedClusterSpecifierPluginConfig().name());
1✔
787
            clusters.add(prefixedName);
1✔
788
            rlsPluginConfigMap.put(prefixedName, (RlsPluginConfig) pluginConfig);
1✔
789
          }
790
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
791
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
792
        } else {
793
          // Discard route
794
        }
795
      }
1✔
796

797
      // Updates channel's load balancing config whenever the set of selectable clusters changes.
798
      boolean shouldUpdateResult = existingClusters == null;
1✔
799
      Set<String> addedClusters =
800
          existingClusters == null ? clusters : Sets.difference(clusters, existingClusters);
1✔
801
      Set<String> deletedClusters =
802
          existingClusters == null
1✔
803
              ? Collections.emptySet() : Sets.difference(existingClusters, clusters);
1✔
804
      existingClusters = clusters;
1✔
805
      for (String cluster : addedClusters) {
1✔
806
        if (clusterRefs.containsKey(cluster)) {
1✔
807
          clusterRefs.get(cluster).refCount.incrementAndGet();
1✔
808
        } else {
809
          if (clusterNameMap.containsKey(cluster)) {
1✔
810
            assert cluster.startsWith("cluster:");
1✔
811
            XdsConfig.Subscription subscription =
1✔
812
                xdsDependencyManager.subscribeToCluster(cluster.substring("cluster:".length()));
1✔
813
            clusterRefs.put(
1✔
814
                cluster,
815
                ClusterRefState.forCluster(
1✔
816
                    new AtomicInteger(1), clusterNameMap.get(cluster), subscription));
1✔
817
          }
818
          if (rlsPluginConfigMap.containsKey(cluster)) {
1✔
819
            clusterRefs.put(
1✔
820
                cluster,
821
                ClusterRefState.forRlsPlugin(
1✔
822
                    new AtomicInteger(1), rlsPluginConfigMap.get(cluster)));
1✔
823
          }
824
          shouldUpdateResult = true;
1✔
825
        }
826
      }
1✔
827
      for (String cluster : clusters) {
1✔
828
        RlsPluginConfig rlsPluginConfig = rlsPluginConfigMap.get(cluster);
1✔
829
        if (!Objects.equals(rlsPluginConfig, clusterRefs.get(cluster).rlsPluginConfig)) {
1✔
830
          ClusterRefState newClusterRefState =
1✔
831
              ClusterRefState.forRlsPlugin(clusterRefs.get(cluster).refCount, rlsPluginConfig);
1✔
832
          clusterRefs.put(cluster, newClusterRefState);
1✔
833
          shouldUpdateResult = true;
1✔
834
        }
835
      }
1✔
836
      // Update service config to include newly added clusters.
837
      if (shouldUpdateResult && routingConfig != null) {
1✔
838
        updateResolutionResult(xdsConfig);
1✔
839
        shouldUpdateResult = false;
1✔
840
      } else {
841
        // Need to update at least once
842
        shouldUpdateResult = true;
1✔
843
      }
844
      // Make newly added clusters selectable by config selector and deleted clusters no longer
845
      // selectable.
846
      routingConfig = new RoutingConfig(xdsConfig, httpMaxStreamDurationNano, routesData.build());
1✔
847
      for (String cluster : deletedClusters) {
1✔
848
        int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
849
        if (count == 0) {
1✔
850
          clusterRefs.remove(cluster).close();
1✔
851
          shouldUpdateResult = true;
1✔
852
        }
853
      }
1✔
854
      if (shouldUpdateResult) {
1✔
855
        updateResolutionResult(xdsConfig);
1✔
856
      }
857
    }
1✔
858

859
    private ClientInterceptor createFilters(
860
        @Nullable List<NamedFilterConfig> filterConfigs,
861
        VirtualHost virtualHost,
862
        Route route,
863
        @Nullable ClusterWeight weightedCluster) {
864
      if (filterConfigs == null) {
1✔
865
        return new PassthroughClientInterceptor();
1✔
866
      }
867

868
      Map<String, FilterConfig> selectedOverrideConfigs =
1✔
869
          new HashMap<>(virtualHost.filterConfigOverrides());
1✔
870
      selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
871
      if (weightedCluster != null) {
1✔
872
        selectedOverrideConfigs.putAll(weightedCluster.filterConfigOverrides());
1✔
873
      }
874

875
      ImmutableList.Builder<ClientInterceptor> filterInterceptors = ImmutableList.builder();
1✔
876
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
877
        String name = namedFilter.name;
1✔
878
        FilterConfig config = namedFilter.filterConfig;
1✔
879
        FilterConfig overrideConfig = selectedOverrideConfigs.get(name);
1✔
880
        String filterKey = namedFilter.filterStateKey();
1✔
881

882
        Filter filter = activeFilters.get(filterKey);
1✔
883
        checkNotNull(filter, "activeFilters.get(%s)", filterKey);
1✔
884
        ClientInterceptor interceptor =
1✔
885
            filter.buildClientInterceptor(config, overrideConfig, scheduler);
1✔
886

887
        if (interceptor != null) {
1✔
888
          filterInterceptors.add(interceptor);
1✔
889
        }
890
      }
1✔
891

892
      // Combine interceptors produced by different filters into a single one that executes
893
      // them sequentially. The order is preserved.
894
      return combineInterceptors(filterInterceptors.build());
1✔
895
    }
896

897
    private void cleanUpRoutes(Status error) {
898
      routingConfig = new RoutingConfig(error);
1✔
899
      if (existingClusters != null) {
1✔
900
        for (String cluster : existingClusters) {
1✔
901
          int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
902
          if (count == 0) {
1✔
903
            clusterRefs.remove(cluster).close();
1✔
904
          }
905
        }
1✔
906
        existingClusters = null;
1✔
907
      }
908

909
      // Without addresses the default LB (normally pick_first) should become TRANSIENT_FAILURE, and
910
      // the config selector handles the error message itself.
911
      listener.onResult2(ResolutionResult.newBuilder()
1✔
912
          .setAttributes(Attributes.newBuilder()
1✔
913
            .set(InternalConfigSelector.KEY, configSelector)
1✔
914
            .build())
1✔
915
          .setServiceConfig(emptyServiceConfig)
1✔
916
          .build());
1✔
917
    }
1✔
918
  }
919

920
  /**
921
   * VirtualHost-level configuration for request routing.
922
   */
923
  private static class RoutingConfig {
924
    final XdsConfig xdsConfig;
925
    final long fallbackTimeoutNano;
926
    final ImmutableList<RouteData> routes;
927
    final Status errorStatus;
928

929
    private RoutingConfig(
930
        XdsConfig xdsConfig, long fallbackTimeoutNano, ImmutableList<RouteData> routes) {
1✔
931
      this.xdsConfig = checkNotNull(xdsConfig, "xdsConfig");
1✔
932
      this.fallbackTimeoutNano = fallbackTimeoutNano;
1✔
933
      this.routes = checkNotNull(routes, "routes");
1✔
934
      this.errorStatus = null;
1✔
935
    }
1✔
936

937
    private RoutingConfig(Status errorStatus) {
1✔
938
      this.xdsConfig = null;
1✔
939
      this.fallbackTimeoutNano = 0;
1✔
940
      this.routes = null;
1✔
941
      this.errorStatus = checkNotNull(errorStatus, "errorStatus");
1✔
942
      checkArgument(!errorStatus.isOk(), "errorStatus should not be okay");
1✔
943
    }
1✔
944
  }
945

946
  static final class RouteData {
947
    final RouteMatch routeMatch;
948
    /** null implies non-forwarding action. */
949
    @Nullable
950
    final RouteAction routeAction;
951
    /**
952
     * Only one of these interceptors should be used per-RPC. There are only multiple values in the
953
     * list for weighted clusters, in which case the order of the list mirrors the weighted
954
     * clusters.
955
     */
956
    final ImmutableList<ClientInterceptor> filterChoices;
957

958
    RouteData(RouteMatch routeMatch, @Nullable RouteAction routeAction, ClientInterceptor filter) {
959
      this(routeMatch, routeAction, ImmutableList.of(filter));
1✔
960
    }
1✔
961

962
    RouteData(
963
        RouteMatch routeMatch,
964
        @Nullable RouteAction routeAction,
965
        ImmutableList<ClientInterceptor> filterChoices) {
1✔
966
      this.routeMatch = checkNotNull(routeMatch, "routeMatch");
1✔
967
      checkArgument(
1✔
968
          routeAction == null || !filterChoices.isEmpty(),
1✔
969
          "filter may be empty only for non-forwarding action");
970
      this.routeAction = routeAction;
1✔
971
      if (routeAction != null && routeAction.weightedClusters() != null) {
1✔
972
        checkArgument(
1✔
973
            routeAction.weightedClusters().size() == filterChoices.size(),
1✔
974
            "filter choices must match size of weighted clusters");
975
      }
976
      for (ClientInterceptor filter : filterChoices) {
1✔
977
        checkNotNull(filter, "entry in filterChoices is null");
1✔
978
      }
1✔
979
      this.filterChoices = checkNotNull(filterChoices, "filterChoices");
1✔
980
    }
1✔
981
  }
982

983
  private static class ClusterRefState {
984
    final AtomicInteger refCount;
985
    @Nullable
986
    final String traditionalCluster;
987
    @Nullable
988
    final RlsPluginConfig rlsPluginConfig;
989
    @Nullable
990
    final XdsConfig.Subscription subscription;
991

992
    private ClusterRefState(
993
        AtomicInteger refCount, @Nullable String traditionalCluster,
994
        @Nullable RlsPluginConfig rlsPluginConfig, @Nullable XdsConfig.Subscription subscription) {
1✔
995
      this.refCount = refCount;
1✔
996
      checkArgument(traditionalCluster == null ^ rlsPluginConfig == null,
1✔
997
          "There must be exactly one non-null value in traditionalCluster and pluginConfig");
998
      this.traditionalCluster = traditionalCluster;
1✔
999
      this.rlsPluginConfig = rlsPluginConfig;
1✔
1000
      this.subscription = subscription;
1✔
1001
    }
1✔
1002

1003
    private Map<String, ?> toLbPolicy() {
1004
      if (traditionalCluster != null) {
1✔
1005
        return ImmutableMap.of(
1✔
1006
            XdsLbPolicies.CDS_POLICY_NAME,
1007
            ImmutableMap.of("cluster", traditionalCluster));
1✔
1008
      } else {
1009
        ImmutableMap<String, ?> rlsConfig = new ImmutableMap.Builder<String, Object>()
1✔
1010
            .put("routeLookupConfig", rlsPluginConfig.config())
1✔
1011
            .put(
1✔
1012
                "childPolicy",
1013
                ImmutableList.of(ImmutableMap.of(XdsLbPolicies.CDS_POLICY_NAME, ImmutableMap.of(
1✔
1014
                    "is_dynamic", true))))
1✔
1015
            .put("childPolicyConfigTargetFieldName", "cluster")
1✔
1016
            .buildOrThrow();
1✔
1017
        return ImmutableMap.of("rls_experimental", rlsConfig);
1✔
1018
      }
1019
    }
1020

1021
    private void close() {
1022
      if (subscription != null) {
1✔
1023
        subscription.close();
1✔
1024
      }
1025
    }
1✔
1026

1027
    static ClusterRefState forCluster(
1028
        AtomicInteger refCount, String name, XdsConfig.Subscription subscription) {
1029
      return new ClusterRefState(refCount, name, null, checkNotNull(subscription, "subscription"));
1✔
1030
    }
1031

1032
    static ClusterRefState forRlsPlugin(
1033
        AtomicInteger refCount,
1034
        RlsPluginConfig rlsPluginConfig) {
1035
      return new ClusterRefState(refCount, null, rlsPluginConfig, null);
1✔
1036
    }
1037
  }
1038
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc