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

grpc / grpc-java / #19770

07 Apr 2025 03:06PM UTC coverage: 88.595% (+0.007%) from 88.588%
#19770

push

github

web-flow
xds: ClusterResolverLoadBalancer handle update for both resolved addresses and errors via ResolutionResult (#11997) (#12006)

Backport of #11997 to v1.72.x.
------
Fixes #11995

34613 of 39069 relevant lines covered (88.59%)

0.89 hits per line

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

95.02
/../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.HttpConnectProxiedSocketAddress;
29
import io.grpc.InternalLogId;
30
import io.grpc.LoadBalancer;
31
import io.grpc.LoadBalancerProvider;
32
import io.grpc.LoadBalancerRegistry;
33
import io.grpc.NameResolver;
34
import io.grpc.NameResolver.ResolutionResult;
35
import io.grpc.Status;
36
import io.grpc.StatusOr;
37
import io.grpc.SynchronizationContext;
38
import io.grpc.SynchronizationContext.ScheduledHandle;
39
import io.grpc.internal.BackoffPolicy;
40
import io.grpc.internal.ExponentialBackoffPolicy;
41
import io.grpc.internal.ObjectPool;
42
import io.grpc.util.ForwardingLoadBalancerHelper;
43
import io.grpc.util.GracefulSwitchLoadBalancer;
44
import io.grpc.util.OutlierDetectionLoadBalancer.OutlierDetectionLoadBalancerConfig;
45
import io.grpc.xds.ClusterImplLoadBalancerProvider.ClusterImplConfig;
46
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig;
47
import io.grpc.xds.ClusterResolverLoadBalancerProvider.ClusterResolverConfig.DiscoveryMechanism;
48
import io.grpc.xds.Endpoints.DropOverload;
49
import io.grpc.xds.Endpoints.LbEndpoint;
50
import io.grpc.xds.Endpoints.LocalityLbEndpoints;
51
import io.grpc.xds.EnvoyServerProtoData.FailurePercentageEjection;
52
import io.grpc.xds.EnvoyServerProtoData.OutlierDetection;
53
import io.grpc.xds.EnvoyServerProtoData.SuccessRateEjection;
54
import io.grpc.xds.EnvoyServerProtoData.UpstreamTlsContext;
55
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig;
56
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig.PriorityChildConfig;
57
import io.grpc.xds.XdsEndpointResource.EdsUpdate;
58
import io.grpc.xds.client.Bootstrapper.ServerInfo;
59
import io.grpc.xds.client.Locality;
60
import io.grpc.xds.client.XdsClient;
61
import io.grpc.xds.client.XdsClient.ResourceWatcher;
62
import io.grpc.xds.client.XdsLogger;
63
import io.grpc.xds.client.XdsLogger.XdsLogLevel;
64
import java.net.InetSocketAddress;
65
import java.net.SocketAddress;
66
import java.net.URI;
67
import java.net.URISyntaxException;
68
import java.util.ArrayList;
69
import java.util.Arrays;
70
import java.util.Collections;
71
import java.util.HashMap;
72
import java.util.HashSet;
73
import java.util.List;
74
import java.util.Locale;
75
import java.util.Map;
76
import java.util.Objects;
77
import java.util.Set;
78
import java.util.TreeMap;
79
import java.util.concurrent.ScheduledExecutorService;
80
import java.util.concurrent.TimeUnit;
81
import javax.annotation.Nullable;
82

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

104
  ClusterResolverLoadBalancer(Helper helper) {
105
    this(helper, LoadBalancerRegistry.getDefaultRegistry(),
1✔
106
        new ExponentialBackoffPolicy.Provider());
107
  }
1✔
108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

303
      private RefreshableHelper(Helper delegate) {
1✔
304
        this.delegate = checkNotNull(delegate, "delegate");
1✔
305
      }
1✔
306

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

316
      @Override
317
      protected Helper delegate() {
318
        return delegate;
1✔
319
      }
320
    }
321

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

345
      protected boolean shutdown;
346

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

358
      abstract void start();
359

360
      void shutdown() {
361
        shutdown = true;
1✔
362
      }
1✔
363
    }
364

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

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

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

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

396
      @Override
397
      public void onChanged(final EdsUpdate update) {
398
        class EndpointsUpdated implements Runnable {
1✔
399
          @Override
400
          public void run() {
401
            if (shutdown) {
1✔
402
              return;
×
403
            }
404
            logger.log(XdsLogLevel.DEBUG, "Received endpoint update {0}", update);
1✔
405
            if (logger.isLoggable(XdsLogLevel.INFO)) {
1✔
406
              logger.log(XdsLogLevel.INFO, "Cluster {0}: {1} localities, {2} drop categories",
×
407
                  update.clusterName, update.localityLbEndpointsMap.size(),
×
408
                  update.dropPolicies.size());
×
409
            }
410
            Map<Locality, LocalityLbEndpoints> localityLbEndpoints =
1✔
411
                update.localityLbEndpointsMap;
412
            List<DropOverload> dropOverloads = update.dropPolicies;
1✔
413
            List<EquivalentAddressGroup> addresses = new ArrayList<>();
1✔
414
            Map<String, Map<Locality, Integer>> prioritizedLocalityWeights = new HashMap<>();
1✔
415
            List<String> sortedPriorityNames = generatePriorityNames(name, localityLbEndpoints);
1✔
416
            for (Locality locality : localityLbEndpoints.keySet()) {
1✔
417
              LocalityLbEndpoints localityLbInfo = localityLbEndpoints.get(locality);
1✔
418
              String priorityName = localityPriorityNames.get(locality);
1✔
419
              boolean discard = true;
1✔
420
              for (LbEndpoint endpoint : localityLbInfo.endpoints()) {
1✔
421
                if (endpoint.isHealthy()) {
1✔
422
                  discard = false;
1✔
423
                  long weight = localityLbInfo.localityWeight();
1✔
424
                  if (endpoint.loadBalancingWeight() != 0) {
1✔
425
                    weight *= endpoint.loadBalancingWeight();
1✔
426
                  }
427
                  String localityName = localityName(locality);
1✔
428
                  Attributes attr =
1✔
429
                      endpoint.eag().getAttributes().toBuilder()
1✔
430
                          .set(XdsAttributes.ATTR_LOCALITY, locality)
1✔
431
                          .set(XdsAttributes.ATTR_LOCALITY_NAME, localityName)
1✔
432
                          .set(XdsAttributes.ATTR_LOCALITY_WEIGHT,
1✔
433
                              localityLbInfo.localityWeight())
1✔
434
                          .set(XdsAttributes.ATTR_SERVER_WEIGHT, weight)
1✔
435
                          .set(XdsAttributes.ATTR_ADDRESS_NAME, endpoint.hostname())
1✔
436
                          .build();
1✔
437

438
                  EquivalentAddressGroup eag;
439
                  if (config.isHttp11ProxyAvailable()) {
1✔
440
                    List<SocketAddress> rewrittenAddresses = new ArrayList<>();
1✔
441
                    for (SocketAddress addr : endpoint.eag().getAddresses()) {
1✔
442
                      rewrittenAddresses.add(rewriteAddress(
1✔
443
                          addr, endpoint.endpointMetadata(), localityLbInfo.localityMetadata()));
1✔
444
                    }
1✔
445
                    eag = new EquivalentAddressGroup(rewrittenAddresses, attr);
1✔
446
                  } else {
1✔
447
                    eag = new EquivalentAddressGroup(endpoint.eag().getAddresses(), attr);
1✔
448
                  }
449
                  eag = AddressFilter.setPathFilter(eag, Arrays.asList(priorityName, localityName));
1✔
450
                  addresses.add(eag);
1✔
451
                }
452
              }
1✔
453
              if (discard) {
1✔
454
                logger.log(XdsLogLevel.INFO,
1✔
455
                    "Discard locality {0} with 0 healthy endpoints", locality);
456
                continue;
1✔
457
              }
458
              if (!prioritizedLocalityWeights.containsKey(priorityName)) {
1✔
459
                prioritizedLocalityWeights.put(priorityName, new HashMap<Locality, Integer>());
1✔
460
              }
461
              prioritizedLocalityWeights.get(priorityName).put(
1✔
462
                  locality, localityLbInfo.localityWeight());
1✔
463
            }
1✔
464
            if (prioritizedLocalityWeights.isEmpty()) {
1✔
465
              // Will still update the result, as if the cluster resource is revoked.
466
              logger.log(XdsLogLevel.INFO,
1✔
467
                  "Cluster {0} has no usable priority/locality/endpoint", update.clusterName);
468
            }
469
            sortedPriorityNames.retainAll(prioritizedLocalityWeights.keySet());
1✔
470
            Map<String, PriorityChildConfig> priorityChildConfigs =
1✔
471
                generateEdsBasedPriorityChildConfigs(
1✔
472
                    name, edsServiceName, lrsServerInfo, maxConcurrentRequests, tlsContext,
1✔
473
                    filterMetadata, outlierDetection, endpointLbConfig, lbRegistry,
1✔
474
                    prioritizedLocalityWeights, dropOverloads);
475
            status = Status.OK;
1✔
476
            resolved = true;
1✔
477
            result = new ClusterResolutionResult(addresses, priorityChildConfigs,
1✔
478
                sortedPriorityNames);
479
            handleEndpointResourceUpdate();
1✔
480
          }
1✔
481
        }
482

483
        new EndpointsUpdated().run();
1✔
484
      }
1✔
485

486
      private SocketAddress rewriteAddress(SocketAddress addr,
487
          ImmutableMap<String, Object> endpointMetadata,
488
          ImmutableMap<String, Object> localityMetadata) {
489
        if (!(addr instanceof InetSocketAddress)) {
1✔
490
          return addr;
×
491
        }
492

493
        SocketAddress proxyAddress;
494
        try {
495
          proxyAddress = (SocketAddress) endpointMetadata.get(
1✔
496
              "envoy.http11_proxy_transport_socket.proxy_address");
497
          if (proxyAddress == null) {
1✔
498
            proxyAddress = (SocketAddress) localityMetadata.get(
1✔
499
                "envoy.http11_proxy_transport_socket.proxy_address");
500
          }
501
        } catch (ClassCastException e) {
×
502
          return addr;
×
503
        }
1✔
504

505
        if (proxyAddress == null) {
1✔
506
          return addr;
×
507
        }
508

509
        return HttpConnectProxiedSocketAddress.newBuilder()
1✔
510
            .setTargetAddress((InetSocketAddress) addr)
1✔
511
            .setProxyAddress(proxyAddress)
1✔
512
            .build();
1✔
513
      }
514

515
      private List<String> generatePriorityNames(String name,
516
          Map<Locality, LocalityLbEndpoints> localityLbEndpoints) {
517
        TreeMap<Integer, List<Locality>> todo = new TreeMap<>();
1✔
518
        for (Locality locality : localityLbEndpoints.keySet()) {
1✔
519
          int priority = localityLbEndpoints.get(locality).priority();
1✔
520
          if (!todo.containsKey(priority)) {
1✔
521
            todo.put(priority, new ArrayList<>());
1✔
522
          }
523
          todo.get(priority).add(locality);
1✔
524
        }
1✔
525
        Map<Locality, String> newNames = new HashMap<>();
1✔
526
        Set<String> usedNames = new HashSet<>();
1✔
527
        List<String> ret = new ArrayList<>();
1✔
528
        for (Integer priority: todo.keySet()) {
1✔
529
          String foundName = "";
1✔
530
          for (Locality locality : todo.get(priority)) {
1✔
531
            if (localityPriorityNames.containsKey(locality)
1✔
532
                && usedNames.add(localityPriorityNames.get(locality))) {
1✔
533
              foundName = localityPriorityNames.get(locality);
1✔
534
              break;
1✔
535
            }
536
          }
1✔
537
          if ("".equals(foundName)) {
1✔
538
            foundName = String.format(Locale.US, "%s[child%d]", name, priorityNameGenId++);
1✔
539
          }
540
          for (Locality locality : todo.get(priority)) {
1✔
541
            newNames.put(locality, foundName);
1✔
542
          }
1✔
543
          ret.add(foundName);
1✔
544
        }
1✔
545
        localityPriorityNames = newNames;
1✔
546
        return ret;
1✔
547
      }
548

549
      @Override
550
      public void onResourceDoesNotExist(final String resourceName) {
551
        if (shutdown) {
1✔
552
          return;
×
553
        }
554
        logger.log(XdsLogLevel.INFO, "Resource {0} unavailable", resourceName);
1✔
555
        status = Status.OK;
1✔
556
        resolved = true;
1✔
557
        result = null;  // resource revoked
1✔
558
        handleEndpointResourceUpdate();
1✔
559
      }
1✔
560

561
      @Override
562
      public void onError(final Status error) {
563
        if (shutdown) {
1✔
564
          return;
×
565
        }
566
        String resourceName = edsServiceName != null ? edsServiceName : name;
1✔
567
        status = Status.UNAVAILABLE
1✔
568
            .withDescription(String.format("Unable to load EDS %s. xDS server returned: %s: %s",
1✔
569
                  resourceName, error.getCode(), error.getDescription()))
1✔
570
            .withCause(error.getCause());
1✔
571
        logger.log(XdsLogLevel.WARNING, "Received EDS error: {0}", error);
1✔
572
        handleEndpointResolutionError();
1✔
573
      }
1✔
574
    }
575

576
    private final class LogicalDnsClusterState extends ClusterState {
577
      private final String dnsHostName;
578
      private final NameResolver.Factory nameResolverFactory;
579
      private final NameResolver.Args nameResolverArgs;
580
      private NameResolver resolver;
581
      @Nullable
582
      private BackoffPolicy backoffPolicy;
583
      @Nullable
584
      private ScheduledHandle scheduledRefresh;
585

586
      private LogicalDnsClusterState(String name, String dnsHostName,
587
          @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
588
          @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata) {
1✔
589
        super(name, lrsServerInfo, maxConcurrentRequests, tlsContext, filterMetadata, null);
1✔
590
        this.dnsHostName = checkNotNull(dnsHostName, "dnsHostName");
1✔
591
        nameResolverFactory =
1✔
592
            checkNotNull(helper.getNameResolverRegistry().asFactory(), "nameResolverFactory");
1✔
593
        nameResolverArgs = checkNotNull(helper.getNameResolverArgs(), "nameResolverArgs");
1✔
594
      }
1✔
595

596
      @Override
597
      void start() {
598
        URI uri;
599
        try {
600
          uri = new URI("dns", "", "/" + dnsHostName, null);
1✔
601
        } catch (URISyntaxException e) {
×
602
          status = Status.INTERNAL.withDescription(
×
603
              "Bug, invalid URI creation: " + dnsHostName).withCause(e);
×
604
          handleEndpointResolutionError();
×
605
          return;
×
606
        }
1✔
607
        resolver = nameResolverFactory.newNameResolver(uri, nameResolverArgs);
1✔
608
        if (resolver == null) {
1✔
609
          status = Status.INTERNAL.withDescription("Xds cluster resolver lb for logical DNS "
×
610
              + "cluster [" + name + "] cannot find DNS resolver with uri:" + uri);
611
          handleEndpointResolutionError();
×
612
          return;
×
613
        }
614
        resolver.start(new NameResolverListener(dnsHostName));
1✔
615
      }
1✔
616

617
      void refresh() {
618
        if (resolver == null) {
1✔
619
          return;
×
620
        }
621
        cancelBackoff();
1✔
622
        resolver.refresh();
1✔
623
      }
1✔
624

625
      @Override
626
      void shutdown() {
627
        super.shutdown();
1✔
628
        if (resolver != null) {
1✔
629
          resolver.shutdown();
1✔
630
        }
631
        cancelBackoff();
1✔
632
      }
1✔
633

634
      private void cancelBackoff() {
635
        if (scheduledRefresh != null) {
1✔
636
          scheduledRefresh.cancel();
1✔
637
          scheduledRefresh = null;
1✔
638
          backoffPolicy = null;
1✔
639
        }
640
      }
1✔
641

642
      private class DelayedNameResolverRefresh implements Runnable {
1✔
643
        @Override
644
        public void run() {
645
          scheduledRefresh = null;
1✔
646
          if (!shutdown) {
1✔
647
            resolver.refresh();
1✔
648
          }
649
        }
1✔
650
      }
651

652
      private class NameResolverListener extends NameResolver.Listener2 {
653
        private final String dnsHostName;
654

655
        NameResolverListener(String dnsHostName) {
1✔
656
          this.dnsHostName = dnsHostName;
1✔
657
        }
1✔
658

659
        @Override
660
        public void onResult(final ResolutionResult resolutionResult) {
661
          syncContext.execute(() -> onResult2(resolutionResult));
1✔
662
        }
1✔
663

664
        @Override
665
        public Status onResult2(final ResolutionResult resolutionResult) {
666
          if (shutdown) {
1✔
667
            return Status.OK;
×
668
          }
669
          // Arbitrary priority notation for all DNS-resolved endpoints.
670
          String priorityName = priorityName(name, 0);  // value doesn't matter
1✔
671
          List<EquivalentAddressGroup> addresses = new ArrayList<>();
1✔
672
          StatusOr<List<EquivalentAddressGroup>> addressesOrError =
1✔
673
                  resolutionResult.getAddressesOrError();
1✔
674
          if (addressesOrError.hasValue()) {
1✔
675
            backoffPolicy = null;  // reset backoff sequence if succeeded
1✔
676
            for (EquivalentAddressGroup eag : resolutionResult.getAddresses()) {
1✔
677
              // No weight attribute is attached, all endpoint-level LB policy should be able
678
              // to handle such it.
679
              String localityName = localityName(LOGICAL_DNS_CLUSTER_LOCALITY);
1✔
680
              Attributes attr = eag.getAttributes().toBuilder()
1✔
681
                      .set(XdsAttributes.ATTR_LOCALITY, LOGICAL_DNS_CLUSTER_LOCALITY)
1✔
682
                      .set(XdsAttributes.ATTR_LOCALITY_NAME, localityName)
1✔
683
                      .set(XdsAttributes.ATTR_ADDRESS_NAME, dnsHostName)
1✔
684
                      .build();
1✔
685
              eag = new EquivalentAddressGroup(eag.getAddresses(), attr);
1✔
686
              eag = AddressFilter.setPathFilter(eag, Arrays.asList(priorityName, localityName));
1✔
687
              addresses.add(eag);
1✔
688
            }
1✔
689
            PriorityChildConfig priorityChildConfig = generateDnsBasedPriorityChildConfig(
1✔
690
                    name, lrsServerInfo, maxConcurrentRequests, tlsContext, filterMetadata,
691
                    lbRegistry, Collections.<DropOverload>emptyList());
1✔
692
            status = Status.OK;
1✔
693
            resolved = true;
1✔
694
            result = new ClusterResolutionResult(addresses, priorityName, priorityChildConfig);
1✔
695
            handleEndpointResourceUpdate();
1✔
696
            return Status.OK;
1✔
697
          } else {
698
            handleErrorInSyncContext(addressesOrError.getStatus());
1✔
699
            return addressesOrError.getStatus();
1✔
700
          }
701
        }
702

703
        @Override
704
        public void onError(final Status error) {
705
          syncContext.execute(() -> handleErrorInSyncContext(error));
1✔
706
        }
1✔
707

708
        private void handleErrorInSyncContext(final Status error) {
709
          if (shutdown) {
1✔
710
            return;
×
711
          }
712
          status = error;
1✔
713
          // NameResolver.Listener API cannot distinguish between address-not-found and
714
          // transient errors. If the error occurs in the first resolution, treat it as
715
          // address not found. Otherwise, either there is previously resolved addresses
716
          // previously encountered error, propagate the error to downstream/upstream and
717
          // let downstream/upstream handle it.
718
          if (!resolved) {
1✔
719
            resolved = true;
1✔
720
            handleEndpointResourceUpdate();
1✔
721
          } else {
722
            handleEndpointResolutionError();
1✔
723
          }
724
          if (scheduledRefresh != null && scheduledRefresh.isPending()) {
1✔
725
            return;
×
726
          }
727
          if (backoffPolicy == null) {
1✔
728
            backoffPolicy = backoffPolicyProvider.get();
1✔
729
          }
730
          long delayNanos = backoffPolicy.nextBackoffNanos();
1✔
731
          logger.log(XdsLogLevel.DEBUG,
1✔
732
                  "Logical DNS resolver for cluster {0} encountered name resolution "
733
                          + "error: {1}, scheduling DNS resolution backoff for {2} ns",
734
                  name, error, delayNanos);
1✔
735
          scheduledRefresh =
1✔
736
                  syncContext.schedule(
1✔
737
                          new DelayedNameResolverRefresh(), delayNanos, TimeUnit.NANOSECONDS,
738
                          timeService);
1✔
739
        }
1✔
740
      }
741
    }
742
  }
743

744
  private static class ClusterResolutionResult {
745
    // Endpoint addresses.
746
    private final List<EquivalentAddressGroup> addresses;
747
    // Config (include load balancing policy/config) for each priority in the cluster.
748
    private final Map<String, PriorityChildConfig> priorityChildConfigs;
749
    // List of priority names ordered in descending priorities.
750
    private final List<String> priorities;
751

752
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses, String priority,
753
        PriorityChildConfig config) {
754
      this(addresses, Collections.singletonMap(priority, config),
1✔
755
          Collections.singletonList(priority));
1✔
756
    }
1✔
757

758
    ClusterResolutionResult(List<EquivalentAddressGroup> addresses,
759
        Map<String, PriorityChildConfig> configs, List<String> priorities) {
1✔
760
      this.addresses = addresses;
1✔
761
      this.priorityChildConfigs = configs;
1✔
762
      this.priorities = priorities;
1✔
763
    }
1✔
764
  }
765

766
  /**
767
   * Generates the config to be used in the priority LB policy for the single priority of
768
   * logical DNS cluster.
769
   *
770
   * <p>priority LB -> cluster_impl LB (single hardcoded priority) -> pick_first
771
   */
772
  private static PriorityChildConfig generateDnsBasedPriorityChildConfig(
773
      String cluster, @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests,
774
      @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata,
775
      LoadBalancerRegistry lbRegistry, List<DropOverload> dropOverloads) {
776
    // Override endpoint-level LB policy with pick_first for logical DNS cluster.
777
    Object endpointLbConfig = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
778
        lbRegistry.getProvider("pick_first"), null);
1✔
779
    ClusterImplConfig clusterImplConfig =
1✔
780
        new ClusterImplConfig(cluster, null, lrsServerInfo, maxConcurrentRequests,
781
            dropOverloads, endpointLbConfig, tlsContext, filterMetadata);
782
    LoadBalancerProvider clusterImplLbProvider =
1✔
783
        lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
784
    Object clusterImplPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
785
        clusterImplLbProvider, clusterImplConfig);
786
    return new PriorityChildConfig(clusterImplPolicy, false /* ignoreReresolution*/);
1✔
787
  }
788

789
  /**
790
   * Generates configs to be used in the priority LB policy for priorities in an EDS cluster.
791
   *
792
   * <p>priority LB -> cluster_impl LB (one per priority) -> (weighted_target LB
793
   * -> round_robin / least_request_experimental (one per locality)) / ring_hash_experimental
794
   */
795
  private static Map<String, PriorityChildConfig> generateEdsBasedPriorityChildConfigs(
796
      String cluster, @Nullable String edsServiceName, @Nullable ServerInfo lrsServerInfo,
797
      @Nullable Long maxConcurrentRequests, @Nullable UpstreamTlsContext tlsContext,
798
      Map<String, Struct> filterMetadata,
799
      @Nullable OutlierDetection outlierDetection, Object endpointLbConfig,
800
      LoadBalancerRegistry lbRegistry, Map<String,
801
      Map<Locality, Integer>> prioritizedLocalityWeights, List<DropOverload> dropOverloads) {
802
    Map<String, PriorityChildConfig> configs = new HashMap<>();
1✔
803
    for (String priority : prioritizedLocalityWeights.keySet()) {
1✔
804
      ClusterImplConfig clusterImplConfig =
1✔
805
          new ClusterImplConfig(cluster, edsServiceName, lrsServerInfo, maxConcurrentRequests,
806
              dropOverloads, endpointLbConfig, tlsContext, filterMetadata);
807
      LoadBalancerProvider clusterImplLbProvider =
1✔
808
          lbRegistry.getProvider(XdsLbPolicies.CLUSTER_IMPL_POLICY_NAME);
1✔
809
      Object priorityChildPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
810
          clusterImplLbProvider, clusterImplConfig);
811

812
      // If outlier detection has been configured we wrap the child policy in the outlier detection
813
      // load balancer.
814
      if (outlierDetection != null) {
1✔
815
        LoadBalancerProvider outlierDetectionProvider = lbRegistry.getProvider(
1✔
816
            "outlier_detection_experimental");
817
        priorityChildPolicy = GracefulSwitchLoadBalancer.createLoadBalancingPolicyConfig(
1✔
818
            outlierDetectionProvider,
819
            buildOutlierDetectionLbConfig(outlierDetection, priorityChildPolicy));
1✔
820
      }
821

822
      PriorityChildConfig priorityChildConfig =
1✔
823
          new PriorityChildConfig(priorityChildPolicy, true /* ignoreReresolution */);
824
      configs.put(priority, priorityChildConfig);
1✔
825
    }
1✔
826
    return configs;
1✔
827
  }
828

829
  /**
830
   * Converts {@link OutlierDetection} that represents the xDS configuration to {@link
831
   * OutlierDetectionLoadBalancerConfig} that the {@link io.grpc.util.OutlierDetectionLoadBalancer}
832
   * understands.
833
   */
834
  private static OutlierDetectionLoadBalancerConfig buildOutlierDetectionLbConfig(
835
      OutlierDetection outlierDetection, Object childConfig) {
836
    OutlierDetectionLoadBalancerConfig.Builder configBuilder
1✔
837
        = new OutlierDetectionLoadBalancerConfig.Builder();
838

839
    configBuilder.setChildConfig(childConfig);
1✔
840

841
    if (outlierDetection.intervalNanos() != null) {
1✔
842
      configBuilder.setIntervalNanos(outlierDetection.intervalNanos());
1✔
843
    }
844
    if (outlierDetection.baseEjectionTimeNanos() != null) {
1✔
845
      configBuilder.setBaseEjectionTimeNanos(outlierDetection.baseEjectionTimeNanos());
1✔
846
    }
847
    if (outlierDetection.maxEjectionTimeNanos() != null) {
1✔
848
      configBuilder.setMaxEjectionTimeNanos(outlierDetection.maxEjectionTimeNanos());
1✔
849
    }
850
    if (outlierDetection.maxEjectionPercent() != null) {
1✔
851
      configBuilder.setMaxEjectionPercent(outlierDetection.maxEjectionPercent());
1✔
852
    }
853

854
    SuccessRateEjection successRate = outlierDetection.successRateEjection();
1✔
855
    if (successRate != null) {
1✔
856
      OutlierDetectionLoadBalancerConfig.SuccessRateEjection.Builder
857
          successRateConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
858
          .SuccessRateEjection.Builder();
859

860
      if (successRate.stdevFactor() != null) {
1✔
861
        successRateConfigBuilder.setStdevFactor(successRate.stdevFactor());
1✔
862
      }
863
      if (successRate.enforcementPercentage() != null) {
1✔
864
        successRateConfigBuilder.setEnforcementPercentage(successRate.enforcementPercentage());
1✔
865
      }
866
      if (successRate.minimumHosts() != null) {
1✔
867
        successRateConfigBuilder.setMinimumHosts(successRate.minimumHosts());
1✔
868
      }
869
      if (successRate.requestVolume() != null) {
1✔
870
        successRateConfigBuilder.setRequestVolume(successRate.requestVolume());
1✔
871
      }
872

873
      configBuilder.setSuccessRateEjection(successRateConfigBuilder.build());
1✔
874
    }
875

876
    FailurePercentageEjection failurePercentage = outlierDetection.failurePercentageEjection();
1✔
877
    if (failurePercentage != null) {
1✔
878
      OutlierDetectionLoadBalancerConfig.FailurePercentageEjection.Builder
879
          failurePercentageConfigBuilder = new OutlierDetectionLoadBalancerConfig
1✔
880
          .FailurePercentageEjection.Builder();
881

882
      if (failurePercentage.threshold() != null) {
1✔
883
        failurePercentageConfigBuilder.setThreshold(failurePercentage.threshold());
1✔
884
      }
885
      if (failurePercentage.enforcementPercentage() != null) {
1✔
886
        failurePercentageConfigBuilder.setEnforcementPercentage(
1✔
887
            failurePercentage.enforcementPercentage());
1✔
888
      }
889
      if (failurePercentage.minimumHosts() != null) {
1✔
890
        failurePercentageConfigBuilder.setMinimumHosts(failurePercentage.minimumHosts());
1✔
891
      }
892
      if (failurePercentage.requestVolume() != null) {
1✔
893
        failurePercentageConfigBuilder.setRequestVolume(failurePercentage.requestVolume());
1✔
894
      }
895

896
      configBuilder.setFailurePercentageEjection(failurePercentageConfigBuilder.build());
1✔
897
    }
898

899
    return configBuilder.build();
1✔
900
  }
901

902
  /**
903
   * Generates a string that represents the priority in the LB policy config. The string is unique
904
   * across priorities in all clusters and priorityName(c, p1) < priorityName(c, p2) iff p1 < p2.
905
   * The ordering is undefined for priorities in different clusters.
906
   */
907
  private static String priorityName(String cluster, int priority) {
908
    return cluster + "[child" + priority + "]";
1✔
909
  }
910

911
  /**
912
   * Generates a string that represents the locality in the LB policy config. The string is unique
913
   * across all localities in all clusters.
914
   */
915
  private static String localityName(Locality locality) {
916
    return "{region=\"" + locality.region()
1✔
917
        + "\", zone=\"" + locality.zone()
1✔
918
        + "\", sub_zone=\"" + locality.subZone()
1✔
919
        + "\"}";
920
  }
921
}
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