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

grpc / grpc-java / #19249

24 May 2024 10:08PM UTC coverage: 88.444% (-0.07%) from 88.512%
#19249

push

github

web-flow
xds: Plumb the Cluster's filterMetadata to RPCs

This will be used by CSM observability, and may get exposed to further
uses in the future.

32060 of 36249 relevant lines covered (88.44%)

0.88 hits per line

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

95.63
/../xds/src/main/java/io/grpc/xds/ClusterResolverLoadBalancer.java
1
/*
2
 * Copyright 2020 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.xds;
18

19
import static com.google.common.base.Preconditions.checkNotNull;
20
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
21
import static io.grpc.xds.XdsLbPolicies.PRIORITY_POLICY_NAME;
22

23
import com.google.common.annotations.VisibleForTesting;
24
import com.google.common.collect.ImmutableMap;
25
import com.google.protobuf.Struct;
26
import io.grpc.Attributes;
27
import io.grpc.EquivalentAddressGroup;
28
import io.grpc.InternalLogId;
29
import io.grpc.LoadBalancer;
30
import io.grpc.LoadBalancerProvider;
31
import io.grpc.LoadBalancerRegistry;
32
import io.grpc.NameResolver;
33
import io.grpc.NameResolver.ResolutionResult;
34
import io.grpc.Status;
35
import io.grpc.SynchronizationContext;
36
import io.grpc.SynchronizationContext.ScheduledHandle;
37
import io.grpc.internal.BackoffPolicy;
38
import io.grpc.internal.ExponentialBackoffPolicy;
39
import io.grpc.internal.ObjectPool;
40
import io.grpc.internal.ServiceConfigUtil.PolicySelection;
41
import io.grpc.util.ForwardingLoadBalancerHelper;
42
import io.grpc.util.GracefulSwitchLoadBalancer;
43
import io.grpc.util.OutlierDetectionLoadBalancer.OutlierDetectionLoadBalancerConfig;
44
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
45
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig;
46
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig.DiscoveryMechanism;
47
import io.grpc.xds.Endpoints.DropOverload;
48
import io.grpc.xds.Endpoints.LbEndpoint;
49
import io.grpc.xds.Endpoints.LocalityLbEndpoints;
50
import io.grpc.xds.EnvoyServerProtoData.FailurePercentageEjection;
51
import io.grpc.xds.EnvoyServerProtoData.OutlierDetection;
52
import io.grpc.xds.EnvoyServerProtoData.SuccessRateEjection;
53
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
54
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig;
55
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig.PriorityChildConfig;
56
import io.grpc.xds.XdsEndpointResource.EdsUpdate;
57
import io.grpc.xds.client.Bootstrapper.ServerInfo;
58
import io.grpc.xds.client.Locality;
59
import io.grpc.xds.client.XdsClient;
60
import io.grpc.xds.client.XdsClient.ResourceWatcher;
61
import io.grpc.xds.client.XdsLogger;
62
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
63
import java.net.URI;
64
import java.net.URISyntaxException;
65
import java.util.ArrayList;
66
import java.util.Arrays;
67
import java.util.Collections;
68
import java.util.HashMap;
69
import java.util.HashSet;
70
import java.util.List;
71
import java.util.Locale;
72
import java.util.Map;
73
import java.util.Objects;
74
import java.util.Set;
75
import java.util.TreeMap;
76
import java.util.concurrent.ScheduledExecutorService;
77
import java.util.concurrent.TimeUnit;
78
import javax.annotation.Nullable;
79

80
/**
81
 * Load balancer for cluster_resolver_experimental LB policy. This LB policy is the child LB policy
82
 * of the cds_experimental LB policy and the parent LB policy of the priority_experimental LB
83
 * policy in the xDS load balancing hierarchy. This policy resolves endpoints of non-aggregate
84
 * clusters (e.g., EDS or Logical DNS) and groups endpoints in priorities and localities to be
85
 * used in the downstream LB policies for fine-grained load balancing purposes.
86
 */
87
final class ClusterResolverLoadBalancer extends LoadBalancer {
88
  // DNS-resolved endpoints do not have the definition of the locality it belongs to, just hardcode
89
  // to an empty locality.
90
  private static final Locality LOGICAL_DNS_CLUSTER_LOCALITY = Locality.create("", "", "");
1✔
91
  private final XdsLogger logger;
92
  private final SynchronizationContext syncContext;
93
  private final ScheduledExecutorService timeService;
94
  private final LoadBalancerRegistry lbRegistry;
95
  private final BackoffPolicy.Provider backoffPolicyProvider;
96
  private final GracefulSwitchLoadBalancer delegate;
97
  private ObjectPool<XdsClient> xdsClientPool;
98
  private XdsClient xdsClient;
99
  private ClusterResolverConfig config;
100

101
  ClusterResolverLoadBalancer(Helper helper) {
102
    this(helper, LoadBalancerRegistry.getDefaultRegistry(),
1✔
103
        new ExponentialBackoffPolicy.Provider());
104
  }
1✔
105

106
  @VisibleForTesting
107
  ClusterResolverLoadBalancer(Helper helper, LoadBalancerRegistry lbRegistry,
108
      BackoffPolicy.Provider backoffPolicyProvider) {
1✔
109
    this.lbRegistry = checkNotNull(lbRegistry, "lbRegistry");
1✔
110
    this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
1✔
111
    this.syncContext = checkNotNull(helper.getSynchronizationContext(), "syncContext");
1✔
112
    this.timeService = checkNotNull(helper.getScheduledExecutorService(), "timeService");
1✔
113
    delegate = new GracefulSwitchLoadBalancer(helper);
1✔
114
    logger = XdsLogger.withLogId(
1✔
115
        InternalLogId.allocate("cluster-resolver-lb", helper.getAuthority()));
1✔
116
    logger.log(XdsLogLevel.INFO, "Created");
1✔
117
  }
1✔
118

119
  @Override
120
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
121
    logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
1✔
122
    if (xdsClientPool == null) {
1✔
123
      xdsClientPool = resolvedAddresses.getAttributes().get(InternalXdsAttributes.XDS_CLIENT_POOL);
1✔
124
      xdsClient = xdsClientPool.getObject();
1✔
125
    }
126
    ClusterResolverConfig config =
1✔
127
        (ClusterResolverConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
128
    if (!Objects.equals(this.config, config)) {
1✔
129
      logger.log(XdsLogLevel.DEBUG, "Config: {0}", config);
1✔
130
      delegate.switchTo(new ClusterResolverLbStateFactory());
1✔
131
      this.config = config;
1✔
132
      delegate.handleResolvedAddresses(resolvedAddresses);
1✔
133
    }
134
    return Status.OK;
1✔
135
  }
136

137
  @Override
138
  public void handleNameResolutionError(Status error) {
139
    logger.log(XdsLogLevel.WARNING, "Received name resolution error: {0}", error);
1✔
140
    delegate.handleNameResolutionError(error);
1✔
141
  }
1✔
142

143
  @Override
144
  public void shutdown() {
145
    logger.log(XdsLogLevel.INFO, "Shutdown");
1✔
146
    delegate.shutdown();
1✔
147
    if (xdsClientPool != null) {
1✔
148
      xdsClientPool.returnObject(xdsClient);
1✔
149
    }
150
  }
1✔
151

152
  private final class ClusterResolverLbStateFactory extends LoadBalancer.Factory {
1✔
153
    @Override
154
    public LoadBalancer newLoadBalancer(Helper helper) {
155
      return new ClusterResolverLbState(helper);
1✔
156
    }
157
  }
158

159
  /**
160
   * The state of a cluster_resolver LB working session. A new instance is created whenever
161
   * the cluster_resolver LB receives a new config. The old instance is replaced when the
162
   * new one is ready to handle new RPCs.
163
   */
164
  private final class ClusterResolverLbState extends LoadBalancer {
165
    private final Helper helper;
166
    private final List<String> clusters = new ArrayList<>();
1✔
167
    private final Map<String, ClusterState> clusterStates = new HashMap<>();
1✔
168
    private PolicySelection endpointLbPolicy;
169
    private ResolvedAddresses resolvedAddresses;
170
    private LoadBalancer childLb;
171

172
    ClusterResolverLbState(Helper helper) {
1✔
173
      this.helper = new RefreshableHelper(checkNotNull(helper, "helper"));
1✔
174
      logger.log(XdsLogLevel.DEBUG, "New ClusterResolverLbState");
1✔
175
    }
1✔
176

177
    @Override
178
    public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
179
      this.resolvedAddresses = resolvedAddresses;
1✔
180
      ClusterResolverConfig config =
1✔
181
          (ClusterResolverConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
182
      endpointLbPolicy = config.lbPolicy;
1✔
183
      for (DiscoveryMechanism instance : config.discoveryMechanisms) {
1✔
184
        clusters.add(instance.cluster);
1✔
185
        ClusterState state;
186
        if (instance.type == DiscoveryMechanism.Type.EDS) {
1✔
187
          state = new EdsClusterState(instance.cluster, instance.edsServiceName,
1✔
188
              instance.lrsServerInfo, instance.maxConcurrentRequests, instance.tlsContext,
189
              instance.filterMetadata, instance.outlierDetection);
190
        } else {  // logical DNS
191
          state = new LogicalDnsClusterState(instance.cluster, instance.dnsHostName,
1✔
192
              instance.lrsServerInfo, instance.maxConcurrentRequests, instance.tlsContext,
193
              instance.filterMetadata);
194
        }
195
        clusterStates.put(instance.cluster, state);
1✔
196
        state.start();
1✔
197
      }
1✔
198
      return Status.OK;
1✔
199
    }
200

201
    @Override
202
    public void handleNameResolutionError(Status error) {
203
      if (childLb != null) {
1✔
204
        childLb.handleNameResolutionError(error);
1✔
205
      } else {
206
        helper.updateBalancingState(
1✔
207
            TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(error)));
1✔
208
      }
209
    }
1✔
210

211
    @Override
212
    public void shutdown() {
213
      for (ClusterState state : clusterStates.values()) {
1✔
214
        state.shutdown();
1✔
215
      }
1✔
216
      if (childLb != null) {
1✔
217
        childLb.shutdown();
1✔
218
      }
219
    }
1✔
220

221
    private void handleEndpointResourceUpdate() {
222
      List<EquivalentAddressGroup> addresses = new ArrayList<>();
1✔
223
      Map<String, PriorityChildConfig> priorityChildConfigs = new HashMap<>();
1✔
224
      List<String> priorities = new ArrayList<>();  // totally ordered priority list
1✔
225

226
      Status endpointNotFound = Status.OK;
1✔
227
      for (String cluster : clusters) {
1✔
228
        ClusterState state = clusterStates.get(cluster);
1✔
229
        // Propagate endpoints to the child LB policy only after all clusters have been resolved.
230
        if (!state.resolved && state.status.isOk()) {
1✔
231
          return;
1✔
232
        }
233
        if (state.result != null) {
1✔
234
          addresses.addAll(state.result.addresses);
1✔
235
          priorityChildConfigs.putAll(state.result.priorityChildConfigs);
1✔
236
          priorities.addAll(state.result.priorities);
1✔
237
        } else {
238
          endpointNotFound = state.status;
1✔
239
        }
240
      }
1✔
241
      if (addresses.isEmpty()) {
1✔
242
        if (endpointNotFound.isOk()) {
1✔
243
          endpointNotFound = Status.UNAVAILABLE.withDescription(
1✔
244
              "No usable endpoint from cluster(s): " + clusters);
245
        } else {
246
          endpointNotFound =
1✔
247
              Status.UNAVAILABLE.withCause(endpointNotFound.getCause())
1✔
248
                  .withDescription(endpointNotFound.getDescription());
1✔
249
        }
250
        helper.updateBalancingState(
1✔
251
            TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(endpointNotFound)));
1✔
252
        if (childLb != null) {
1✔
253
          childLb.shutdown();
1✔
254
          childLb = null;
1✔
255
        }
256
        return;
1✔
257
      }
258
      PriorityLbConfig childConfig =
1✔
259
          new PriorityLbConfig(Collections.unmodifiableMap(priorityChildConfigs),
1✔
260
              Collections.unmodifiableList(priorities));
1✔
261
      if (childLb == null) {
1✔
262
        childLb = lbRegistry.getProvider(PRIORITY_POLICY_NAME).newLoadBalancer(helper);
1✔
263
      }
264
      childLb.handleResolvedAddresses(
1✔
265
          resolvedAddresses.toBuilder()
1✔
266
              .setLoadBalancingPolicyConfig(childConfig)
1✔
267
              .setAddresses(Collections.unmodifiableList(addresses))
1✔
268
              .build());
1✔
269
    }
1✔
270

271
    private void handleEndpointResolutionError() {
272
      boolean allInError = true;
1✔
273
      Status error = null;
1✔
274
      for (String cluster : clusters) {
1✔
275
        ClusterState state = clusterStates.get(cluster);
1✔
276
        if (state.status.isOk()) {
1✔
277
          allInError = false;
1✔
278
        } else {
279
          error = state.status;
1✔
280
        }
281
      }
1✔
282
      if (allInError) {
1✔
283
        if (childLb != null) {
1✔
284
          childLb.handleNameResolutionError(error);
1✔
285
        } else {
286
          helper.updateBalancingState(
1✔
287
              TRANSIENT_FAILURE, new FixedResultPicker(PickResult.withError(error)));
1✔
288
        }
289
      }
290
    }
1✔
291

292
    /**
293
     * Wires re-resolution requests from downstream LB policies with DNS resolver.
294
     */
295
    private final class RefreshableHelper extends ForwardingLoadBalancerHelper {
296
      private final Helper delegate;
297

298
      private RefreshableHelper(Helper delegate) {
1✔
299
        this.delegate = checkNotNull(delegate, "delegate");
1✔
300
      }
1✔
301

302
      @Override
303
      public void refreshNameResolution() {
304
        for (ClusterState state : clusterStates.values()) {
1✔
305
          if (state instanceof LogicalDnsClusterState) {
1✔
306
            ((LogicalDnsClusterState) state).refresh();
1✔
307
          }
308
        }
1✔
309
      }
1✔
310

311
      @Override
312
      protected Helper delegate() {
313
        return delegate;
1✔
314
      }
315
    }
316

317
    /**
318
     * Resolution state of an underlying cluster.
319
     */
320
    private abstract class ClusterState {
321
      // Name of the cluster to be resolved.
322
      protected final String name;
323
      @Nullable
324
      protected final ServerInfo lrsServerInfo;
325
      @Nullable
326
      protected final Long maxConcurrentRequests;
327
      @Nullable
328
      protected final UpstreamTlsContext tlsContext;
329
      protected final Map<String, Struct> filterMetadata;
330
      @Nullable
331
      protected final OutlierDetection outlierDetection;
332
      // Resolution status, may contain most recent error encountered.
333
      protected Status status = Status.OK;
1✔
334
      // True if has received resolution result.
335
      protected boolean resolved;
336
      // Most recently resolved addresses and config, or null if resource not exists.
337
      @Nullable
338
      protected ClusterResolutionResult result;
339

340
      protected boolean shutdown;
341

342
      private ClusterState(String name, @Nullable ServerInfo lrsServerInfo,
343
          @Nullable Long maxConcurrentRequests, @Nullable UpstreamTlsContext tlsContext,
344
          Map<String, Struct> filterMetadata, @Nullable OutlierDetection outlierDetection) {
1✔
345
        this.name = name;
1✔
346
        this.lrsServerInfo = lrsServerInfo;
1✔
347
        this.maxConcurrentRequests = maxConcurrentRequests;
1✔
348
        this.tlsContext = tlsContext;
1✔
349
        this.filterMetadata = ImmutableMap.copyOf(filterMetadata);
1✔
350
        this.outlierDetection = outlierDetection;
1✔
351
      }
1✔
352

353
      abstract void start();
354

355
      void shutdown() {
356
        shutdown = true;
1✔
357
      }
1✔
358
    }
359

360
    private final class EdsClusterState extends ClusterState implements ResourceWatcher<EdsUpdate> {
361
      @Nullable
362
      private final String edsServiceName;
363
      private Map<Locality, String> localityPriorityNames = Collections.emptyMap();
1✔
364
      int priorityNameGenId = 1;
1✔
365

366
      private EdsClusterState(String name, @Nullable String edsServiceName,
367
          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
368
          @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata,
369
          @Nullable OutlierDetection outlierDetection) {
1✔
370
        super(name, lrsServerInfo, maxConcurrentRequests, tlsContext, filterMetadata,
1✔
371
            outlierDetection);
372
        this.edsServiceName = edsServiceName;
1✔
373
      }
1✔
374

375
      @Override
376
      void start() {
377
        String resourceName = edsServiceName != null ? edsServiceName : name;
1✔
378
        logger.log(XdsLogLevel.INFO, "Start watching EDS resource {0}", resourceName);
1✔
379
        xdsClient.watchXdsResource(XdsEndpointResource.getInstance(),
1✔
380
            resourceName, this, syncContext);
1✔
381
      }
1✔
382

383
      @Override
384
      protected void shutdown() {
385
        super.shutdown();
1✔
386
        String resourceName = edsServiceName != null ? edsServiceName : name;
1✔
387
        logger.log(XdsLogLevel.INFO, "Stop watching EDS resource {0}", resourceName);
1✔
388
        xdsClient.cancelXdsResourceWatch(XdsEndpointResource.getInstance(), resourceName, this);
1✔
389
      }
1✔
390

391
      @Override
392
      public void onChanged(final EdsUpdate update) {
393
        class EndpointsUpdated implements Runnable {
1✔
394
          @Override
395
          public void run() {
396
            if (shutdown) {
1✔
397
              return;
×
398
            }
399
            logger.log(XdsLogLevel.DEBUG, "Received endpoint update {0}", update);
1✔
400
            if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
401
              logger.log(XdsLogLevel.INFO, "Cluster {0}: {1} localities, {2} drop categories",
×
402
                  update.clusterName, update.localityLbEndpointsMap.size(),
×
403
                  update.dropPolicies.size());
×
404
            }
405
            Map<Locality, LocalityLbEndpoints> localityLbEndpoints =
1✔
406
                update.localityLbEndpointsMap;
407
            List<DropOverload> dropOverloads = update.dropPolicies;
1✔
408
            List<EquivalentAddressGroup> addresses = new ArrayList<>();
1✔
409
            Map<String, Map<Locality, Integer>> prioritizedLocalityWeights = new HashMap<>();
1✔
410
            List<String> sortedPriorityNames = generatePriorityNames(name, localityLbEndpoints);
1✔
411
            for (Locality locality : localityLbEndpoints.keySet()) {
1✔
412
              LocalityLbEndpoints localityLbInfo = localityLbEndpoints.get(locality);
1✔
413
              String priorityName = localityPriorityNames.get(locality);
1✔
414
              boolean discard = true;
1✔
415
              for (LbEndpoint endpoint : localityLbInfo.endpoints()) {
1✔
416
                if (endpoint.isHealthy()) {
1✔
417
                  discard = false;
1✔
418
                  long weight = localityLbInfo.localityWeight();
1✔
419
                  if (endpoint.loadBalancingWeight() != 0) {
1✔
420
                    weight *= endpoint.loadBalancingWeight();
1✔
421
                  }
422
                  String localityName = localityName(locality);
1✔
423
                  Attributes attr =
1✔
424
                      endpoint.eag().getAttributes().toBuilder()
1✔
425
                          .set(InternalXdsAttributes.ATTR_LOCALITY, locality)
1✔
426
                          .set(InternalXdsAttributes.ATTR_LOCALITY_NAME, localityName)
1✔
427
                          .set(InternalXdsAttributes.ATTR_LOCALITY_WEIGHT,
1✔
428
                              localityLbInfo.localityWeight())
1✔
429
                          .set(InternalXdsAttributes.ATTR_SERVER_WEIGHT, weight)
1✔
430
                          .build();
1✔
431
                  EquivalentAddressGroup eag = new EquivalentAddressGroup(
1✔
432
                      endpoint.eag().getAddresses(), attr);
1✔
433
                  eag = AddressFilter.setPathFilter(eag, Arrays.asList(priorityName, localityName));
1✔
434
                  addresses.add(eag);
1✔
435
                }
436
              }
1✔
437
              if (discard) {
1✔
438
                logger.log(XdsLogLevel.INFO,
1✔
439
                    "Discard locality {0} with 0 healthy endpoints", locality);
440
                continue;
1✔
441
              }
442
              if (!prioritizedLocalityWeights.containsKey(priorityName)) {
1✔
443
                prioritizedLocalityWeights.put(priorityName, new HashMap<Locality, Integer>());
1✔
444
              }
445
              prioritizedLocalityWeights.get(priorityName).put(
1✔
446
                  locality, localityLbInfo.localityWeight());
1✔
447
            }
1✔
448
            if (prioritizedLocalityWeights.isEmpty()) {
1✔
449
              // Will still update the result, as if the cluster resource is revoked.
450
              logger.log(XdsLogLevel.INFO,
1✔
451
                  "Cluster {0} has no usable priority/locality/endpoint", update.clusterName);
452
            }
453
            sortedPriorityNames.retainAll(prioritizedLocalityWeights.keySet());
1✔
454
            Map<String, PriorityChildConfig> priorityChildConfigs =
1✔
455
                generateEdsBasedPriorityChildConfigs(
1✔
456
                    name, edsServiceName, lrsServerInfo, maxConcurrentRequests, tlsContext,
1✔
457
                    filterMetadata, outlierDetection, endpointLbPolicy, lbRegistry,
1✔
458
                    prioritizedLocalityWeights, dropOverloads);
459
            status = Status.OK;
1✔
460
            resolved = true;
1✔
461
            result = new ClusterResolutionResult(addresses, priorityChildConfigs,
1✔
462
                sortedPriorityNames);
463
            handleEndpointResourceUpdate();
1✔
464
          }
1✔
465
        }
466

467
        new EndpointsUpdated().run();
1✔
468
      }
1✔
469

470
      private List<String> generatePriorityNames(String name,
471
          Map<Locality, LocalityLbEndpoints> localityLbEndpoints) {
472
        TreeMap<Integer, List<Locality>> todo = new TreeMap<>();
1✔
473
        for (Locality locality : localityLbEndpoints.keySet()) {
1✔
474
          int priority = localityLbEndpoints.get(locality).priority();
1✔
475
          if (!todo.containsKey(priority)) {
1✔
476
            todo.put(priority, new ArrayList<>());
1✔
477
          }
478
          todo.get(priority).add(locality);
1✔
479
        }
1✔
480
        Map<Locality, String> newNames = new HashMap<>();
1✔
481
        Set<String> usedNames = new HashSet<>();
1✔
482
        List<String> ret = new ArrayList<>();
1✔
483
        for (Integer priority: todo.keySet()) {
1✔
484
          String foundName = "";
1✔
485
          for (Locality locality : todo.get(priority)) {
1✔
486
            if (localityPriorityNames.containsKey(locality)
1✔
487
                && usedNames.add(localityPriorityNames.get(locality))) {
1✔
488
              foundName = localityPriorityNames.get(locality);
1✔
489
              break;
1✔
490
            }
491
          }
1✔
492
          if ("".equals(foundName)) {
1✔
493
            foundName = String.format(Locale.US, "%s[child%d]", name, priorityNameGenId++);
1✔
494
          }
495
          for (Locality locality : todo.get(priority)) {
1✔
496
            newNames.put(locality, foundName);
1✔
497
          }
1✔
498
          ret.add(foundName);
1✔
499
        }
1✔
500
        localityPriorityNames = newNames;
1✔
501
        return ret;
1✔
502
      }
503

504
      @Override
505
      public void onResourceDoesNotExist(final String resourceName) {
506
        if (shutdown) {
1✔
507
          return;
×
508
        }
509
        logger.log(XdsLogLevel.INFO, "Resource {0} unavailable", resourceName);
1✔
510
        status = Status.OK;
1✔
511
        resolved = true;
1✔
512
        result = null;  // resource revoked
1✔
513
        handleEndpointResourceUpdate();
1✔
514
      }
1✔
515

516
      @Override
517
      public void onError(final Status error) {
518
        if (shutdown) {
1✔
519
          return;
×
520
        }
521
        String resourceName = edsServiceName != null ? edsServiceName : name;
1✔
522
        status = Status.UNAVAILABLE
1✔
523
            .withDescription(String.format("Unable to load EDS %s. xDS server returned: %s: %s",
1✔
524
                  resourceName, error.getCode(), error.getDescription()))
1✔
525
            .withCause(error.getCause());
1✔
526
        logger.log(XdsLogLevel.WARNING, "Received EDS error: {0}", error);
1✔
527
        handleEndpointResolutionError();
1✔
528
      }
1✔
529
    }
530

531
    private final class LogicalDnsClusterState extends ClusterState {
532
      private final String dnsHostName;
533
      private final NameResolver.Factory nameResolverFactory;
534
      private final NameResolver.Args nameResolverArgs;
535
      private NameResolver resolver;
536
      @Nullable
537
      private BackoffPolicy backoffPolicy;
538
      @Nullable
539
      private ScheduledHandle scheduledRefresh;
540

541
      private LogicalDnsClusterState(String name, String dnsHostName,
542
          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
543
          @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata) {
1✔
544
        super(name, lrsServerInfo, maxConcurrentRequests, tlsContext, filterMetadata, null);
1✔
545
        this.dnsHostName = checkNotNull(dnsHostName, "dnsHostName");
1✔
546
        nameResolverFactory =
1✔
547
            checkNotNull(helper.getNameResolverRegistry().asFactory(), "nameResolverFactory");
1✔
548
        nameResolverArgs = checkNotNull(helper.getNameResolverArgs(), "nameResolverArgs");
1✔
549
      }
1✔
550

551
      @Override
552
      void start() {
553
        URI uri;
554
        try {
555
          uri = new URI("dns", "", "/" + dnsHostName, null);
1✔
556
        } catch (URISyntaxException e) {
×
557
          status = Status.INTERNAL.withDescription(
×
558
              "Bug, invalid URI creation: " + dnsHostName).withCause(e);
×
559
          handleEndpointResolutionError();
×
560
          return;
×
561
        }
1✔
562
        resolver = nameResolverFactory.newNameResolver(uri, nameResolverArgs);
1✔
563
        if (resolver == null) {
1✔
564
          status = Status.INTERNAL.withDescription("Xds cluster resolver lb for logical DNS "
×
565
              + "cluster [" + name + "] cannot find DNS resolver with uri:" + uri);
566
          handleEndpointResolutionError();
×
567
          return;
×
568
        }
569
        resolver.start(new NameResolverListener());
1✔
570
      }
1✔
571

572
      void refresh() {
573
        if (resolver == null) {
1✔
574
          return;
×
575
        }
576
        cancelBackoff();
1✔
577
        resolver.refresh();
1✔
578
      }
1✔
579

580
      @Override
581
      void shutdown() {
582
        super.shutdown();
1✔
583
        if (resolver != null) {
1✔
584
          resolver.shutdown();
1✔
585
        }
586
        cancelBackoff();
1✔
587
      }
1✔
588

589
      private void cancelBackoff() {
590
        if (scheduledRefresh != null) {
1✔
591
          scheduledRefresh.cancel();
1✔
592
          scheduledRefresh = null;
1✔
593
          backoffPolicy = null;
1✔
594
        }
595
      }
1✔
596

597
      private class DelayedNameResolverRefresh implements Runnable {
1✔
598
        @Override
599
        public void run() {
600
          scheduledRefresh = null;
1✔
601
          if (!shutdown) {
1✔
602
            resolver.refresh();
1✔
603
          }
604
        }
1✔
605
      }
606

607
      private class NameResolverListener extends NameResolver.Listener2 {
1✔
608
        @Override
609
        public void onResult(final ResolutionResult resolutionResult) {
610
          class NameResolved implements Runnable {
1✔
611
            @Override
612
            public void run() {
613
              if (shutdown) {
1✔
614
                return;
×
615
              }
616
              backoffPolicy = null;  // reset backoff sequence if succeeded
1✔
617
              // Arbitrary priority notation for all DNS-resolved endpoints.
618
              String priorityName = priorityName(name, 0);  // value doesn't matter
1✔
619
              List<EquivalentAddressGroup> addresses = new ArrayList<>();
1✔
620
              for (EquivalentAddressGroup eag : resolutionResult.getAddresses()) {
1✔
621
                // No weight attribute is attached, all endpoint-level LB policy should be able
622
                // to handle such it.
623
                String localityName = localityName(LOGICAL_DNS_CLUSTER_LOCALITY);
1✔
624
                Attributes attr = eag.getAttributes().toBuilder()
1✔
625
                    .set(InternalXdsAttributes.ATTR_LOCALITY, LOGICAL_DNS_CLUSTER_LOCALITY)
1✔
626
                    .set(InternalXdsAttributes.ATTR_LOCALITY_NAME, localityName)
1✔
627
                    .build();
1✔
628
                eag = new EquivalentAddressGroup(eag.getAddresses(), attr);
1✔
629
                eag = AddressFilter.setPathFilter(eag, Arrays.asList(priorityName, localityName));
1✔
630
                addresses.add(eag);
1✔
631
              }
1✔
632
              PriorityChildConfig priorityChildConfig = generateDnsBasedPriorityChildConfig(
1✔
633
                  name, lrsServerInfo, maxConcurrentRequests, tlsContext, filterMetadata,
634
                  lbRegistry, Collections.<DropOverload>emptyList());
1✔
635
              status = Status.OK;
1✔
636
              resolved = true;
1✔
637
              result = new ClusterResolutionResult(addresses, priorityName, priorityChildConfig);
1✔
638
              handleEndpointResourceUpdate();
1✔
639
            }
1✔
640
          }
641

642
          syncContext.execute(new NameResolved());
1✔
643
        }
1✔
644

645
        @Override
646
        public void onError(final Status error) {
647
          syncContext.execute(new Runnable() {
1✔
648
            @Override
649
            public void run() {
650
              if (shutdown) {
1✔
651
                return;
×
652
              }
653
              status = error;
1✔
654
              // NameResolver.Listener API cannot distinguish between address-not-found and
655
              // transient errors. If the error occurs in the first resolution, treat it as
656
              // address not found. Otherwise, either there is previously resolved addresses
657
              // previously encountered error, propagate the error to downstream/upstream and
658
              // let downstream/upstream handle it.
659
              if (!resolved) {
1✔
660
                resolved = true;
1✔
661
                handleEndpointResourceUpdate();
1✔
662
              } else {
663
                handleEndpointResolutionError();
1✔
664
              }
665
              if (scheduledRefresh != null && scheduledRefresh.isPending()) {
1✔
666
                return;
×
667
              }
668
              if (backoffPolicy == null) {
1✔
669
                backoffPolicy = backoffPolicyProvider.get();
1✔
670
              }
671
              long delayNanos = backoffPolicy.nextBackoffNanos();
1✔
672
              logger.log(XdsLogLevel.DEBUG,
1✔
673
                  "Logical DNS resolver for cluster {0} encountered name resolution "
674
                      + "error: {1}, scheduling DNS resolution backoff for {2} ns",
675
                  name, error, delayNanos);
1✔
676
              scheduledRefresh =
1✔
677
                  syncContext.schedule(
1✔
678
                      new DelayedNameResolverRefresh(), delayNanos, TimeUnit.NANOSECONDS,
679
                      timeService);
1✔
680
            }
1✔
681
          });
682
        }
1✔
683
      }
684
    }
685
  }
686

687
  private static class ClusterResolutionResult {
688
    // Endpoint addresses.
689
    private final List<EquivalentAddressGroup> addresses;
690
    // Config (include load balancing policy/config) for each priority in the cluster.
691
    private final Map<String, PriorityChildConfig> priorityChildConfigs;
692
    // List of priority names ordered in descending priorities.
693
    private final List<String> priorities;
694

695
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses, String priority,
696
        PriorityChildConfig config) {
697
      this(addresses, Collections.singletonMap(priority, config),
1✔
698
          Collections.singletonList(priority));
1✔
699
    }
1✔
700

701
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses,
702
        Map<String, PriorityChildConfig> configs, List<String> priorities) {
1✔
703
      this.addresses = addresses;
1✔
704
      this.priorityChildConfigs = configs;
1✔
705
      this.priorities = priorities;
1✔
706
    }
1✔
707
  }
708

709
  /**
710
   * Generates the config to be used in the priority LB policy for the single priority of
711
   * logical DNS cluster.
712
   *
713
   * <p>priority LB -> cluster_impl LB (single hardcoded priority) -> pick_first
714
   */
715
  private static PriorityChildConfig generateDnsBasedPriorityChildConfig(
716
      String cluster, @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
717
      @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata,
718
      LoadBalancerRegistry lbRegistry, List<DropOverload> dropOverloads) {
719
    // Override endpoint-level LB policy with pick_first for logical DNS cluster.
720
    PolicySelection endpointLbPolicy =
1✔
721
        new PolicySelection(lbRegistry.getProvider("pick_first"), null);
1✔
722
    ClusterImplConfig clusterImplConfig =
1✔
723
        new ClusterImplConfig(cluster, null, lrsServerInfo, maxConcurrentRequests,
724
            dropOverloads, endpointLbPolicy, tlsContext, filterMetadata);
725
    LoadBalancerProvider clusterImplLbProvider =
1✔
726
        lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
727
    PolicySelection clusterImplPolicy =
1✔
728
        new PolicySelection(clusterImplLbProvider, clusterImplConfig);
729
    return new PriorityChildConfig(clusterImplPolicy, false /* ignoreReresolution*/);
1✔
730
  }
731

732
  /**
733
   * Generates configs to be used in the priority LB policy for priorities in an EDS cluster.
734
   *
735
   * <p>priority LB -> cluster_impl LB (one per priority) -> (weighted_target LB
736
   * -> round_robin / least_request_experimental (one per locality)) / ring_hash_experimental
737
   */
738
  private static Map<String, PriorityChildConfig> generateEdsBasedPriorityChildConfigs(
739
      String cluster, @Nullable String edsServiceName, @Nullable ServerInfo lrsServerInfo,
740
      @Nullable Long maxConcurrentRequests, @Nullable UpstreamTlsContext tlsContext,
741
      Map<String, Struct> filterMetadata,
742
      @Nullable OutlierDetection outlierDetection, PolicySelection endpointLbPolicy,
743
      LoadBalancerRegistry lbRegistry, Map<String,
744
      Map<Locality, Integer>> prioritizedLocalityWeights, List<DropOverload> dropOverloads) {
745
    Map<String, PriorityChildConfig> configs = new HashMap<>();
1✔
746
    for (String priority : prioritizedLocalityWeights.keySet()) {
1✔
747
      ClusterImplConfig clusterImplConfig =
1✔
748
          new ClusterImplConfig(cluster, edsServiceName, lrsServerInfo, maxConcurrentRequests,
749
              dropOverloads, endpointLbPolicy, tlsContext, filterMetadata);
750
      LoadBalancerProvider clusterImplLbProvider =
1✔
751
          lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
752
      PolicySelection priorityChildPolicy =
1✔
753
          new PolicySelection(clusterImplLbProvider, clusterImplConfig);
754

755
      // If outlier detection has been configured we wrap the child policy in the outlier detection
756
      // load balancer.
757
      if (outlierDetection != null) {
1✔
758
        LoadBalancerProvider outlierDetectionProvider = lbRegistry.getProvider(
1✔
759
            "outlier_detection_experimental");
760
        priorityChildPolicy = new PolicySelection(outlierDetectionProvider,
1✔
761
            buildOutlierDetectionLbConfig(outlierDetection, priorityChildPolicy));
1✔
762
      }
763

764
      PriorityChildConfig priorityChildConfig =
1✔
765
          new PriorityChildConfig(priorityChildPolicy, true /* ignoreReresolution */);
766
      configs.put(priority, priorityChildConfig);
1✔
767
    }
1✔
768
    return configs;
1✔
769
  }
770

771
  /**
772
   * Converts {@link OutlierDetection} that represents the xDS configuration to {@link
773
   * OutlierDetectionLoadBalancerConfig} that the {@link io.grpc.util.OutlierDetectionLoadBalancer}
774
   * understands.
775
   */
776
  private static OutlierDetectionLoadBalancerConfig buildOutlierDetectionLbConfig(
777
      OutlierDetection outlierDetection, PolicySelection childPolicy) {
778
    OutlierDetectionLoadBalancerConfig.Builder configBuilder
1✔
779
        = new OutlierDetectionLoadBalancerConfig.Builder();
780

781
    configBuilder.setChildPolicy(childPolicy);
1✔
782

783
    if (outlierDetection.intervalNanos() != null) {
1✔
784
      configBuilder.setIntervalNanos(outlierDetection.intervalNanos());
1✔
785
    }
786
    if (outlierDetection.baseEjectionTimeNanos() != null) {
1✔
787
      configBuilder.setBaseEjectionTimeNanos(outlierDetection.baseEjectionTimeNanos());
1✔
788
    }
789
    if (outlierDetection.maxEjectionTimeNanos() != null) {
1✔
790
      configBuilder.setMaxEjectionTimeNanos(outlierDetection.maxEjectionTimeNanos());
1✔
791
    }
792
    if (outlierDetection.maxEjectionPercent() != null) {
1✔
793
      configBuilder.setMaxEjectionPercent(outlierDetection.maxEjectionPercent());
1✔
794
    }
795

796
    SuccessRateEjection successRate = outlierDetection.successRateEjection();
1✔
797
    if (successRate != null) {
1✔
798
      OutlierDetectionLoadBalancerConfig.SuccessRateEjection.Builder
799
          successRateConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
800
          .SuccessRateEjection.Builder();
801

802
      if (successRate.stdevFactor() != null) {
1✔
803
        successRateConfigBuilder.setStdevFactor(successRate.stdevFactor());
1✔
804
      }
805
      if (successRate.enforcementPercentage() != null) {
1✔
806
        successRateConfigBuilder.setEnforcementPercentage(successRate.enforcementPercentage());
1✔
807
      }
808
      if (successRate.minimumHosts() != null) {
1✔
809
        successRateConfigBuilder.setMinimumHosts(successRate.minimumHosts());
1✔
810
      }
811
      if (successRate.requestVolume() != null) {
1✔
812
        successRateConfigBuilder.setRequestVolume(successRate.requestVolume());
1✔
813
      }
814

815
      configBuilder.setSuccessRateEjection(successRateConfigBuilder.build());
1✔
816
    }
817

818
    FailurePercentageEjection failurePercentage = outlierDetection.failurePercentageEjection();
1✔
819
    if (failurePercentage != null) {
1✔
820
      OutlierDetectionLoadBalancerConfig.FailurePercentageEjection.Builder
821
          failurePercentageConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
822
          .FailurePercentageEjection.Builder();
823

824
      if (failurePercentage.threshold() != null) {
1✔
825
        failurePercentageConfigBuilder.setThreshold(failurePercentage.threshold());
1✔
826
      }
827
      if (failurePercentage.enforcementPercentage() != null) {
1✔
828
        failurePercentageConfigBuilder.setEnforcementPercentage(
1✔
829
            failurePercentage.enforcementPercentage());
1✔
830
      }
831
      if (failurePercentage.minimumHosts() != null) {
1✔
832
        failurePercentageConfigBuilder.setMinimumHosts(failurePercentage.minimumHosts());
1✔
833
      }
834
      if (failurePercentage.requestVolume() != null) {
1✔
835
        failurePercentageConfigBuilder.setRequestVolume(failurePercentage.requestVolume());
1✔
836
      }
837

838
      configBuilder.setFailurePercentageEjection(failurePercentageConfigBuilder.build());
1✔
839
    }
840

841
    return configBuilder.build();
1✔
842
  }
843

844
  /**
845
   * Generates a string that represents the priority in the LB policy config. The string is unique
846
   * across priorities in all clusters and priorityName(c, p1) < priorityName(c, p2) iff p1 < p2.
847
   * The ordering is undefined for priorities in different clusters.
848
   */
849
  private static String priorityName(String cluster, int priority) {
850
    return cluster + "[child" + priority + "]";
1✔
851
  }
852

853
  /**
854
   * Generates a string that represents the locality in the LB policy config. The string is unique
855
   * across all localities in all clusters.
856
   */
857
  private static String localityName(Locality locality) {
858
    return "{region=\"" + locality.region()
1✔
859
        + "\", zone=\"" + locality.zone()
1✔
860
        + "\", sub_zone=\"" + locality.subZone()
1✔
861
        + "\"}";
862
  }
863
}
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