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

grpc / grpc-java / #19858

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

push

github

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

34613 of 39064 relevant lines covered (88.61%)

0.89 hits per line

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

94.3
/../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
  private static String expandPercentS(String template, String replacement) {
238
    return template.replace("%s", replacement);
1✔
239
  }
240

241
  @Override
242
  public void shutdown() {
243
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
244
    if (resolveState != null) {
1✔
245
      resolveState.shutdown();
1✔
246
    }
247
    if (xdsClient != null) {
1✔
248
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
249
    }
250
  }
1✔
251

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

288
  @VisibleForTesting
289
  XdsClient getXdsClient() {
290
    return xdsClient;
1✔
291
  }
292

293
  // called in syncContext
294
  private void updateResolutionResult(XdsConfig xdsConfig) {
295
    syncContext.throwIfNotInThisSynchronizationContext();
1✔
296

297
    ImmutableMap.Builder<String, Object> childPolicy = new ImmutableMap.Builder<>();
1✔
298
    for (String name : clusterRefs.keySet()) {
1✔
299
      Map<String, ?> lbPolicy = clusterRefs.get(name).toLbPolicy();
1✔
300
      childPolicy.put(name, ImmutableMap.of("lbPolicy", ImmutableList.of(lbPolicy)));
1✔
301
    }
1✔
302
    Map<String, ?> rawServiceConfig = ImmutableMap.of(
1✔
303
        "loadBalancingConfig",
304
        ImmutableList.of(ImmutableMap.of(
1✔
305
            XdsLbPolicies.CLUSTER_MANAGER_POLICY_NAME,
306
            ImmutableMap.of("childPolicy", childPolicy.buildOrThrow()))));
1✔
307

308
    if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
309
      logger.log(
×
310
          XdsLogLevel.INFO, "Generated service config: {0}", new Gson().toJson(rawServiceConfig));
×
311
    }
312
    ConfigOrError parsedServiceConfig = serviceConfigParser.parseServiceConfig(rawServiceConfig);
1✔
313
    Attributes attrs =
314
        Attributes.newBuilder()
1✔
315
            .set(XdsAttributes.XDS_CLIENT_POOL, xdsClientPool)
1✔
316
            .set(XdsAttributes.XDS_CONFIG, xdsConfig)
1✔
317
            .set(XdsAttributes.XDS_CLUSTER_SUBSCRIPT_REGISTRY, resolveState.xdsDependencyManager)
1✔
318
            .set(XdsAttributes.CALL_COUNTER_PROVIDER, callCounterProvider)
1✔
319
            .set(InternalConfigSelector.KEY, configSelector)
1✔
320
            .build();
1✔
321
    ResolutionResult result =
322
        ResolutionResult.newBuilder()
1✔
323
            .setAttributes(attrs)
1✔
324
            .setServiceConfig(parsedServiceConfig)
1✔
325
            .build();
1✔
326
    listener.onResult2(result);
1✔
327
  }
1✔
328

329
  /**
330
   * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern} with
331
   * case-insensitive.
332
   *
333
   * <p>Wildcard pattern rules:
334
   * <ol>
335
   * <li>A single asterisk (*) matches any domain.</li>
336
   * <li>Asterisk (*) is only permitted in the left-most or the right-most part of the pattern,
337
   *     but not both.</li>
338
   * </ol>
339
   */
340
  @VisibleForTesting
341
  static boolean matchHostName(String hostName, String pattern) {
342
    checkArgument(hostName.length() != 0 && !hostName.startsWith(".") && !hostName.endsWith("."),
1✔
343
        "Invalid host name");
344
    checkArgument(pattern.length() != 0 && !pattern.startsWith(".") && !pattern.endsWith("."),
1✔
345
        "Invalid pattern/domain name");
346

347
    hostName = hostName.toLowerCase(Locale.US);
1✔
348
    pattern = pattern.toLowerCase(Locale.US);
1✔
349
    // hostName and pattern are now in lower case -- domain names are case-insensitive.
350

351
    if (!pattern.contains("*")) {
1✔
352
      // Not a wildcard pattern -- hostName and pattern must match exactly.
353
      return hostName.equals(pattern);
1✔
354
    }
355
    // Wildcard pattern
356

357
    if (pattern.length() == 1) {
1✔
358
      return true;
×
359
    }
360

361
    int index = pattern.indexOf('*');
1✔
362

363
    // At most one asterisk (*) is allowed.
364
    if (pattern.indexOf('*', index + 1) != -1) {
1✔
365
      return false;
×
366
    }
367

368
    // Asterisk can only match prefix or suffix.
369
    if (index != 0 && index != pattern.length() - 1) {
1✔
370
      return false;
×
371
    }
372

373
    // HostName must be at least as long as the pattern because asterisk has to
374
    // match one or more characters.
375
    if (hostName.length() < pattern.length()) {
1✔
376
      return false;
1✔
377
    }
378

379
    if (index == 0 && hostName.endsWith(pattern.substring(1))) {
1✔
380
      // Prefix matching fails.
381
      return true;
1✔
382
    }
383

384
    // Pattern matches hostname if suffix matching succeeds.
385
    return index == pattern.length() - 1
1✔
386
        && hostName.startsWith(pattern.substring(0, pattern.length() - 1));
1✔
387
  }
388

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

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

494
                @Override
495
                public void onHeaders(Metadata headers) {
496
                  committed = true;
1✔
497
                  releaseCluster(finalCluster);
1✔
498
                  delegate().onHeaders(headers);
1✔
499
                }
1✔
500

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

515
      return
1✔
516
          Result.newBuilder()
1✔
517
              .setConfig(config)
1✔
518
              .setInterceptor(combineInterceptors(
1✔
519
                  ImmutableList.of(filters, new ClusterSelectionInterceptor())))
1✔
520
              .build();
1✔
521
    }
522

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

539
    private void releaseCluster(final String cluster) {
540
      int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
541
      if (count < 0) {
1✔
542
        throw new AssertionError();
×
543
      }
544
      if (count == 0) {
1✔
545
        syncContext.execute(new Runnable() {
1✔
546
          @Override
547
          public void run() {
548
            if (clusterRefs.get(cluster).refCount.get() != 0) {
1✔
549
              throw new AssertionError();
×
550
            }
551
            clusterRefs.remove(cluster);
1✔
552
            if (resolveState.lastConfigOrStatus.hasValue()) {
1✔
553
              updateResolutionResult(resolveState.lastConfigOrStatus.getValue());
1✔
554
            } else {
555
              resolveState.cleanUpRoutes(resolveState.lastConfigOrStatus.getStatus());
×
556
            }
557
          }
1✔
558
        });
559
      }
560
    }
1✔
561

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

593
  static final class PassthroughClientInterceptor implements ClientInterceptor {
1✔
594
    @Override
595
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
596
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
597
      return next.newCall(method, callOptions);
1✔
598
    }
599
  }
600

601
  private static ClientInterceptor combineInterceptors(final List<ClientInterceptor> interceptors) {
602
    if (interceptors.size() == 0) {
1✔
603
      return new PassthroughClientInterceptor();
1✔
604
    }
605
    if (interceptors.size() == 1) {
1✔
606
      return interceptors.get(0);
1✔
607
    }
608
    return new ClientInterceptor() {
1✔
609
      @Override
610
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
611
          MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
612
        next = ClientInterceptors.interceptForward(next, interceptors);
1✔
613
        return next.newCall(method, callOptions);
1✔
614
      }
615
    };
616
  }
617

618
  @Nullable
619
  private static String getHeaderValue(Metadata headers, String headerName) {
620
    if (headerName.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
1✔
621
      return null;
×
622
    }
623
    if (headerName.equals("content-type")) {
1✔
624
      return "application/grpc";
×
625
    }
626
    Metadata.Key<String> key;
627
    try {
628
      key = Metadata.Key.of(headerName, Metadata.ASCII_STRING_MARSHALLER);
1✔
629
    } catch (IllegalArgumentException e) {
×
630
      return null;
×
631
    }
1✔
632
    Iterable<String> values = headers.getAll(key);
1✔
633
    return values == null ? null : Joiner.on(",").join(values);
1✔
634
  }
635

636
  private static String prefixedClusterName(String name) {
637
    return "cluster:" + name;
1✔
638
  }
639

640
  private static String prefixedClusterSpecifierPluginName(String pluginName) {
641
    return "cluster_specifier_plugin:" + pluginName;
1✔
642
  }
643

644
  class ResolveState implements XdsDependencyManager.XdsConfigWatcher {
645
    private final ConfigOrError emptyServiceConfig =
1✔
646
        serviceConfigParser.parseServiceConfig(Collections.<String, Object>emptyMap());
1✔
647
    private final String authority;
648
    private final XdsDependencyManager xdsDependencyManager;
649
    private boolean stopped;
650
    @Nullable
651
    private Set<String> existingClusters;  // clusters to which new requests can be routed
652
    private StatusOr<XdsConfig> lastConfigOrStatus;
653

654
    private ResolveState(String ldsResourceName) {
1✔
655
      authority = overrideAuthority != null ? overrideAuthority : encodedServiceAuthority;
1✔
656
      xdsDependencyManager =
1✔
657
          new XdsDependencyManager(xdsClient, syncContext, authority, ldsResourceName,
1✔
658
              nameResolverArgs, scheduler);
1✔
659
    }
1✔
660

661
    void start() {
662
      xdsDependencyManager.start(this);
1✔
663
    }
1✔
664

665
    private void shutdown() {
666
      if (stopped) {
1✔
667
        return;
×
668
      }
669

670
      stopped = true;
1✔
671
      xdsDependencyManager.shutdown();
1✔
672
      updateActiveFilters(null);
1✔
673
    }
1✔
674

675
    @Override
676
    public void onUpdate(StatusOr<XdsConfig> updateOrStatus) {
677
      if (stopped) {
1✔
678
        return;
×
679
      }
680
      logger.log(XdsLogLevel.INFO, "Receive XDS resource update: {0}", updateOrStatus);
1✔
681

682
      lastConfigOrStatus = updateOrStatus;
1✔
683
      if (!updateOrStatus.hasValue()) {
1✔
684
        updateActiveFilters(null);
1✔
685
        cleanUpRoutes(updateOrStatus.getStatus());
1✔
686
        return;
1✔
687
      }
688

689
      // Process Route
690
      XdsConfig update = updateOrStatus.getValue();
1✔
691
      HttpConnectionManager httpConnectionManager = update.getListener().httpConnectionManager();
1✔
692
      if (httpConnectionManager == null) {
1✔
693
        logger.log(XdsLogLevel.INFO, "API Listener: httpConnectionManager does not exist.");
×
694
        updateActiveFilters(null);
×
695
        cleanUpRoutes(updateOrStatus.getStatus());
×
696
        return;
×
697
      }
698

699
      VirtualHost virtualHost = update.getVirtualHost();
1✔
700
      ImmutableList<NamedFilterConfig> filterConfigs = httpConnectionManager.httpFilterConfigs();
1✔
701
      long streamDurationNano = httpConnectionManager.httpMaxStreamDurationNano();
1✔
702

703
      updateActiveFilters(filterConfigs);
1✔
704
      updateRoutes(update, virtualHost, streamDurationNano, filterConfigs);
1✔
705
    }
1✔
706

707
    // called in syncContext
708
    private void updateActiveFilters(@Nullable List<NamedFilterConfig> filterConfigs) {
709
      if (filterConfigs == null) {
1✔
710
        filterConfigs = ImmutableList.of();
1✔
711
      }
712
      Set<String> filtersToShutdown = new HashSet<>(activeFilters.keySet());
1✔
713
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
714
        String typeUrl = namedFilter.filterConfig.typeUrl();
1✔
715
        String filterKey = namedFilter.filterStateKey();
1✔
716

717
        Filter.Provider provider = filterRegistry.get(typeUrl);
1✔
718
        checkNotNull(provider, "provider %s", typeUrl);
1✔
719
        Filter filter = activeFilters.computeIfAbsent(
1✔
720
            filterKey, k -> provider.newInstance(namedFilter.name));
1✔
721
        checkNotNull(filter, "filter %s", filterKey);
1✔
722
        filtersToShutdown.remove(filterKey);
1✔
723
      }
1✔
724

725
      // Shutdown filters not present in current HCM.
726
      for (String filterKey : filtersToShutdown) {
1✔
727
        Filter filterToShutdown = activeFilters.remove(filterKey);
1✔
728
        checkNotNull(filterToShutdown, "filterToShutdown %s", filterKey);
1✔
729
        filterToShutdown.close();
1✔
730
      }
1✔
731
    }
1✔
732

733
    private void updateRoutes(
734
        XdsConfig xdsConfig,
735
        @Nullable VirtualHost virtualHost,
736
        long httpMaxStreamDurationNano,
737
        @Nullable List<NamedFilterConfig> filterConfigs) {
738
      List<Route> routes = virtualHost.routes();
1✔
739
      ImmutableList.Builder<RouteData> routesData = ImmutableList.builder();
1✔
740

741
      // Populate all clusters to which requests can be routed to through the virtual host.
742
      Set<String> clusters = new HashSet<>();
1✔
743
      // uniqueName -> clusterName
744
      Map<String, String> clusterNameMap = new HashMap<>();
1✔
745
      // uniqueName -> pluginConfig
746
      Map<String, RlsPluginConfig> rlsPluginConfigMap = new HashMap<>();
1✔
747
      for (Route route : routes) {
1✔
748
        RouteAction action = route.routeAction();
1✔
749
        String prefixedName;
750
        if (action == null) {
1✔
751
          routesData.add(new RouteData(route.routeMatch(), null, ImmutableList.of()));
1✔
752
        } else if (action.cluster() != null) {
1✔
753
          prefixedName = prefixedClusterName(action.cluster());
1✔
754
          clusters.add(prefixedName);
1✔
755
          clusterNameMap.put(prefixedName, action.cluster());
1✔
756
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
757
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
758
        } else if (action.weightedClusters() != null) {
1✔
759
          ImmutableList.Builder<ClientInterceptor> filterList = ImmutableList.builder();
1✔
760
          for (ClusterWeight weightedCluster : action.weightedClusters()) {
1✔
761
            prefixedName = prefixedClusterName(weightedCluster.name());
1✔
762
            clusters.add(prefixedName);
1✔
763
            clusterNameMap.put(prefixedName, weightedCluster.name());
1✔
764
            filterList.add(createFilters(filterConfigs, virtualHost, route, weightedCluster));
1✔
765
          }
1✔
766
          routesData.add(
1✔
767
              new RouteData(route.routeMatch(), route.routeAction(), filterList.build()));
1✔
768
        } else if (action.namedClusterSpecifierPluginConfig() != null) {
1✔
769
          PluginConfig pluginConfig = action.namedClusterSpecifierPluginConfig().config();
1✔
770
          if (pluginConfig instanceof RlsPluginConfig) {
1✔
771
            prefixedName = prefixedClusterSpecifierPluginName(
1✔
772
                action.namedClusterSpecifierPluginConfig().name());
1✔
773
            clusters.add(prefixedName);
1✔
774
            rlsPluginConfigMap.put(prefixedName, (RlsPluginConfig) pluginConfig);
1✔
775
          }
776
          ClientInterceptor filters = createFilters(filterConfigs, virtualHost, route, null);
1✔
777
          routesData.add(new RouteData(route.routeMatch(), route.routeAction(), filters));
1✔
778
        } else {
779
          // Discard route
780
        }
781
      }
1✔
782

783
      // Updates channel's load balancing config whenever the set of selectable clusters changes.
784
      boolean shouldUpdateResult = existingClusters == null;
1✔
785
      Set<String> addedClusters =
786
          existingClusters == null ? clusters : Sets.difference(clusters, existingClusters);
1✔
787
      Set<String> deletedClusters =
788
          existingClusters == null
1✔
789
              ? Collections.emptySet() : Sets.difference(existingClusters, clusters);
1✔
790
      existingClusters = clusters;
1✔
791
      for (String cluster : addedClusters) {
1✔
792
        if (clusterRefs.containsKey(cluster)) {
1✔
793
          clusterRefs.get(cluster).refCount.incrementAndGet();
1✔
794
        } else {
795
          if (clusterNameMap.containsKey(cluster)) {
1✔
796
            clusterRefs.put(
1✔
797
                cluster,
798
                ClusterRefState.forCluster(new AtomicInteger(1), clusterNameMap.get(cluster)));
1✔
799
          }
800
          if (rlsPluginConfigMap.containsKey(cluster)) {
1✔
801
            clusterRefs.put(
1✔
802
                cluster,
803
                ClusterRefState.forRlsPlugin(
1✔
804
                    new AtomicInteger(1), rlsPluginConfigMap.get(cluster)));
1✔
805
          }
806
          shouldUpdateResult = true;
1✔
807
        }
808
      }
1✔
809
      for (String cluster : clusters) {
1✔
810
        RlsPluginConfig rlsPluginConfig = rlsPluginConfigMap.get(cluster);
1✔
811
        if (!Objects.equals(rlsPluginConfig, clusterRefs.get(cluster).rlsPluginConfig)) {
1✔
812
          ClusterRefState newClusterRefState =
1✔
813
              ClusterRefState.forRlsPlugin(clusterRefs.get(cluster).refCount, rlsPluginConfig);
1✔
814
          clusterRefs.put(cluster, newClusterRefState);
1✔
815
          shouldUpdateResult = true;
1✔
816
        }
817
      }
1✔
818
      // Update service config to include newly added clusters.
819
      if (shouldUpdateResult && routingConfig != null) {
1✔
820
        updateResolutionResult(xdsConfig);
1✔
821
        shouldUpdateResult = false;
1✔
822
      }
823
      // Make newly added clusters selectable by config selector and deleted clusters no longer
824
      // selectable.
825
      routingConfig = new RoutingConfig(xdsConfig, httpMaxStreamDurationNano, routesData.build());
1✔
826
      for (String cluster : deletedClusters) {
1✔
827
        int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
828
        if (count == 0) {
1✔
829
          clusterRefs.remove(cluster);
1✔
830
          shouldUpdateResult = true;
1✔
831
        }
832
      }
1✔
833
      if (shouldUpdateResult) {
1✔
834
        updateResolutionResult(xdsConfig);
1✔
835
      }
836
    }
1✔
837

838
    private ClientInterceptor createFilters(
839
        @Nullable List<NamedFilterConfig> filterConfigs,
840
        VirtualHost virtualHost,
841
        Route route,
842
        @Nullable ClusterWeight weightedCluster) {
843
      if (filterConfigs == null) {
1✔
844
        return new PassthroughClientInterceptor();
1✔
845
      }
846

847
      Map<String, FilterConfig> selectedOverrideConfigs =
1✔
848
          new HashMap<>(virtualHost.filterConfigOverrides());
1✔
849
      selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
850
      if (weightedCluster != null) {
1✔
851
        selectedOverrideConfigs.putAll(weightedCluster.filterConfigOverrides());
1✔
852
      }
853

854
      ImmutableList.Builder<ClientInterceptor> filterInterceptors = ImmutableList.builder();
1✔
855
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
856
        String name = namedFilter.name;
1✔
857
        FilterConfig config = namedFilter.filterConfig;
1✔
858
        FilterConfig overrideConfig = selectedOverrideConfigs.get(name);
1✔
859
        String filterKey = namedFilter.filterStateKey();
1✔
860

861
        Filter filter = activeFilters.get(filterKey);
1✔
862
        checkNotNull(filter, "activeFilters.get(%s)", filterKey);
1✔
863
        ClientInterceptor interceptor =
1✔
864
            filter.buildClientInterceptor(config, overrideConfig, scheduler);
1✔
865

866
        if (interceptor != null) {
1✔
867
          filterInterceptors.add(interceptor);
1✔
868
        }
869
      }
1✔
870

871
      // Combine interceptors produced by different filters into a single one that executes
872
      // them sequentially. The order is preserved.
873
      return combineInterceptors(filterInterceptors.build());
1✔
874
    }
875

876
    private void cleanUpRoutes(Status error) {
877
      routingConfig = new RoutingConfig(error);
1✔
878
      if (existingClusters != null) {
1✔
879
        for (String cluster : existingClusters) {
1✔
880
          int count = clusterRefs.get(cluster).refCount.decrementAndGet();
1✔
881
          if (count == 0) {
1✔
882
            clusterRefs.remove(cluster);
1✔
883
          }
884
        }
1✔
885
        existingClusters = null;
1✔
886
      }
887

888
      // Without addresses the default LB (normally pick_first) should become TRANSIENT_FAILURE, and
889
      // the config selector handles the error message itself.
890
      listener.onResult2(ResolutionResult.newBuilder()
1✔
891
          .setAttributes(Attributes.newBuilder()
1✔
892
            .set(InternalConfigSelector.KEY, configSelector)
1✔
893
            .build())
1✔
894
          .setServiceConfig(emptyServiceConfig)
1✔
895
          .build());
1✔
896
    }
1✔
897
  }
898

899
  /**
900
   * VirtualHost-level configuration for request routing.
901
   */
902
  private static class RoutingConfig {
903
    final XdsConfig xdsConfig;
904
    final long fallbackTimeoutNano;
905
    final ImmutableList<RouteData> routes;
906
    final Status errorStatus;
907

908
    private RoutingConfig(
909
        XdsConfig xdsConfig, long fallbackTimeoutNano, ImmutableList<RouteData> routes) {
1✔
910
      this.xdsConfig = checkNotNull(xdsConfig, "xdsConfig");
1✔
911
      this.fallbackTimeoutNano = fallbackTimeoutNano;
1✔
912
      this.routes = checkNotNull(routes, "routes");
1✔
913
      this.errorStatus = null;
1✔
914
    }
1✔
915

916
    private RoutingConfig(Status errorStatus) {
1✔
917
      this.xdsConfig = null;
1✔
918
      this.fallbackTimeoutNano = 0;
1✔
919
      this.routes = null;
1✔
920
      this.errorStatus = checkNotNull(errorStatus, "errorStatus");
1✔
921
      checkArgument(!errorStatus.isOk(), "errorStatus should not be okay");
1✔
922
    }
1✔
923
  }
924

925
  static final class RouteData {
926
    final RouteMatch routeMatch;
927
    /** null implies non-forwarding action. */
928
    @Nullable
929
    final RouteAction routeAction;
930
    /**
931
     * Only one of these interceptors should be used per-RPC. There are only multiple values in the
932
     * list for weighted clusters, in which case the order of the list mirrors the weighted
933
     * clusters.
934
     */
935
    final ImmutableList<ClientInterceptor> filterChoices;
936

937
    RouteData(RouteMatch routeMatch, @Nullable RouteAction routeAction, ClientInterceptor filter) {
938
      this(routeMatch, routeAction, ImmutableList.of(filter));
1✔
939
    }
1✔
940

941
    RouteData(
942
        RouteMatch routeMatch,
943
        @Nullable RouteAction routeAction,
944
        ImmutableList<ClientInterceptor> filterChoices) {
1✔
945
      this.routeMatch = checkNotNull(routeMatch, "routeMatch");
1✔
946
      checkArgument(
1✔
947
          routeAction == null || !filterChoices.isEmpty(),
1✔
948
          "filter may be empty only for non-forwarding action");
949
      this.routeAction = routeAction;
1✔
950
      if (routeAction != null && routeAction.weightedClusters() != null) {
1✔
951
        checkArgument(
1✔
952
            routeAction.weightedClusters().size() == filterChoices.size(),
1✔
953
            "filter choices must match size of weighted clusters");
954
      }
955
      for (ClientInterceptor filter : filterChoices) {
1✔
956
        checkNotNull(filter, "entry in filterChoices is null");
1✔
957
      }
1✔
958
      this.filterChoices = checkNotNull(filterChoices, "filterChoices");
1✔
959
    }
1✔
960
  }
961

962
  private static class ClusterRefState {
963
    final AtomicInteger refCount;
964
    @Nullable
965
    final String traditionalCluster;
966
    @Nullable
967
    final RlsPluginConfig rlsPluginConfig;
968

969
    private ClusterRefState(
970
        AtomicInteger refCount, @Nullable String traditionalCluster,
971
        @Nullable RlsPluginConfig rlsPluginConfig) {
1✔
972
      this.refCount = refCount;
1✔
973
      checkArgument(traditionalCluster == null ^ rlsPluginConfig == null,
1✔
974
          "There must be exactly one non-null value in traditionalCluster and pluginConfig");
975
      this.traditionalCluster = traditionalCluster;
1✔
976
      this.rlsPluginConfig = rlsPluginConfig;
1✔
977
    }
1✔
978

979
    private Map<String, ?> toLbPolicy() {
980
      if (traditionalCluster != null) {
1✔
981
        return ImmutableMap.of(
1✔
982
            XdsLbPolicies.CDS_POLICY_NAME,
983
            ImmutableMap.of("cluster", traditionalCluster));
1✔
984
      } else {
985
        ImmutableMap<String, ?> rlsConfig = new ImmutableMap.Builder<String, Object>()
1✔
986
            .put("routeLookupConfig", rlsPluginConfig.config())
1✔
987
            .put(
1✔
988
                "childPolicy",
989
                ImmutableList.of(ImmutableMap.of(XdsLbPolicies.CDS_POLICY_NAME, ImmutableMap.of())))
1✔
990
            .put("childPolicyConfigTargetFieldName", "cluster")
1✔
991
            .buildOrThrow();
1✔
992
        return ImmutableMap.of("rls_experimental", rlsConfig);
1✔
993
      }
994
    }
995

996
    static ClusterRefState forCluster(AtomicInteger refCount, String name) {
997
      return new ClusterRefState(refCount, name, null);
1✔
998
    }
999

1000
    static ClusterRefState forRlsPlugin(AtomicInteger refCount, RlsPluginConfig rlsPluginConfig) {
1001
      return new ClusterRefState(refCount, null, rlsPluginConfig);
1✔
1002
    }
1003
  }
1004
}
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