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

grpc / grpc-java / #19789

23 Apr 2025 04:45AM UTC coverage: 88.551% (-0.001%) from 88.552%
#19789

push

github

web-flow
Update psm-dualstack.cfg (#11950) (#12029)

120 minutes has not been sufficient, causing frequent VM timeout errors in the test runs.

33684 of 38039 relevant lines covered (88.55%)

0.89 hits per line

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

95.72
/../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.StatusOr;
36
import io.grpc.SynchronizationContext;
37
import io.grpc.SynchronizationContext.ScheduledHandle;
38
import io.grpc.internal.BackoffPolicy;
39
import io.grpc.internal.ExponentialBackoffPolicy;
40
import io.grpc.internal.ObjectPool;
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(XdsAttributes.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
      this.config = config;
1✔
131
      Object gracefulConfig = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
132
          new ClusterResolverLbStateFactory(), config);
133
      delegate.handleResolvedAddresses(
1✔
134
          resolvedAddresses.toBuilder().setLoadBalancingPolicyConfig(gracefulConfig).build());
1✔
135
    }
136
    return Status.OK;
1✔
137
  }
138

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

342
      protected boolean shutdown;
343

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

355
      abstract void start();
356

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

617
        @Override
618
        public void onResult(final ResolutionResult resolutionResult) {
619
          syncContext.execute(() -> onResult2(resolutionResult));
1✔
620
        }
1✔
621

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

661
        @Override
662
        public void onError(final Status error) {
663
          syncContext.execute(() -> handleErrorInSyncContext(error));
1✔
664
        }
1✔
665

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

702
  private static class ClusterResolutionResult {
703
    // Endpoint addresses.
704
    private final List<EquivalentAddressGroup> addresses;
705
    // Config (include load balancing policy/config) for each priority in the cluster.
706
    private final Map<String, PriorityChildConfig> priorityChildConfigs;
707
    // List of priority names ordered in descending priorities.
708
    private final List<String> priorities;
709

710
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses, String priority,
711
        PriorityChildConfig config) {
712
      this(addresses, Collections.singletonMap(priority, config),
1✔
713
          Collections.singletonList(priority));
1✔
714
    }
1✔
715

716
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses,
717
        Map<String, PriorityChildConfig> configs, List<String> priorities) {
1✔
718
      this.addresses = addresses;
1✔
719
      this.priorityChildConfigs = configs;
1✔
720
      this.priorities = priorities;
1✔
721
    }
1✔
722
  }
723

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

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

770
      // If outlier detection has been configured we wrap the child policy in the outlier detection
771
      // load balancer.
772
      if (outlierDetection != null) {
1✔
773
        LoadBalancerProvider outlierDetectionProvider = lbRegistry.getProvider(
1✔
774
            "outlier_detection_experimental");
775
        priorityChildPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
776
            outlierDetectionProvider,
777
            buildOutlierDetectionLbConfig(outlierDetection, priorityChildPolicy));
1✔
778
      }
779

780
      PriorityChildConfig priorityChildConfig =
1✔
781
          new PriorityChildConfig(priorityChildPolicy, true /* ignoreReresolution */);
782
      configs.put(priority, priorityChildConfig);
1✔
783
    }
1✔
784
    return configs;
1✔
785
  }
786

787
  /**
788
   * Converts {@link OutlierDetection} that represents the xDS configuration to {@link
789
   * OutlierDetectionLoadBalancerConfig} that the {@link io.grpc.util.OutlierDetectionLoadBalancer}
790
   * understands.
791
   */
792
  private static OutlierDetectionLoadBalancerConfig buildOutlierDetectionLbConfig(
793
      OutlierDetection outlierDetection, Object childConfig) {
794
    OutlierDetectionLoadBalancerConfig.Builder configBuilder
1✔
795
        = new OutlierDetectionLoadBalancerConfig.Builder();
796

797
    configBuilder.setChildConfig(childConfig);
1✔
798

799
    if (outlierDetection.intervalNanos() != null) {
1✔
800
      configBuilder.setIntervalNanos(outlierDetection.intervalNanos());
1✔
801
    }
802
    if (outlierDetection.baseEjectionTimeNanos() != null) {
1✔
803
      configBuilder.setBaseEjectionTimeNanos(outlierDetection.baseEjectionTimeNanos());
1✔
804
    }
805
    if (outlierDetection.maxEjectionTimeNanos() != null) {
1✔
806
      configBuilder.setMaxEjectionTimeNanos(outlierDetection.maxEjectionTimeNanos());
1✔
807
    }
808
    if (outlierDetection.maxEjectionPercent() != null) {
1✔
809
      configBuilder.setMaxEjectionPercent(outlierDetection.maxEjectionPercent());
1✔
810
    }
811

812
    SuccessRateEjection successRate = outlierDetection.successRateEjection();
1✔
813
    if (successRate != null) {
1✔
814
      OutlierDetectionLoadBalancerConfig.SuccessRateEjection.Builder
815
          successRateConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
816
          .SuccessRateEjection.Builder();
817

818
      if (successRate.stdevFactor() != null) {
1✔
819
        successRateConfigBuilder.setStdevFactor(successRate.stdevFactor());
1✔
820
      }
821
      if (successRate.enforcementPercentage() != null) {
1✔
822
        successRateConfigBuilder.setEnforcementPercentage(successRate.enforcementPercentage());
1✔
823
      }
824
      if (successRate.minimumHosts() != null) {
1✔
825
        successRateConfigBuilder.setMinimumHosts(successRate.minimumHosts());
1✔
826
      }
827
      if (successRate.requestVolume() != null) {
1✔
828
        successRateConfigBuilder.setRequestVolume(successRate.requestVolume());
1✔
829
      }
830

831
      configBuilder.setSuccessRateEjection(successRateConfigBuilder.build());
1✔
832
    }
833

834
    FailurePercentageEjection failurePercentage = outlierDetection.failurePercentageEjection();
1✔
835
    if (failurePercentage != null) {
1✔
836
      OutlierDetectionLoadBalancerConfig.FailurePercentageEjection.Builder
837
          failurePercentageConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
838
          .FailurePercentageEjection.Builder();
839

840
      if (failurePercentage.threshold() != null) {
1✔
841
        failurePercentageConfigBuilder.setThreshold(failurePercentage.threshold());
1✔
842
      }
843
      if (failurePercentage.enforcementPercentage() != null) {
1✔
844
        failurePercentageConfigBuilder.setEnforcementPercentage(
1✔
845
            failurePercentage.enforcementPercentage());
1✔
846
      }
847
      if (failurePercentage.minimumHosts() != null) {
1✔
848
        failurePercentageConfigBuilder.setMinimumHosts(failurePercentage.minimumHosts());
1✔
849
      }
850
      if (failurePercentage.requestVolume() != null) {
1✔
851
        failurePercentageConfigBuilder.setRequestVolume(failurePercentage.requestVolume());
1✔
852
      }
853

854
      configBuilder.setFailurePercentageEjection(failurePercentageConfigBuilder.build());
1✔
855
    }
856

857
    return configBuilder.build();
1✔
858
  }
859

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

869
  /**
870
   * Generates a string that represents the locality in the LB policy config. The string is unique
871
   * across all localities in all clusters.
872
   */
873
  private static String localityName(Locality locality) {
874
    return "{region=\"" + locality.region()
1✔
875
        + "\", zone=\"" + locality.zone()
1✔
876
        + "\", sub_zone=\"" + locality.subZone()
1✔
877
        + "\"}";
878
  }
879
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc