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

grpc / grpc-java / #19744

21 Mar 2025 05:31AM UTC coverage: 88.581% (-0.007%) from 88.588%
#19744

push

github

web-flow
xds: Expose filter names to filter instances (#11971)

This is to support gRFC A83 xDS GCP Authentication Filter:
> Otherwise, the filter will look in the CDS resource's metadata for a
> key corresponding to the filter's instance name.

34591 of 39050 relevant lines covered (88.58%)

0.89 hits per line

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

94.87
/../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.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler.FilterChainSelector;
51
import io.grpc.xds.ThreadSafeRandom.ThreadSafeRandomImpl;
52
import io.grpc.xds.VirtualHost.Route;
53
import io.grpc.xds.XdsListenerResource.LdsUpdate;
54
import io.grpc.xds.XdsRouteConfigureResource.RdsUpdate;
55
import io.grpc.xds.XdsServerBuilder.XdsServingStatusListener;
56
import io.grpc.xds.client.XdsClient;
57
import io.grpc.xds.client.XdsClient.ResourceWatcher;
58
import io.grpc.xds.internal.security.SslContextProviderSupplier;
59
import java.io.IOException;
60
import java.net.SocketAddress;
61
import java.util.ArrayList;
62
import java.util.HashMap;
63
import java.util.HashSet;
64
import java.util.List;
65
import java.util.Map;
66
import java.util.Set;
67
import java.util.concurrent.CountDownLatch;
68
import java.util.concurrent.ExecutionException;
69
import java.util.concurrent.ScheduledExecutorService;
70
import java.util.concurrent.TimeUnit;
71
import java.util.concurrent.atomic.AtomicBoolean;
72
import java.util.concurrent.atomic.AtomicReference;
73
import java.util.logging.Level;
74
import java.util.logging.Logger;
75
import javax.annotation.Nullable;
76

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

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

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

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

116
  // Must be accessed in syncContext.
117
  // Filter instances are unique per Server, per FilterChain, and per filter's name+typeUrl.
118
  // FilterChain.name -> <NamedFilterConfig.filterStateKey -> filter_instance>.
119
  private final HashMap<String, HashMap<String, Filter>> activeFilters = new HashMap<>();
1✔
120
  // Default filter chain Filter instances are unique per Server, and per filter's name+typeUrl.
121
  // NamedFilterConfig.filterStateKey -> filter_instance.
122
  private final HashMap<String, Filter> activeFiltersDefaultChain = new HashMap<>();
1✔
123

124
  XdsServerWrapper(
125
      String listenerAddress,
126
      ServerBuilder<?> delegateBuilder,
127
      XdsServingStatusListener listener,
128
      FilterChainSelectorManager filterChainSelectorManager,
129
      XdsClientPoolFactory xdsClientPoolFactory,
130
      FilterRegistry filterRegistry) {
131
    this(listenerAddress, delegateBuilder, listener, filterChainSelectorManager,
1✔
132
        xdsClientPoolFactory, filterRegistry, SharedResourceHolder.get(GrpcUtil.TIMER_SERVICE));
1✔
133
    sharedTimeService = true;
1✔
134
  }
1✔
135

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

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

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

207
  @Override
208
  public Server shutdown() {
209
    if (!shutdown.compareAndSet(false, true)) {
1✔
210
      return this;
1✔
211
    }
212
    syncContext.execute(new Runnable() {
1✔
213
      @Override
214
      public void run() {
215
        if (!delegate.isShutdown()) {
1✔
216
          delegate.shutdown();
1✔
217
        }
218
        internalShutdown();
1✔
219
      }
1✔
220
    });
221
    return this;
1✔
222
  }
223

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

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

261
  @Override
262
  public boolean isShutdown() {
263
    return shutdown.get();
1✔
264
  }
265

266
  @Override
267
  public boolean isTerminated() {
268
    return internalTerminationLatch.getCount() == 0 && delegate.isTerminated();
1✔
269
  }
270

271
  @Override
272
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
273
    long startTime = System.nanoTime();
1✔
274
    if (!internalTerminationLatch.await(timeout, unit)) {
1✔
275
      return false;
×
276
    }
277
    long remainingTime = unit.toNanos(timeout) - (System.nanoTime() - startTime);
1✔
278
    return delegate.awaitTermination(remainingTime, TimeUnit.NANOSECONDS);
1✔
279
  }
280

281
  @Override
282
  public void awaitTermination() throws InterruptedException {
283
    internalTerminationLatch.await();
1✔
284
    delegate.awaitTermination();
1✔
285
  }
1✔
286

287
  @Override
288
  public int getPort() {
289
    return delegate.getPort();
1✔
290
  }
291

292
  @Override
293
  public List<? extends SocketAddress> getListenSockets() {
294
    return delegate.getListenSockets();
1✔
295
  }
296

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

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

307
  @Override
308
  public List<ServerServiceDefinition> getMutableServices() {
309
    return delegate.getMutableServices();
×
310
  }
311

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

345
  private final class RestartTask implements Runnable {
1✔
346
    @Override
347
    public void run() {
348
      startDelegateServer();
1✔
349
    }
1✔
350
  }
351

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

374
    private DiscoveryState(String resourceName) {
1✔
375
      this.resourceName = checkNotNull(resourceName, "resourceName");
1✔
376
      xdsClient.watchXdsResource(
1✔
377
          XdsListenerResource.getInstance(), resourceName, this, syncContext);
1✔
378
    }
1✔
379

380
    @Override
381
    public void onChanged(final LdsUpdate update) {
382
      if (stopped) {
1✔
383
        return;
×
384
      }
385
      logger.log(Level.FINEST, "Received Lds update {0}", update);
1✔
386
      checkNotNull(update.listener(), "update");
1✔
387
      if (!pendingRds.isEmpty()) {
1✔
388
        // filter chain state has not yet been applied to filterChainSelectorManager and there
389
        // are two sets of sslContextProviderSuppliers, so we release the old ones.
390
        releaseSuppliersInFlight();
1✔
391
        pendingRds.clear();
1✔
392
      }
393

394
      filterChains = update.listener().filterChains();
1✔
395
      defaultFilterChain = update.listener().defaultFilterChain();
1✔
396
      // Filters are loaded even if the server isn't serving yet.
397
      updateActiveFilters();
1✔
398

399
      List<FilterChain> allFilterChains = filterChains;
1✔
400
      if (defaultFilterChain != null) {
1✔
401
        allFilterChains = new ArrayList<>(filterChains);
1✔
402
        allFilterChains.add(defaultFilterChain);
1✔
403
      }
404

405
      Set<String> allRds = new HashSet<>();
1✔
406
      for (FilterChain filterChain : allFilterChains) {
1✔
407
        HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
408
        if (hcm.virtualHosts() == null) {
1✔
409
          RouteDiscoveryState rdsState = routeDiscoveryStates.get(hcm.rdsName());
1✔
410
          if (rdsState == null) {
1✔
411
            rdsState = new RouteDiscoveryState(hcm.rdsName());
1✔
412
            routeDiscoveryStates.put(hcm.rdsName(), rdsState);
1✔
413
            xdsClient.watchXdsResource(XdsRouteConfigureResource.getInstance(),
1✔
414
                hcm.rdsName(), rdsState, syncContext);
1✔
415
          }
416
          if (rdsState.isPending) {
1✔
417
            pendingRds.add(hcm.rdsName());
1✔
418
          }
419
          allRds.add(hcm.rdsName());
1✔
420
        }
421
      }
1✔
422

423
      for (Map.Entry<String, RouteDiscoveryState> entry: routeDiscoveryStates.entrySet()) {
1✔
424
        if (!allRds.contains(entry.getKey())) {
1✔
425
          xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(),
1✔
426
              entry.getKey(), entry.getValue());
1✔
427
        }
428
      }
1✔
429
      routeDiscoveryStates.keySet().retainAll(allRds);
1✔
430
      if (pendingRds.isEmpty()) {
1✔
431
        updateSelector();
1✔
432
      }
433
    }
1✔
434

435
    @Override
436
    public void onResourceDoesNotExist(final String resourceName) {
437
      if (stopped) {
1✔
438
        return;
×
439
      }
440
      StatusException statusException = Status.UNAVAILABLE.withDescription(
1✔
441
          String.format("Listener %s unavailable, xDS node ID: %s", resourceName,
1✔
442
              xdsClient.getBootstrapInfo().node().getId())).asException();
1✔
443
      handleConfigNotFound(statusException);
1✔
444
    }
1✔
445

446
    @Override
447
    public void onError(final Status error) {
448
      if (stopped) {
1✔
449
        return;
×
450
      }
451
      String description = error.getDescription() == null ? "" : error.getDescription() + " ";
1✔
452
      Status errorWithNodeId = error.withDescription(
1✔
453
          description + "xDS node ID: " + xdsClient.getBootstrapInfo().node().getId());
1✔
454
      logger.log(Level.FINE, "Error from XdsClient", errorWithNodeId);
1✔
455
      if (!isServing) {
1✔
456
        listener.onNotServing(errorWithNodeId.asException());
1✔
457
      }
458
    }
1✔
459

460
    private void shutdown() {
461
      stopped = true;
1✔
462
      cleanUpRouteDiscoveryStates();
1✔
463
      logger.log(Level.FINE, "Stop watching LDS resource {0}", resourceName);
1✔
464
      xdsClient.cancelXdsResourceWatch(XdsListenerResource.getInstance(), resourceName, this);
1✔
465
      shutdownActiveFilters();
1✔
466
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
467
      filterChainSelectorManager.updateSelector(FilterChainSelector.NO_FILTER_CHAIN);
1✔
468
      for (SslContextProviderSupplier s: toRelease) {
1✔
469
        s.close();
1✔
470
      }
1✔
471
      releaseSuppliersInFlight();
1✔
472
    }
1✔
473

474
    private void updateSelector() {
475
      // This is regenerated in generateRoutingConfig() calls below.
476
      savedRdsRoutingConfigRef.clear();
1✔
477

478
      // Prepare server routing config map.
479
      ImmutableMap.Builder<FilterChain, AtomicReference<ServerRoutingConfig>> routingConfigs =
480
          ImmutableMap.builder();
1✔
481
      for (FilterChain filterChain: filterChains) {
1✔
482
        HashMap<String, Filter> chainFilters = activeFilters.get(filterChain.name());
1✔
483
        routingConfigs.put(filterChain, generateRoutingConfig(filterChain, chainFilters));
1✔
484
      }
1✔
485

486
      // Prepare the new selector.
487
      FilterChainSelector selector;
488
      if (defaultFilterChain != null) {
1✔
489
        selector = new FilterChainSelector(
1✔
490
            routingConfigs.build(),
1✔
491
            defaultFilterChain.sslContextProviderSupplier(),
1✔
492
            generateRoutingConfig(defaultFilterChain, activeFiltersDefaultChain));
1✔
493
      } else {
494
        selector = new FilterChainSelector(routingConfigs.build());
1✔
495
      }
496

497
      // Prepare the list of current selector's resources to close later.
498
      List<SslContextProviderSupplier> oldSslSuppliers = getSuppliersInUse();
1✔
499

500
      // Swap the selectors, initiate a graceful shutdown of the old one.
501
      logger.log(Level.FINEST, "Updating selector {0}", selector);
1✔
502
      filterChainSelectorManager.updateSelector(selector);
1✔
503

504
      // Release old resources.
505
      for (SslContextProviderSupplier supplier: oldSslSuppliers) {
1✔
506
        supplier.close();
1✔
507
      }
1✔
508

509
      // Now that we have valid Transport Socket config, we can start/restart listening on a port.
510
      startDelegateServer();
1✔
511
    }
1✔
512

513
    // called in syncContext
514
    private void updateActiveFilters() {
515
      Set<String> removedChains = new HashSet<>(activeFilters.keySet());
1✔
516
      for (FilterChain filterChain: filterChains) {
1✔
517
        removedChains.remove(filterChain.name());
1✔
518
        updateActiveFiltersForChain(
1✔
519
            activeFilters.computeIfAbsent(filterChain.name(), k -> new HashMap<>()),
1✔
520
            filterChain.httpConnectionManager().httpFilterConfigs());
1✔
521
      }
1✔
522

523
      // Shutdown all filters of chains missing from the LDS.
524
      for (String chainToShutdown : removedChains) {
1✔
525
        HashMap<String, Filter> filtersToShutdown = activeFilters.get(chainToShutdown);
1✔
526
        checkNotNull(filtersToShutdown, "filtersToShutdown of chain %s", chainToShutdown);
1✔
527
        updateActiveFiltersForChain(filtersToShutdown, null);
1✔
528
        activeFilters.remove(chainToShutdown);
1✔
529
      }
1✔
530

531
      // Default chain.
532
      ImmutableList<NamedFilterConfig> defaultChainConfigs = null;
1✔
533
      if (defaultFilterChain != null) {
1✔
534
        defaultChainConfigs = defaultFilterChain.httpConnectionManager().httpFilterConfigs();
1✔
535
      }
536
      updateActiveFiltersForChain(activeFiltersDefaultChain, defaultChainConfigs);
1✔
537
    }
1✔
538

539
    // called in syncContext
540
    private void shutdownActiveFilters() {
541
      for (HashMap<String, Filter> chainFilters : activeFilters.values()) {
1✔
542
        checkNotNull(chainFilters, "chainFilters");
1✔
543
        updateActiveFiltersForChain(chainFilters, null);
1✔
544
      }
1✔
545
      activeFilters.clear();
1✔
546
      updateActiveFiltersForChain(activeFiltersDefaultChain, null);
1✔
547
    }
1✔
548

549
    // called in syncContext
550
    private void updateActiveFiltersForChain(
551
        Map<String, Filter> chainFilters, @Nullable List<NamedFilterConfig> filterConfigs) {
552
      if (filterConfigs == null) {
1✔
553
        filterConfigs = ImmutableList.of();
1✔
554
      }
555

556
      Set<String> filtersToShutdown = new HashSet<>(chainFilters.keySet());
1✔
557
      for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
558
        String typeUrl = namedFilter.filterConfig.typeUrl();
1✔
559
        String filterKey = namedFilter.filterStateKey();
1✔
560

561
        Filter.Provider provider = filterRegistry.get(typeUrl);
1✔
562
        checkNotNull(provider, "provider %s", typeUrl);
1✔
563
        Filter filter = chainFilters.computeIfAbsent(
1✔
564
            filterKey, k -> provider.newInstance(namedFilter.name));
1✔
565
        checkNotNull(filter, "filter %s", filterKey);
1✔
566
        filtersToShutdown.remove(filterKey);
1✔
567
      }
1✔
568

569
      // Shutdown filters not present in current HCM.
570
      for (String filterKey : filtersToShutdown) {
1✔
571
        Filter filterToShutdown = chainFilters.remove(filterKey);
1✔
572
        checkNotNull(filterToShutdown, "filterToShutdown %s", filterKey);
1✔
573
        filterToShutdown.close();
1✔
574
      }
1✔
575
    }
1✔
576

577
    private AtomicReference<ServerRoutingConfig> generateRoutingConfig(
578
        FilterChain filterChain, Map<String, Filter> chainFilters) {
579
      HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
580
      ServerRoutingConfig routingConfig;
581

582
      // Inlined routes.
583
      ImmutableList<VirtualHost> vhosts = hcm.virtualHosts();
1✔
584
      if (vhosts != null) {
1✔
585
        routingConfig = ServerRoutingConfig.create(vhosts,
1✔
586
            generatePerRouteInterceptors(hcm.httpFilterConfigs(), vhosts, chainFilters));
1✔
587
        return new AtomicReference<>(routingConfig);
1✔
588
      }
589

590
      // Routes from RDS.
591
      RouteDiscoveryState rds = routeDiscoveryStates.get(hcm.rdsName());
1✔
592
      checkNotNull(rds, "rds");
1✔
593

594
      ImmutableList<VirtualHost> savedVhosts = rds.savedVirtualHosts;
1✔
595
      if (savedVhosts != null) {
1✔
596
        routingConfig = ServerRoutingConfig.create(savedVhosts,
1✔
597
            generatePerRouteInterceptors(hcm.httpFilterConfigs(), savedVhosts, chainFilters));
1✔
598
      } else {
599
        routingConfig = ServerRoutingConfig.FAILING_ROUTING_CONFIG;
1✔
600
      }
601
      AtomicReference<ServerRoutingConfig> routingConfigRef = new AtomicReference<>(routingConfig);
1✔
602
      savedRdsRoutingConfigRef.put(filterChain, routingConfigRef);
1✔
603
      return routingConfigRef;
1✔
604
    }
605

606
    private ImmutableMap<Route, ServerInterceptor> generatePerRouteInterceptors(
607
        @Nullable List<NamedFilterConfig> filterConfigs,
608
        List<VirtualHost> virtualHosts,
609
        Map<String, Filter> chainFilters) {
610
      syncContext.throwIfNotInThisSynchronizationContext();
1✔
611

612
      checkNotNull(chainFilters, "chainFilters");
1✔
613
      ImmutableMap.Builder<Route, ServerInterceptor> perRouteInterceptors =
1✔
614
          new ImmutableMap.Builder<>();
615

616
      for (VirtualHost virtualHost : virtualHosts) {
1✔
617
        for (Route route : virtualHost.routes()) {
1✔
618
          // Short circuit.
619
          if (filterConfigs == null) {
1✔
620
            perRouteInterceptors.put(route, noopInterceptor);
×
621
            continue;
×
622
          }
623

624
          // Override vhost filter configs with more specific per-route configs.
625
          Map<String, FilterConfig> perRouteOverrides = ImmutableMap.<String, FilterConfig>builder()
1✔
626
              .putAll(virtualHost.filterConfigOverrides())
1✔
627
              .putAll(route.filterConfigOverrides())
1✔
628
              .buildKeepingLast();
1✔
629

630
          // Interceptors for this vhost/route combo.
631
          List<ServerInterceptor> interceptors = new ArrayList<>(filterConfigs.size());
1✔
632
          for (NamedFilterConfig namedFilter : filterConfigs) {
1✔
633
            String name = namedFilter.name;
1✔
634
            FilterConfig config = namedFilter.filterConfig;
1✔
635
            FilterConfig overrideConfig = perRouteOverrides.get(name);
1✔
636
            String filterKey = namedFilter.filterStateKey();
1✔
637

638
            Filter filter = chainFilters.get(filterKey);
1✔
639
            checkNotNull(filter, "chainFilters.get(%s)", filterKey);
1✔
640
            ServerInterceptor interceptor = filter.buildServerInterceptor(config, overrideConfig);
1✔
641

642
            if (interceptor != null) {
1✔
643
              interceptors.add(interceptor);
1✔
644
            }
645
          }
1✔
646

647
          // Combine interceptors produced by different filters into a single one that executes
648
          // them sequentially. The order is preserved.
649
          perRouteInterceptors.put(route, combineInterceptors(interceptors));
1✔
650
        }
1✔
651
      }
1✔
652

653
      return perRouteInterceptors.buildOrThrow();
1✔
654
    }
655

656
    private ServerInterceptor combineInterceptors(final List<ServerInterceptor> interceptors) {
657
      if (interceptors.isEmpty()) {
1✔
658
        return noopInterceptor;
1✔
659
      }
660
      if (interceptors.size() == 1) {
1✔
661
        return interceptors.get(0);
×
662
      }
663
      return new ServerInterceptor() {
1✔
664
        @Override
665
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
666
            Metadata headers, ServerCallHandler<ReqT, RespT> next) {
667
          // intercept forward
668
          for (int i = interceptors.size() - 1; i >= 0; i--) {
1✔
669
            next = InternalServerInterceptors.interceptCallHandlerCreate(
1✔
670
                interceptors.get(i), next);
1✔
671
          }
672
          return next.startCall(call, headers);
1✔
673
        }
674
      };
675
    }
676

677
    private void handleConfigNotFound(StatusException exception) {
678
      cleanUpRouteDiscoveryStates();
1✔
679
      shutdownActiveFilters();
1✔
680
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
681
      filterChainSelectorManager.updateSelector(FilterChainSelector.NO_FILTER_CHAIN);
1✔
682
      for (SslContextProviderSupplier s: toRelease) {
1✔
683
        s.close();
1✔
684
      }
1✔
685
      if (restartTimer != null) {
1✔
686
        restartTimer.cancel();
1✔
687
      }
688
      if (!delegate.isShutdown()) {
1✔
689
        delegate.shutdown();  // let in-progress calls finish
1✔
690
      }
691
      isServing = false;
1✔
692
      listener.onNotServing(exception);
1✔
693
    }
1✔
694

695
    private void cleanUpRouteDiscoveryStates() {
696
      for (RouteDiscoveryState rdsState : routeDiscoveryStates.values()) {
1✔
697
        String rdsName = rdsState.resourceName;
1✔
698
        logger.log(Level.FINE, "Stop watching RDS resource {0}", rdsName);
1✔
699
        xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(), rdsName,
1✔
700
            rdsState);
701
      }
1✔
702
      routeDiscoveryStates.clear();
1✔
703
      savedRdsRoutingConfigRef.clear();
1✔
704
    }
1✔
705

706
    private List<SslContextProviderSupplier> getSuppliersInUse() {
707
      List<SslContextProviderSupplier> toRelease = new ArrayList<>();
1✔
708
      FilterChainSelector selector = filterChainSelectorManager.getSelectorToUpdateSelector();
1✔
709
      if (selector != null) {
1✔
710
        for (FilterChain f: selector.getRoutingConfigs().keySet()) {
1✔
711
          if (f.sslContextProviderSupplier() != null) {
1✔
712
            toRelease.add(f.sslContextProviderSupplier());
1✔
713
          }
714
        }
1✔
715
        SslContextProviderSupplier defaultSupplier =
1✔
716
                selector.getDefaultSslContextProviderSupplier();
1✔
717
        if (defaultSupplier != null) {
1✔
718
          toRelease.add(defaultSupplier);
1✔
719
        }
720
      }
721
      return toRelease;
1✔
722
    }
723

724
    private void releaseSuppliersInFlight() {
725
      SslContextProviderSupplier supplier;
726
      for (FilterChain filterChain : filterChains) {
1✔
727
        supplier = filterChain.sslContextProviderSupplier();
1✔
728
        if (supplier != null) {
1✔
729
          supplier.close();
1✔
730
        }
731
      }
1✔
732
      if (defaultFilterChain != null
1✔
733
              && (supplier = defaultFilterChain.sslContextProviderSupplier()) != null) {
1✔
734
        supplier.close();
1✔
735
      }
736
    }
1✔
737

738
    private final class RouteDiscoveryState implements ResourceWatcher<RdsUpdate> {
739
      private final String resourceName;
740
      private ImmutableList<VirtualHost> savedVirtualHosts;
741
      private boolean isPending = true;
1✔
742

743
      private RouteDiscoveryState(String resourceName) {
1✔
744
        this.resourceName = checkNotNull(resourceName, "resourceName");
1✔
745
      }
1✔
746

747
      @Override
748
      public void onChanged(final RdsUpdate update) {
749
        syncContext.execute(new Runnable() {
1✔
750
          @Override
751
          public void run() {
752
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
753
              return;
1✔
754
            }
755
            if (savedVirtualHosts == null && !isPending) {
1✔
756
              logger.log(Level.WARNING, "Received valid Rds {0} configuration.", resourceName);
1✔
757
            }
758
            savedVirtualHosts = ImmutableList.copyOf(update.virtualHosts);
1✔
759
            updateRdsRoutingConfig();
1✔
760
            maybeUpdateSelector();
1✔
761
          }
1✔
762
        });
763
      }
1✔
764

765
      @Override
766
      public void onResourceDoesNotExist(final String resourceName) {
767
        syncContext.execute(new Runnable() {
1✔
768
          @Override
769
          public void run() {
770
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
771
              return;
×
772
            }
773
            logger.log(Level.WARNING, "Rds {0} unavailable", resourceName);
1✔
774
            savedVirtualHosts = null;
1✔
775
            updateRdsRoutingConfig();
1✔
776
            maybeUpdateSelector();
1✔
777
          }
1✔
778
        });
779
      }
1✔
780

781
      @Override
782
      public void onError(final Status error) {
783
        syncContext.execute(new Runnable() {
1✔
784
          @Override
785
          public void run() {
786
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
787
              return;
×
788
            }
789
            String description = error.getDescription() == null ? "" : error.getDescription() + " ";
1✔
790
            Status errorWithNodeId = error.withDescription(
1✔
791
                    description + "xDS node ID: " + xdsClient.getBootstrapInfo().node().getId());
1✔
792
            logger.log(Level.WARNING, "Error loading RDS resource {0} from XdsClient: {1}.",
1✔
793
                    new Object[]{resourceName, errorWithNodeId});
1✔
794
            maybeUpdateSelector();
1✔
795
          }
1✔
796
        });
797
      }
1✔
798

799
      private void updateRdsRoutingConfig() {
800
        for (FilterChain filterChain : savedRdsRoutingConfigRef.keySet()) {
1✔
801
          HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
802
          if (!resourceName.equals(hcm.rdsName())) {
1✔
803
            continue;
1✔
804
          }
805

806
          ServerRoutingConfig updatedRoutingConfig;
807
          if (savedVirtualHosts == null) {
1✔
808
            updatedRoutingConfig = ServerRoutingConfig.FAILING_ROUTING_CONFIG;
1✔
809
          } else {
810
            HashMap<String, Filter> chainFilters = activeFilters.get(filterChain.name());
1✔
811
            ImmutableMap<Route, ServerInterceptor> interceptors = generatePerRouteInterceptors(
1✔
812
                hcm.httpFilterConfigs(), savedVirtualHosts, chainFilters);
1✔
813
            updatedRoutingConfig = ServerRoutingConfig.create(savedVirtualHosts, interceptors);
1✔
814
          }
815

816
          logger.log(Level.FINEST, "Updating filter chain {0} rds routing config: {1}",
1✔
817
              new Object[]{filterChain.name(), updatedRoutingConfig});
1✔
818
          savedRdsRoutingConfigRef.get(filterChain).set(updatedRoutingConfig);
1✔
819
        }
1✔
820
      }
1✔
821

822
      // Update the selector to use the most recently updated configs only after all rds have been
823
      // discovered for the first time. Later changes on rds will be applied through virtual host
824
      // list atomic ref.
825
      private void maybeUpdateSelector() {
826
        isPending = false;
1✔
827
        boolean isLastPending = pendingRds.remove(resourceName) && pendingRds.isEmpty();
1✔
828
        if (isLastPending) {
1✔
829
          updateSelector();
1✔
830
        }
831
      }
1✔
832
    }
833
  }
834

835
  @VisibleForTesting
836
  final class ConfigApplyingInterceptor implements ServerInterceptor {
1✔
837
    private final ServerInterceptor noopInterceptor = new ServerInterceptor() {
1✔
838
      @Override
839
      public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
840
          Metadata headers, ServerCallHandler<ReqT, RespT> next) {
841
        return next.startCall(call, headers);
×
842
      }
843
    };
844

845
    @Override
846
    public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
847
        Metadata headers, ServerCallHandler<ReqT, RespT> next) {
848
      AtomicReference<ServerRoutingConfig> routingConfigRef =
1✔
849
          call.getAttributes().get(ATTR_SERVER_ROUTING_CONFIG);
1✔
850
      ServerRoutingConfig routingConfig = routingConfigRef == null ? null :
1✔
851
          routingConfigRef.get();
1✔
852
      if (routingConfig == null || routingConfig == ServerRoutingConfig.FAILING_ROUTING_CONFIG) {
1✔
853
        String errorMsg = "Missing or broken xDS routing config: RDS config unavailable.";
1✔
854
        call.close(Status.UNAVAILABLE.withDescription(errorMsg), new Metadata());
1✔
855
        return new Listener<ReqT>() {};
1✔
856
      }
857
      List<VirtualHost> virtualHosts = routingConfig.virtualHosts();
1✔
858
      VirtualHost virtualHost = RoutingUtils.findVirtualHostForHostName(
1✔
859
          virtualHosts, call.getAuthority());
1✔
860
      if (virtualHost == null) {
1✔
861
        call.close(
1✔
862
            Status.UNAVAILABLE.withDescription("Could not find xDS virtual host matching RPC"),
1✔
863
            new Metadata());
864
        return new Listener<ReqT>() {};
1✔
865
      }
866
      Route selectedRoute = null;
1✔
867
      MethodDescriptor<ReqT, RespT> method = call.getMethodDescriptor();
1✔
868
      for (Route route : virtualHost.routes()) {
1✔
869
        if (RoutingUtils.matchRoute(
1✔
870
            route.routeMatch(), "/" + method.getFullMethodName(), headers, random)) {
1✔
871
          selectedRoute = route;
1✔
872
          break;
1✔
873
        }
874
      }
1✔
875
      if (selectedRoute == null) {
1✔
876
        call.close(Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"),
1✔
877
            new Metadata());
878
        return new ServerCall.Listener<ReqT>() {};
1✔
879
      }
880
      if (selectedRoute.routeAction() != null) {
1✔
881
        call.close(Status.UNAVAILABLE.withDescription("Invalid xDS route action for matching "
1✔
882
            + "route: only Route.non_forwarding_action should be allowed."), new Metadata());
883
        return new ServerCall.Listener<ReqT>() {};
1✔
884
      }
885
      ServerInterceptor routeInterceptor = noopInterceptor;
1✔
886
      Map<Route, ServerInterceptor> perRouteInterceptors = routingConfig.interceptors();
1✔
887
      if (perRouteInterceptors != null && perRouteInterceptors.get(selectedRoute) != null) {
1✔
888
        routeInterceptor = perRouteInterceptors.get(selectedRoute);
1✔
889
      }
890
      return routeInterceptor.interceptCall(call, headers, next);
1✔
891
    }
892
  }
893

894
  /**
895
   * The HttpConnectionManager level configuration.
896
   */
897
  @AutoValue
898
  abstract static class ServerRoutingConfig {
1✔
899
    @VisibleForTesting
900
    static final ServerRoutingConfig FAILING_ROUTING_CONFIG = ServerRoutingConfig.create(
1✔
901
        ImmutableList.<VirtualHost>of(), ImmutableMap.<Route, ServerInterceptor>of());
1✔
902

903
    abstract ImmutableList<VirtualHost> virtualHosts();
904

905
    // Prebuilt per route server interceptors from http filter configs.
906
    abstract ImmutableMap<Route, ServerInterceptor> interceptors();
907

908
    /**
909
     * Server routing configuration.
910
     * */
911
    public static ServerRoutingConfig create(
912
        ImmutableList<VirtualHost> virtualHosts,
913
        ImmutableMap<Route, ServerInterceptor> interceptors) {
914
      checkNotNull(virtualHosts, "virtualHosts");
1✔
915
      checkNotNull(interceptors, "interceptors");
1✔
916
      return new AutoValue_XdsServerWrapper_ServerRoutingConfig(virtualHosts, interceptors);
1✔
917
    }
918
  }
919
}
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