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

grpc / grpc-java / #19570

27 Nov 2024 06:59PM UTC coverage: 88.582% (+0.007%) from 88.575%
#19570

push

github

web-flow
Add "#server" as dataplane target value for xDS enabled gRPC servers. (#11715)

As mentioned in [A71 xDS Fallback]( https://github.com/grpc/proposal/blob/master/A71-xds-fallback.md#update-csds-to-aggregate-configs-from-multiple-xdsclient-instances):
updated dataplane target to "#server" for xDS-enabled gRPC servers.

33377 of 37679 relevant lines covered (88.58%)

0.89 hits per line

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

94.22
/../xds/src/main/java/io/grpc/xds/XdsServerWrapper.java
1
/*
2
 * Copyright 2021 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 com.google.common.base.Preconditions.checkState;
21
import static io.grpc.xds.client.Bootstrapper.XDSTP_SCHEME;
22

23
import com.google.auto.value.AutoValue;
24
import com.google.common.annotations.VisibleForTesting;
25
import com.google.common.collect.ImmutableList;
26
import com.google.common.collect.ImmutableMap;
27
import com.google.common.util.concurrent.SettableFuture;
28
import io.grpc.Attributes;
29
import io.grpc.InternalServerInterceptors;
30
import io.grpc.Metadata;
31
import io.grpc.MethodDescriptor;
32
import io.grpc.MetricRecorder;
33
import io.grpc.Server;
34
import io.grpc.ServerBuilder;
35
import io.grpc.ServerCall;
36
import io.grpc.ServerCall.Listener;
37
import io.grpc.ServerCallHandler;
38
import io.grpc.ServerInterceptor;
39
import io.grpc.ServerServiceDefinition;
40
import io.grpc.Status;
41
import io.grpc.StatusException;
42
import io.grpc.SynchronizationContext;
43
import io.grpc.SynchronizationContext.ScheduledHandle;
44
import io.grpc.internal.GrpcUtil;
45
import io.grpc.internal.ObjectPool;
46
import io.grpc.internal.SharedResourceHolder;
47
import io.grpc.xds.EnvoyServerProtoData.FilterChain;
48
import io.grpc.xds.Filter.FilterConfig;
49
import io.grpc.xds.Filter.NamedFilterConfig;
50
import io.grpc.xds.Filter.ServerInterceptorBuilder;
51
import io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler.FilterChainSelector;
52
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
53
import io.grpc.xds.VirtualHost.Route;
54
import io.grpc.xds.XdsListenerResource.LdsUpdate;
55
import io.grpc.xds.XdsRouteConfigureResource.RdsUpdate;
56
import io.grpc.xds.XdsServerBuilder.XdsServingStatusListener;
57
import io.grpc.xds.client.XdsClient;
58
import io.grpc.xds.client.XdsClient.ResourceWatcher;
59
import io.grpc.xds.internal.security.SslContextProviderSupplier;
60
import java.io.IOException;
61
import java.net.SocketAddress;
62
import java.util.ArrayList;
63
import java.util.Collections;
64
import java.util.HashMap;
65
import java.util.HashSet;
66
import java.util.List;
67
import java.util.Map;
68
import java.util.Set;
69
import java.util.concurrent.CountDownLatch;
70
import java.util.concurrent.ExecutionException;
71
import java.util.concurrent.ScheduledExecutorService;
72
import java.util.concurrent.TimeUnit;
73
import java.util.concurrent.atomic.AtomicBoolean;
74
import java.util.concurrent.atomic.AtomicReference;
75
import java.util.logging.Level;
76
import java.util.logging.Logger;
77
import javax.annotation.Nullable;
78

79
final class XdsServerWrapper extends Server {
80
  private static final Logger logger = Logger.getLogger(XdsServerWrapper.class.getName());
1✔
81

82
  private final SynchronizationContext syncContext = new SynchronizationContext(
1✔
83
      new Thread.UncaughtExceptionHandler() {
1✔
84
        @Override
85
        public void uncaughtException(Thread t, Throwable e) {
86
          logger.log(Level.SEVERE, "Exception!" + e);
×
87
          // TODO(chengyuanzhang): implement cleanup.
88
        }
×
89
      });
90

91
  public static final Attributes.Key<AtomicReference<ServerRoutingConfig>>
92
      ATTR_SERVER_ROUTING_CONFIG =
1✔
93
      Attributes.Key.create("io.grpc.xds.ServerWrapper.serverRoutingConfig");
1✔
94

95
  @VisibleForTesting
96
  static final long RETRY_DELAY_NANOS = TimeUnit.MINUTES.toNanos(1);
1✔
97
  private final String listenerAddress;
98
  private final ServerBuilder<?> delegateBuilder;
99
  private boolean sharedTimeService;
100
  private final ScheduledExecutorService timeService;
101
  private final FilterRegistry filterRegistry;
102
  private final ThreadSafeRandom random = ThreadSafeRandomImpl.instance;
1✔
103
  private final XdsClientPoolFactory xdsClientPoolFactory;
104
  private final XdsServingStatusListener listener;
105
  private final FilterChainSelectorManager filterChainSelectorManager;
106
  private final AtomicBoolean started = new AtomicBoolean(false);
1✔
107
  private final AtomicBoolean shutdown = new AtomicBoolean(false);
1✔
108
  private boolean isServing;
109
  private final CountDownLatch internalTerminationLatch = new CountDownLatch(1);
1✔
110
  private final SettableFuture<Exception> initialStartFuture = SettableFuture.create();
1✔
111
  private boolean initialStarted;
112
  private ScheduledHandle restartTimer;
113
  private ObjectPool<XdsClient> xdsClientPool;
114
  private XdsClient xdsClient;
115
  private DiscoveryState discoveryState;
116
  private volatile Server delegate;
117

118
  XdsServerWrapper(
119
      String listenerAddress,
120
      ServerBuilder<?> delegateBuilder,
121
      XdsServingStatusListener listener,
122
      FilterChainSelectorManager filterChainSelectorManager,
123
      XdsClientPoolFactory xdsClientPoolFactory,
124
      FilterRegistry filterRegistry) {
125
    this(listenerAddress, delegateBuilder, listener, filterChainSelectorManager,
1✔
126
        xdsClientPoolFactory, filterRegistry, SharedResourceHolder.get(GrpcUtil.TIMER_SERVICE));
1✔
127
    sharedTimeService = true;
1✔
128
  }
1✔
129

130
  @VisibleForTesting
131
  XdsServerWrapper(
132
          String listenerAddress,
133
          ServerBuilder<?> delegateBuilder,
134
          XdsServingStatusListener listener,
135
          FilterChainSelectorManager filterChainSelectorManager,
136
          XdsClientPoolFactory xdsClientPoolFactory,
137
          FilterRegistry filterRegistry,
138
          ScheduledExecutorService timeService) {
1✔
139
    this.listenerAddress = checkNotNull(listenerAddress, "listenerAddress");
1✔
140
    this.delegateBuilder = checkNotNull(delegateBuilder, "delegateBuilder");
1✔
141
    this.delegateBuilder.intercept(new ConfigApplyingInterceptor());
1✔
142
    this.listener = checkNotNull(listener, "listener");
1✔
143
    this.filterChainSelectorManager
1✔
144
        = checkNotNull(filterChainSelectorManager, "filterChainSelectorManager");
1✔
145
    this.xdsClientPoolFactory = checkNotNull(xdsClientPoolFactory, "xdsClientPoolFactory");
1✔
146
    this.timeService = checkNotNull(timeService, "timeService");
1✔
147
    this.filterRegistry = checkNotNull(filterRegistry,"filterRegistry");
1✔
148
    this.delegate = delegateBuilder.build();
1✔
149
  }
1✔
150

151
  @Override
152
  public Server start() throws IOException {
153
    checkState(started.compareAndSet(false, true), "Already started");
1✔
154
    syncContext.execute(new Runnable() {
1✔
155
      @Override
156
      public void run() {
157
        internalStart();
1✔
158
      }
1✔
159
    });
160
    Exception exception;
161
    try {
162
      exception = initialStartFuture.get();
1✔
163
    } catch (InterruptedException | ExecutionException e) {
×
164
      throw new RuntimeException(e);
×
165
    }
1✔
166
    if (exception != null) {
1✔
167
      throw (exception instanceof IOException) ? (IOException) exception :
1✔
168
              new IOException(exception);
1✔
169
    }
170
    return this;
1✔
171
  }
172

173
  private void internalStart() {
174
    try {
175
      xdsClientPool = xdsClientPoolFactory.getOrCreate("#server", new MetricRecorder() {});
1✔
176
    } catch (Exception e) {
×
177
      StatusException statusException = Status.UNAVAILABLE.withDescription(
×
178
              "Failed to initialize xDS").withCause(e).asException();
×
179
      listener.onNotServing(statusException);
×
180
      initialStartFuture.set(statusException);
×
181
      return;
×
182
    }
1✔
183
    xdsClient = xdsClientPool.getObject();
1✔
184
    String listenerTemplate = xdsClient.getBootstrapInfo().serverListenerResourceNameTemplate();
1✔
185
    if (listenerTemplate == null) {
1✔
186
      StatusException statusException =
1✔
187
          Status.UNAVAILABLE.withDescription(
1✔
188
              "Can only support xDS v3 with listener resource name template").asException();
1✔
189
      listener.onNotServing(statusException);
1✔
190
      initialStartFuture.set(statusException);
1✔
191
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
192
      return;
1✔
193
    }
194
    String replacement = listenerAddress;
1✔
195
    if (listenerTemplate.startsWith(XDSTP_SCHEME)) {
1✔
196
      replacement = XdsClient.percentEncodePath(replacement);
1✔
197
    }
198
    discoveryState = new DiscoveryState(listenerTemplate.replaceAll("%s", replacement));
1✔
199
  }
1✔
200

201
  @Override
202
  public Server shutdown() {
203
    if (!shutdown.compareAndSet(false, true)) {
1✔
204
      return this;
1✔
205
    }
206
    syncContext.execute(new Runnable() {
1✔
207
      @Override
208
      public void run() {
209
        if (!delegate.isShutdown()) {
1✔
210
          delegate.shutdown();
1✔
211
        }
212
        internalShutdown();
1✔
213
      }
1✔
214
    });
215
    return this;
1✔
216
  }
217

218
  @Override
219
  public Server shutdownNow() {
220
    if (!shutdown.compareAndSet(false, true)) {
1✔
221
      return this;
1✔
222
    }
223
    syncContext.execute(new Runnable() {
1✔
224
      @Override
225
      public void run() {
226
        if (!delegate.isShutdown()) {
1✔
227
          delegate.shutdownNow();
1✔
228
        }
229
        internalShutdown();
1✔
230
        initialStartFuture.set(new IOException("server is forcefully shut down"));
1✔
231
      }
1✔
232
    });
233
    return this;
1✔
234
  }
235

236
  // Must run in SynchronizationContext
237
  private void internalShutdown() {
238
    logger.log(Level.FINER, "Shutting down XdsServerWrapper");
1✔
239
    if (discoveryState != null) {
1✔
240
      discoveryState.shutdown();
1✔
241
    }
242
    if (xdsClient != null) {
1✔
243
      xdsClient = xdsClientPool.returnObject(xdsClient);
1✔
244
    }
245
    if (restartTimer != null) {
1✔
246
      restartTimer.cancel();
1✔
247
    }
248
    if (sharedTimeService) {
1✔
249
      SharedResourceHolder.release(GrpcUtil.TIMER_SERVICE, timeService);
1✔
250
    }
251
    isServing = false;
1✔
252
    internalTerminationLatch.countDown();
1✔
253
  }
1✔
254

255
  @Override
256
  public boolean isShutdown() {
257
    return shutdown.get();
1✔
258
  }
259

260
  @Override
261
  public boolean isTerminated() {
262
    return internalTerminationLatch.getCount() == 0 && delegate.isTerminated();
1✔
263
  }
264

265
  @Override
266
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
267
    long startTime = System.nanoTime();
1✔
268
    if (!internalTerminationLatch.await(timeout, unit)) {
1✔
269
      return false;
×
270
    }
271
    long remainingTime = unit.toNanos(timeout) - (System.nanoTime() - startTime);
1✔
272
    return delegate.awaitTermination(remainingTime, TimeUnit.NANOSECONDS);
1✔
273
  }
274

275
  @Override
276
  public void awaitTermination() throws InterruptedException {
277
    internalTerminationLatch.await();
1✔
278
    delegate.awaitTermination();
1✔
279
  }
1✔
280

281
  @Override
282
  public int getPort() {
283
    return delegate.getPort();
1✔
284
  }
285

286
  @Override
287
  public List<? extends SocketAddress> getListenSockets() {
288
    return delegate.getListenSockets();
1✔
289
  }
290

291
  @Override
292
  public List<ServerServiceDefinition> getServices() {
293
    return delegate.getServices();
×
294
  }
295

296
  @Override
297
  public List<ServerServiceDefinition> getImmutableServices() {
298
    return delegate.getImmutableServices();
×
299
  }
300

301
  @Override
302
  public List<ServerServiceDefinition> getMutableServices() {
303
    return delegate.getMutableServices();
×
304
  }
305

306
  // Must run in SynchronizationContext
307
  private void startDelegateServer() {
308
    if (restartTimer != null && restartTimer.isPending()) {
1✔
309
      return;
×
310
    }
311
    if (isServing) {
1✔
312
      return;
1✔
313
    }
314
    if (delegate.isShutdown()) {
1✔
315
      delegate = delegateBuilder.build();
1✔
316
    }
317
    try {
318
      delegate.start();
1✔
319
      listener.onServing();
1✔
320
      isServing = true;
1✔
321
      if (!initialStarted) {
1✔
322
        initialStarted = true;
1✔
323
        initialStartFuture.set(null);
1✔
324
      }
325
      logger.log(Level.FINER, "Delegate server started.");
1✔
326
    } catch (IOException e) {
1✔
327
      logger.log(Level.FINE, "Fail to start delegate server: {0}", e);
1✔
328
      if (!initialStarted) {
1✔
329
        initialStarted = true;
1✔
330
        initialStartFuture.set(e);
1✔
331
      } else {
332
        listener.onNotServing(e);
1✔
333
      }
334
      restartTimer = syncContext.schedule(
1✔
335
        new RestartTask(), RETRY_DELAY_NANOS, TimeUnit.NANOSECONDS, timeService);
336
    }
1✔
337
  }
1✔
338

339
  private final class RestartTask implements Runnable {
1✔
340
    @Override
341
    public void run() {
342
      startDelegateServer();
1✔
343
    }
1✔
344
  }
345

346
  private final class DiscoveryState implements ResourceWatcher<LdsUpdate> {
347
    private final String resourceName;
348
    // RDS resource name is the key.
349
    private final Map<String, RouteDiscoveryState> routeDiscoveryStates = new HashMap<>();
1✔
350
    // Track pending RDS resources using rds name.
351
    private final Set<String> pendingRds = new HashSet<>();
1✔
352
    // Most recently discovered filter chains.
353
    private List<FilterChain> filterChains = new ArrayList<>();
1✔
354
    // Most recently discovered default filter chain.
355
    @Nullable
356
    private FilterChain defaultFilterChain;
357
    private boolean stopped;
358
    private final Map<FilterChain, AtomicReference<ServerRoutingConfig>> savedRdsRoutingConfigRef 
1✔
359
        = new HashMap<>();
360
    private final ServerInterceptor noopInterceptor = new ServerInterceptor() {
1✔
361
      @Override
362
      public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
363
          Metadata headers, ServerCallHandler<ReqT, RespT> next) {
364
        return next.startCall(call, headers);
1✔
365
      }
366
    };
367

368
    private DiscoveryState(String resourceName) {
1✔
369
      this.resourceName = checkNotNull(resourceName, "resourceName");
1✔
370
      xdsClient.watchXdsResource(
1✔
371
          XdsListenerResource.getInstance(), resourceName, this, syncContext);
1✔
372
    }
1✔
373

374
    @Override
375
    public void onChanged(final LdsUpdate update) {
376
      if (stopped) {
1✔
377
        return;
×
378
      }
379
      logger.log(Level.FINEST, "Received Lds update {0}", update);
1✔
380
      checkNotNull(update.listener(), "update");
1✔
381
      if (!pendingRds.isEmpty()) {
1✔
382
        // filter chain state has not yet been applied to filterChainSelectorManager and there
383
        // are two sets of sslContextProviderSuppliers, so we release the old ones.
384
        releaseSuppliersInFlight();
1✔
385
        pendingRds.clear();
1✔
386
      }
387
      filterChains = update.listener().filterChains();
1✔
388
      defaultFilterChain = update.listener().defaultFilterChain();
1✔
389
      List<FilterChain> allFilterChains = filterChains;
1✔
390
      if (defaultFilterChain != null) {
1✔
391
        allFilterChains = new ArrayList<>(filterChains);
1✔
392
        allFilterChains.add(defaultFilterChain);
1✔
393
      }
394
      Set<String> allRds = new HashSet<>();
1✔
395
      for (FilterChain filterChain : allFilterChains) {
1✔
396
        HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
397
        if (hcm.virtualHosts() == null) {
1✔
398
          RouteDiscoveryState rdsState = routeDiscoveryStates.get(hcm.rdsName());
1✔
399
          if (rdsState == null) {
1✔
400
            rdsState = new RouteDiscoveryState(hcm.rdsName());
1✔
401
            routeDiscoveryStates.put(hcm.rdsName(), rdsState);
1✔
402
            xdsClient.watchXdsResource(XdsRouteConfigureResource.getInstance(),
1✔
403
                hcm.rdsName(), rdsState, syncContext);
1✔
404
          }
405
          if (rdsState.isPending) {
1✔
406
            pendingRds.add(hcm.rdsName());
1✔
407
          }
408
          allRds.add(hcm.rdsName());
1✔
409
        }
410
      }
1✔
411
      for (Map.Entry<String, RouteDiscoveryState> entry: routeDiscoveryStates.entrySet()) {
1✔
412
        if (!allRds.contains(entry.getKey())) {
1✔
413
          xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(),
1✔
414
              entry.getKey(), entry.getValue());
1✔
415
        }
416
      }
1✔
417
      routeDiscoveryStates.keySet().retainAll(allRds);
1✔
418
      if (pendingRds.isEmpty()) {
1✔
419
        updateSelector();
1✔
420
      }
421
    }
1✔
422

423
    @Override
424
    public void onResourceDoesNotExist(final String resourceName) {
425
      if (stopped) {
1✔
426
        return;
×
427
      }
428
      StatusException statusException = Status.UNAVAILABLE.withDescription(
1✔
429
          String.format("Listener %s unavailable, xDS node ID: %s", resourceName,
1✔
430
              xdsClient.getBootstrapInfo().node().getId())).asException();
1✔
431
      handleConfigNotFound(statusException);
1✔
432
    }
1✔
433

434
    @Override
435
    public void onError(final Status error) {
436
      if (stopped) {
1✔
437
        return;
×
438
      }
439
      String description = error.getDescription() == null ? "" : error.getDescription() + " ";
1✔
440
      Status errorWithNodeId = error.withDescription(
1✔
441
          description + "xDS node ID: " + xdsClient.getBootstrapInfo().node().getId());
1✔
442
      logger.log(Level.FINE, "Error from XdsClient", errorWithNodeId);
1✔
443
      if (!isServing) {
1✔
444
        listener.onNotServing(errorWithNodeId.asException());
1✔
445
      }
446
    }
1✔
447

448
    private void shutdown() {
449
      stopped = true;
1✔
450
      cleanUpRouteDiscoveryStates();
1✔
451
      logger.log(Level.FINE, "Stop watching LDS resource {0}", resourceName);
1✔
452
      xdsClient.cancelXdsResourceWatch(XdsListenerResource.getInstance(), resourceName, this);
1✔
453
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
454
      filterChainSelectorManager.updateSelector(FilterChainSelector.NO_FILTER_CHAIN);
1✔
455
      for (SslContextProviderSupplier s: toRelease) {
1✔
456
        s.close();
1✔
457
      }
1✔
458
      releaseSuppliersInFlight();
1✔
459
    }
1✔
460

461
    private void updateSelector() {
462
      Map<FilterChain, AtomicReference<ServerRoutingConfig>> filterChainRouting = new HashMap<>();
1✔
463
      savedRdsRoutingConfigRef.clear();
1✔
464
      for (FilterChain filterChain: filterChains) {
1✔
465
        filterChainRouting.put(filterChain, generateRoutingConfig(filterChain));
1✔
466
      }
1✔
467
      FilterChainSelector selector = new FilterChainSelector(
1✔
468
          Collections.unmodifiableMap(filterChainRouting),
1✔
469
          defaultFilterChain == null ? null : defaultFilterChain.sslContextProviderSupplier(),
1✔
470
          defaultFilterChain == null ? new AtomicReference<ServerRoutingConfig>() :
1✔
471
              generateRoutingConfig(defaultFilterChain));
1✔
472
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
473
      logger.log(Level.FINEST, "Updating selector {0}", selector);
1✔
474
      filterChainSelectorManager.updateSelector(selector);
1✔
475
      for (SslContextProviderSupplier e: toRelease) {
1✔
476
        e.close();
1✔
477
      }
1✔
478
      startDelegateServer();
1✔
479
    }
1✔
480

481
    private AtomicReference<ServerRoutingConfig> generateRoutingConfig(FilterChain filterChain) {
482
      HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
483
      if (hcm.virtualHosts() != null) {
1✔
484
        ImmutableMap<Route, ServerInterceptor> interceptors = generatePerRouteInterceptors(
1✔
485
                hcm.httpFilterConfigs(), hcm.virtualHosts());
1✔
486
        return new AtomicReference<>(ServerRoutingConfig.create(hcm.virtualHosts(),interceptors));
1✔
487
      } else {
488
        RouteDiscoveryState rds = routeDiscoveryStates.get(hcm.rdsName());
1✔
489
        checkNotNull(rds, "rds");
1✔
490
        AtomicReference<ServerRoutingConfig> serverRoutingConfigRef = new AtomicReference<>();
1✔
491
        if (rds.savedVirtualHosts != null) {
1✔
492
          ImmutableMap<Route, ServerInterceptor> interceptors = generatePerRouteInterceptors(
1✔
493
              hcm.httpFilterConfigs(), rds.savedVirtualHosts);
1✔
494
          ServerRoutingConfig serverRoutingConfig =
1✔
495
              ServerRoutingConfig.create(rds.savedVirtualHosts, interceptors);
1✔
496
          serverRoutingConfigRef.set(serverRoutingConfig);
1✔
497
        } else {
1✔
498
          serverRoutingConfigRef.set(ServerRoutingConfig.FAILING_ROUTING_CONFIG);
1✔
499
        }
500
        savedRdsRoutingConfigRef.put(filterChain, serverRoutingConfigRef);
1✔
501
        return serverRoutingConfigRef;
1✔
502
      }
503
    }
504

505
    private ImmutableMap<Route, ServerInterceptor> generatePerRouteInterceptors(
506
        List<NamedFilterConfig> namedFilterConfigs, List<VirtualHost> virtualHosts) {
507
      ImmutableMap.Builder<Route, ServerInterceptor> perRouteInterceptors =
1✔
508
          new ImmutableMap.Builder<>();
509
      for (VirtualHost virtualHost : virtualHosts) {
1✔
510
        for (Route route : virtualHost.routes()) {
1✔
511
          List<ServerInterceptor> filterInterceptors = new ArrayList<>();
1✔
512
          Map<String, FilterConfig> selectedOverrideConfigs =
1✔
513
              new HashMap<>(virtualHost.filterConfigOverrides());
1✔
514
          selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
515
          if (namedFilterConfigs != null) {
1✔
516
            for (NamedFilterConfig namedFilterConfig : namedFilterConfigs) {
1✔
517
              FilterConfig filterConfig = namedFilterConfig.filterConfig;
1✔
518
              Filter filter = filterRegistry.get(filterConfig.typeUrl());
1✔
519
              if (filter instanceof ServerInterceptorBuilder) {
1✔
520
                ServerInterceptor interceptor =
1✔
521
                    ((ServerInterceptorBuilder) filter).buildServerInterceptor(
1✔
522
                        filterConfig, selectedOverrideConfigs.get(namedFilterConfig.name));
1✔
523
                if (interceptor != null) {
1✔
524
                  filterInterceptors.add(interceptor);
1✔
525
                }
526
              } else {
1✔
527
                logger.log(Level.WARNING, "HttpFilterConfig(type URL: "
×
528
                    + filterConfig.typeUrl() + ") is not supported on server-side. "
×
529
                    + "Probably a bug at ClientXdsClient verification.");
530
              }
531
            }
1✔
532
          }
533
          ServerInterceptor interceptor = combineInterceptors(filterInterceptors);
1✔
534
          perRouteInterceptors.put(route, interceptor);
1✔
535
        }
1✔
536
      }
1✔
537
      return perRouteInterceptors.buildOrThrow();
1✔
538
    }
539

540
    private ServerInterceptor combineInterceptors(final List<ServerInterceptor> interceptors) {
541
      if (interceptors.isEmpty()) {
1✔
542
        return noopInterceptor;
1✔
543
      }
544
      if (interceptors.size() == 1) {
1✔
545
        return interceptors.get(0);
×
546
      }
547
      return new ServerInterceptor() {
1✔
548
        @Override
549
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
550
            Metadata headers, ServerCallHandler<ReqT, RespT> next) {
551
          // intercept forward
552
          for (int i = interceptors.size() - 1; i >= 0; i--) {
1✔
553
            next = InternalServerInterceptors.interceptCallHandlerCreate(
1✔
554
                interceptors.get(i), next);
1✔
555
          }
556
          return next.startCall(call, headers);
1✔
557
        }
558
      };
559
    }
560

561
    private void handleConfigNotFound(StatusException exception) {
562
      cleanUpRouteDiscoveryStates();
1✔
563
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
564
      filterChainSelectorManager.updateSelector(FilterChainSelector.NO_FILTER_CHAIN);
1✔
565
      for (SslContextProviderSupplier s: toRelease) {
1✔
566
        s.close();
1✔
567
      }
1✔
568
      if (restartTimer != null) {
1✔
569
        restartTimer.cancel();
1✔
570
      }
571
      if (!delegate.isShutdown()) {
1✔
572
        delegate.shutdown();  // let in-progress calls finish
1✔
573
      }
574
      isServing = false;
1✔
575
      listener.onNotServing(exception);
1✔
576
    }
1✔
577

578
    private void cleanUpRouteDiscoveryStates() {
579
      for (RouteDiscoveryState rdsState : routeDiscoveryStates.values()) {
1✔
580
        String rdsName = rdsState.resourceName;
1✔
581
        logger.log(Level.FINE, "Stop watching RDS resource {0}", rdsName);
1✔
582
        xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(), rdsName,
1✔
583
            rdsState);
584
      }
1✔
585
      routeDiscoveryStates.clear();
1✔
586
      savedRdsRoutingConfigRef.clear();
1✔
587
    }
1✔
588

589
    private List<SslContextProviderSupplier> getSuppliersInUse() {
590
      List<SslContextProviderSupplier> toRelease = new ArrayList<>();
1✔
591
      FilterChainSelector selector = filterChainSelectorManager.getSelectorToUpdateSelector();
1✔
592
      if (selector != null) {
1✔
593
        for (FilterChain f: selector.getRoutingConfigs().keySet()) {
1✔
594
          if (f.sslContextProviderSupplier() != null) {
1✔
595
            toRelease.add(f.sslContextProviderSupplier());
1✔
596
          }
597
        }
1✔
598
        SslContextProviderSupplier defaultSupplier =
1✔
599
                selector.getDefaultSslContextProviderSupplier();
1✔
600
        if (defaultSupplier != null) {
1✔
601
          toRelease.add(defaultSupplier);
1✔
602
        }
603
      }
604
      return toRelease;
1✔
605
    }
606

607
    private void releaseSuppliersInFlight() {
608
      SslContextProviderSupplier supplier;
609
      for (FilterChain filterChain : filterChains) {
1✔
610
        supplier = filterChain.sslContextProviderSupplier();
1✔
611
        if (supplier != null) {
1✔
612
          supplier.close();
1✔
613
        }
614
      }
1✔
615
      if (defaultFilterChain != null
1✔
616
              && (supplier = defaultFilterChain.sslContextProviderSupplier()) != null) {
1✔
617
        supplier.close();
1✔
618
      }
619
    }
1✔
620

621
    private final class RouteDiscoveryState implements ResourceWatcher<RdsUpdate> {
622
      private final String resourceName;
623
      private ImmutableList<VirtualHost> savedVirtualHosts;
624
      private boolean isPending = true;
1✔
625

626
      private RouteDiscoveryState(String resourceName) {
1✔
627
        this.resourceName = checkNotNull(resourceName, "resourceName");
1✔
628
      }
1✔
629

630
      @Override
631
      public void onChanged(final RdsUpdate update) {
632
        syncContext.execute(new Runnable() {
1✔
633
          @Override
634
          public void run() {
635
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
636
              return;
1✔
637
            }
638
            if (savedVirtualHosts == null && !isPending) {
1✔
639
              logger.log(Level.WARNING, "Received valid Rds {0} configuration.", resourceName);
1✔
640
            }
641
            savedVirtualHosts = ImmutableList.copyOf(update.virtualHosts);
1✔
642
            updateRdsRoutingConfig();
1✔
643
            maybeUpdateSelector();
1✔
644
          }
1✔
645
        });
646
      }
1✔
647

648
      @Override
649
      public void onResourceDoesNotExist(final String resourceName) {
650
        syncContext.execute(new Runnable() {
1✔
651
          @Override
652
          public void run() {
653
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
654
              return;
×
655
            }
656
            logger.log(Level.WARNING, "Rds {0} unavailable", resourceName);
1✔
657
            savedVirtualHosts = null;
1✔
658
            updateRdsRoutingConfig();
1✔
659
            maybeUpdateSelector();
1✔
660
          }
1✔
661
        });
662
      }
1✔
663

664
      @Override
665
      public void onError(final Status error) {
666
        syncContext.execute(new Runnable() {
1✔
667
          @Override
668
          public void run() {
669
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
670
              return;
×
671
            }
672
            String description = error.getDescription() == null ? "" : error.getDescription() + " ";
1✔
673
            Status errorWithNodeId = error.withDescription(
1✔
674
                    description + "xDS node ID: " + xdsClient.getBootstrapInfo().node().getId());
1✔
675
            logger.log(Level.WARNING, "Error loading RDS resource {0} from XdsClient: {1}.",
1✔
676
                    new Object[]{resourceName, errorWithNodeId});
1✔
677
            maybeUpdateSelector();
1✔
678
          }
1✔
679
        });
680
      }
1✔
681

682
      private void updateRdsRoutingConfig() {
683
        for (FilterChain filterChain : savedRdsRoutingConfigRef.keySet()) {
1✔
684
          if (resourceName.equals(filterChain.httpConnectionManager().rdsName())) {
1✔
685
            ServerRoutingConfig updatedRoutingConfig;
686
            if (savedVirtualHosts == null) {
1✔
687
              updatedRoutingConfig = ServerRoutingConfig.FAILING_ROUTING_CONFIG;
1✔
688
            } else {
689
              ImmutableMap<Route, ServerInterceptor> updatedInterceptors =
1✔
690
                  generatePerRouteInterceptors(
1✔
691
                      filterChain.httpConnectionManager().httpFilterConfigs(),
1✔
692
                      savedVirtualHosts);
693
              updatedRoutingConfig = ServerRoutingConfig.create(savedVirtualHosts,
1✔
694
                  updatedInterceptors);
695
            }
696
            logger.log(Level.FINEST, "Updating filter chain {0} rds routing config: {1}",
1✔
697
                new Object[]{filterChain.name(), updatedRoutingConfig});
1✔
698
            savedRdsRoutingConfigRef.get(filterChain).set(updatedRoutingConfig);
1✔
699
          }
700
        }
1✔
701
      }
1✔
702

703
      // Update the selector to use the most recently updated configs only after all rds have been
704
      // discovered for the first time. Later changes on rds will be applied through virtual host
705
      // list atomic ref.
706
      private void maybeUpdateSelector() {
707
        isPending = false;
1✔
708
        boolean isLastPending = pendingRds.remove(resourceName) && pendingRds.isEmpty();
1✔
709
        if (isLastPending) {
1✔
710
          updateSelector();
1✔
711
        }
712
      }
1✔
713
    }
714
  }
715

716
  @VisibleForTesting
717
  final class ConfigApplyingInterceptor implements ServerInterceptor {
1✔
718
    private final ServerInterceptor noopInterceptor = new ServerInterceptor() {
1✔
719
      @Override
720
      public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
721
          Metadata headers, ServerCallHandler<ReqT, RespT> next) {
722
        return next.startCall(call, headers);
×
723
      }
724
    };
725

726
    @Override
727
    public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
728
        Metadata headers, ServerCallHandler<ReqT, RespT> next) {
729
      AtomicReference<ServerRoutingConfig> routingConfigRef =
1✔
730
          call.getAttributes().get(ATTR_SERVER_ROUTING_CONFIG);
1✔
731
      ServerRoutingConfig routingConfig = routingConfigRef == null ? null :
1✔
732
          routingConfigRef.get();
1✔
733
      if (routingConfig == null || routingConfig == ServerRoutingConfig.FAILING_ROUTING_CONFIG) {
1✔
734
        String errorMsg = "Missing or broken xDS routing config: RDS config unavailable.";
1✔
735
        call.close(Status.UNAVAILABLE.withDescription(errorMsg), new Metadata());
1✔
736
        return new Listener<ReqT>() {};
1✔
737
      }
738
      List<VirtualHost> virtualHosts = routingConfig.virtualHosts();
1✔
739
      VirtualHost virtualHost = RoutingUtils.findVirtualHostForHostName(
1✔
740
          virtualHosts, call.getAuthority());
1✔
741
      if (virtualHost == null) {
1✔
742
        call.close(
1✔
743
            Status.UNAVAILABLE.withDescription("Could not find xDS virtual host matching RPC"),
1✔
744
            new Metadata());
745
        return new Listener<ReqT>() {};
1✔
746
      }
747
      Route selectedRoute = null;
1✔
748
      MethodDescriptor<ReqT, RespT> method = call.getMethodDescriptor();
1✔
749
      for (Route route : virtualHost.routes()) {
1✔
750
        if (RoutingUtils.matchRoute(
1✔
751
            route.routeMatch(), "/" + method.getFullMethodName(), headers, random)) {
1✔
752
          selectedRoute = route;
1✔
753
          break;
1✔
754
        }
755
      }
1✔
756
      if (selectedRoute == null) {
1✔
757
        call.close(Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"),
1✔
758
            new Metadata());
759
        return new ServerCall.Listener<ReqT>() {};
1✔
760
      }
761
      if (selectedRoute.routeAction() != null) {
1✔
762
        call.close(Status.UNAVAILABLE.withDescription("Invalid xDS route action for matching "
1✔
763
            + "route: only Route.non_forwarding_action should be allowed."), new Metadata());
764
        return new ServerCall.Listener<ReqT>() {};
1✔
765
      }
766
      ServerInterceptor routeInterceptor = noopInterceptor;
1✔
767
      Map<Route, ServerInterceptor> perRouteInterceptors = routingConfig.interceptors();
1✔
768
      if (perRouteInterceptors != null && perRouteInterceptors.get(selectedRoute) != null) {
1✔
769
        routeInterceptor = perRouteInterceptors.get(selectedRoute);
1✔
770
      }
771
      return routeInterceptor.interceptCall(call, headers, next);
1✔
772
    }
773
  }
774

775
  /**
776
   * The HttpConnectionManager level configuration.
777
   */
778
  @AutoValue
779
  abstract static class ServerRoutingConfig {
1✔
780
    @VisibleForTesting
781
    static final ServerRoutingConfig FAILING_ROUTING_CONFIG = ServerRoutingConfig.create(
1✔
782
        ImmutableList.<VirtualHost>of(), ImmutableMap.<Route, ServerInterceptor>of());
1✔
783

784
    abstract ImmutableList<VirtualHost> virtualHosts();
785

786
    // Prebuilt per route server interceptors from http filter configs.
787
    abstract ImmutableMap<Route, ServerInterceptor> interceptors();
788

789
    /**
790
     * Server routing configuration.
791
     * */
792
    public static ServerRoutingConfig create(
793
        ImmutableList<VirtualHost> virtualHosts,
794
        ImmutableMap<Route, ServerInterceptor> interceptors) {
795
      checkNotNull(virtualHosts, "virtualHosts");
1✔
796
      checkNotNull(interceptors, "interceptors");
1✔
797
      return new AutoValue_XdsServerWrapper_ServerRoutingConfig(virtualHosts, interceptors);
1✔
798
    }
799
  }
800
}
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