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

grpc / grpc-java / #19535

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

push

github

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

Implementation of A81.

33970 of 40167 relevant lines covered (84.57%)

0.85 hits per line

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

95.68
/../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.util.ForwardingLoadBalancerHelper;
41
import io.grpc.util.GracefulSwitchLoadBalancer;
42
import io.grpc.util.OutlierDetectionLoadBalancer.OutlierDetectionLoadBalancerConfig;
43
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
44
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig;
45
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig.DiscoveryMechanism;
46
import io.grpc.xds.Endpoints.DropOverload;
47
import io.grpc.xds.Endpoints.LbEndpoint;
48
import io.grpc.xds.Endpoints.LocalityLbEndpoints;
49
import io.grpc.xds.EnvoyServerProtoData.FailurePercentageEjection;
50
import io.grpc.xds.EnvoyServerProtoData.OutlierDetection;
51
import io.grpc.xds.EnvoyServerProtoData.SuccessRateEjection;
52
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
53
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig;
54
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig.PriorityChildConfig;
55
import io.grpc.xds.XdsEndpointResource.EdsUpdate;
56
import io.grpc.xds.client.Bootstrapper.ServerInfo;
57
import io.grpc.xds.client.Locality;
58
import io.grpc.xds.client.XdsClient;
59
import io.grpc.xds.client.XdsClient.ResourceWatcher;
60
import io.grpc.xds.client.XdsLogger;
61
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
62
import java.net.URI;
63
import java.net.URISyntaxException;
64
import java.util.ArrayList;
65
import java.util.Arrays;
66
import java.util.Collections;
67
import java.util.HashMap;
68
import java.util.HashSet;
69
import java.util.List;
70
import java.util.Locale;
71
import java.util.Map;
72
import java.util.Objects;
73
import java.util.Set;
74
import java.util.TreeMap;
75
import java.util.concurrent.ScheduledExecutorService;
76
import java.util.concurrent.TimeUnit;
77
import javax.annotation.Nullable;
78

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

341
      protected boolean shutdown;
342

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

354
      abstract void start();
355

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

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

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

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

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

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

469
        new EndpointsUpdated().run();
1✔
470
      }
1✔
471

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

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

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

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

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

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

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

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

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

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

609
      private class NameResolverListener extends NameResolver.Listener2 {
610
        private final String dnsHostName;
611

612
        NameResolverListener(String dnsHostName) {
1✔
613
          this.dnsHostName = dnsHostName;
1✔
614
        }
1✔
615

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

651
          syncContext.execute(new NameResolved());
1✔
652
        }
1✔
653

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

696
  private static class ClusterResolutionResult {
697
    // Endpoint addresses.
698
    private final List<EquivalentAddressGroup> addresses;
699
    // Config (include load balancing policy/config) for each priority in the cluster.
700
    private final Map<String, PriorityChildConfig> priorityChildConfigs;
701
    // List of priority names ordered in descending priorities.
702
    private final List<String> priorities;
703

704
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses, String priority,
705
        PriorityChildConfig config) {
706
      this(addresses, Collections.singletonMap(priority, config),
1✔
707
          Collections.singletonList(priority));
1✔
708
    }
1✔
709

710
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses,
711
        Map<String, PriorityChildConfig> configs, List<String> priorities) {
1✔
712
      this.addresses = addresses;
1✔
713
      this.priorityChildConfigs = configs;
1✔
714
      this.priorities = priorities;
1✔
715
    }
1✔
716
  }
717

718
  /**
719
   * Generates the config to be used in the priority LB policy for the single priority of
720
   * logical DNS cluster.
721
   *
722
   * <p>priority LB -> cluster_impl LB (single hardcoded priority) -> pick_first
723
   */
724
  private static PriorityChildConfig generateDnsBasedPriorityChildConfig(
725
      String cluster, @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
726
      @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata,
727
      LoadBalancerRegistry lbRegistry, List<DropOverload> dropOverloads) {
728
    // Override endpoint-level LB policy with pick_first for logical DNS cluster.
729
    Object endpointLbConfig = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
730
        lbRegistry.getProvider("pick_first"), null);
1✔
731
    ClusterImplConfig clusterImplConfig =
1✔
732
        new ClusterImplConfig(cluster, null, lrsServerInfo, maxConcurrentRequests,
733
            dropOverloads, endpointLbConfig, tlsContext, filterMetadata);
734
    LoadBalancerProvider clusterImplLbProvider =
1✔
735
        lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
736
    Object clusterImplPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
737
        clusterImplLbProvider, clusterImplConfig);
738
    return new PriorityChildConfig(clusterImplPolicy, false /* ignoreReresolution*/);
1✔
739
  }
740

741
  /**
742
   * Generates configs to be used in the priority LB policy for priorities in an EDS cluster.
743
   *
744
   * <p>priority LB -> cluster_impl LB (one per priority) -> (weighted_target LB
745
   * -> round_robin / least_request_experimental (one per locality)) / ring_hash_experimental
746
   */
747
  private static Map<String, PriorityChildConfig> generateEdsBasedPriorityChildConfigs(
748
      String cluster, @Nullable String edsServiceName, @Nullable ServerInfo lrsServerInfo,
749
      @Nullable Long maxConcurrentRequests, @Nullable UpstreamTlsContext tlsContext,
750
      Map<String, Struct> filterMetadata,
751
      @Nullable OutlierDetection outlierDetection, Object endpointLbConfig,
752
      LoadBalancerRegistry lbRegistry, Map<String,
753
      Map<Locality, Integer>> prioritizedLocalityWeights, List<DropOverload> dropOverloads) {
754
    Map<String, PriorityChildConfig> configs = new HashMap<>();
1✔
755
    for (String priority : prioritizedLocalityWeights.keySet()) {
1✔
756
      ClusterImplConfig clusterImplConfig =
1✔
757
          new ClusterImplConfig(cluster, edsServiceName, lrsServerInfo, maxConcurrentRequests,
758
              dropOverloads, endpointLbConfig, tlsContext, filterMetadata);
759
      LoadBalancerProvider clusterImplLbProvider =
1✔
760
          lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
761
      Object priorityChildPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
762
          clusterImplLbProvider, clusterImplConfig);
763

764
      // If outlier detection has been configured we wrap the child policy in the outlier detection
765
      // load balancer.
766
      if (outlierDetection != null) {
1✔
767
        LoadBalancerProvider outlierDetectionProvider = lbRegistry.getProvider(
1✔
768
            "outlier_detection_experimental");
769
        priorityChildPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
770
            outlierDetectionProvider,
771
            buildOutlierDetectionLbConfig(outlierDetection, priorityChildPolicy));
1✔
772
      }
773

774
      PriorityChildConfig priorityChildConfig =
1✔
775
          new PriorityChildConfig(priorityChildPolicy, true /* ignoreReresolution */);
776
      configs.put(priority, priorityChildConfig);
1✔
777
    }
1✔
778
    return configs;
1✔
779
  }
780

781
  /**
782
   * Converts {@link OutlierDetection} that represents the xDS configuration to {@link
783
   * OutlierDetectionLoadBalancerConfig} that the {@link io.grpc.util.OutlierDetectionLoadBalancer}
784
   * understands.
785
   */
786
  private static OutlierDetectionLoadBalancerConfig buildOutlierDetectionLbConfig(
787
      OutlierDetection outlierDetection, Object childConfig) {
788
    OutlierDetectionLoadBalancerConfig.Builder configBuilder
1✔
789
        = new OutlierDetectionLoadBalancerConfig.Builder();
790

791
    configBuilder.setChildConfig(childConfig);
1✔
792

793
    if (outlierDetection.intervalNanos() != null) {
1✔
794
      configBuilder.setIntervalNanos(outlierDetection.intervalNanos());
1✔
795
    }
796
    if (outlierDetection.baseEjectionTimeNanos() != null) {
1✔
797
      configBuilder.setBaseEjectionTimeNanos(outlierDetection.baseEjectionTimeNanos());
1✔
798
    }
799
    if (outlierDetection.maxEjectionTimeNanos() != null) {
1✔
800
      configBuilder.setMaxEjectionTimeNanos(outlierDetection.maxEjectionTimeNanos());
1✔
801
    }
802
    if (outlierDetection.maxEjectionPercent() != null) {
1✔
803
      configBuilder.setMaxEjectionPercent(outlierDetection.maxEjectionPercent());
1✔
804
    }
805

806
    SuccessRateEjection successRate = outlierDetection.successRateEjection();
1✔
807
    if (successRate != null) {
1✔
808
      OutlierDetectionLoadBalancerConfig.SuccessRateEjection.Builder
809
          successRateConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
810
          .SuccessRateEjection.Builder();
811

812
      if (successRate.stdevFactor() != null) {
1✔
813
        successRateConfigBuilder.setStdevFactor(successRate.stdevFactor());
1✔
814
      }
815
      if (successRate.enforcementPercentage() != null) {
1✔
816
        successRateConfigBuilder.setEnforcementPercentage(successRate.enforcementPercentage());
1✔
817
      }
818
      if (successRate.minimumHosts() != null) {
1✔
819
        successRateConfigBuilder.setMinimumHosts(successRate.minimumHosts());
1✔
820
      }
821
      if (successRate.requestVolume() != null) {
1✔
822
        successRateConfigBuilder.setRequestVolume(successRate.requestVolume());
1✔
823
      }
824

825
      configBuilder.setSuccessRateEjection(successRateConfigBuilder.build());
1✔
826
    }
827

828
    FailurePercentageEjection failurePercentage = outlierDetection.failurePercentageEjection();
1✔
829
    if (failurePercentage != null) {
1✔
830
      OutlierDetectionLoadBalancerConfig.FailurePercentageEjection.Builder
831
          failurePercentageConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
832
          .FailurePercentageEjection.Builder();
833

834
      if (failurePercentage.threshold() != null) {
1✔
835
        failurePercentageConfigBuilder.setThreshold(failurePercentage.threshold());
1✔
836
      }
837
      if (failurePercentage.enforcementPercentage() != null) {
1✔
838
        failurePercentageConfigBuilder.setEnforcementPercentage(
1✔
839
            failurePercentage.enforcementPercentage());
1✔
840
      }
841
      if (failurePercentage.minimumHosts() != null) {
1✔
842
        failurePercentageConfigBuilder.setMinimumHosts(failurePercentage.minimumHosts());
1✔
843
      }
844
      if (failurePercentage.requestVolume() != null) {
1✔
845
        failurePercentageConfigBuilder.setRequestVolume(failurePercentage.requestVolume());
1✔
846
      }
847

848
      configBuilder.setFailurePercentageEjection(failurePercentageConfigBuilder.build());
1✔
849
    }
850

851
    return configBuilder.build();
1✔
852
  }
853

854
  /**
855
   * Generates a string that represents the priority in the LB policy config. The string is unique
856
   * across priorities in all clusters and priorityName(c, p1) < priorityName(c, p2) iff p1 < p2.
857
   * The ordering is undefined for priorities in different clusters.
858
   */
859
  private static String priorityName(String cluster, int priority) {
860
    return cluster + "[child" + priority + "]";
1✔
861
  }
862

863
  /**
864
   * Generates a string that represents the locality in the LB policy config. The string is unique
865
   * across all localities in all clusters.
866
   */
867
  private static String localityName(Locality locality) {
868
    return "{region=\"" + locality.region()
1✔
869
        + "\", zone=\"" + locality.zone()
1✔
870
        + "\", sub_zone=\"" + locality.subZone()
1✔
871
        + "\"}";
872
  }
873
}
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