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

grpc / grpc-java / #19682

11 Feb 2025 01:14AM CUT coverage: 88.605% (-0.004%) from 88.609%
#19682

push

github

web-flow
xds: improve code readability of server FilterChain parsing

- Improve code flow and variable names
- Reduce nesting
- Add comments between logical blocks
- Add comments explaining some xDS/gRPC nuances

34182 of 38578 relevant lines covered (88.6%)

0.89 hits per line

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

94.17
/../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.HashMap;
64
import java.util.HashSet;
65
import java.util.List;
66
import java.util.Map;
67
import java.util.Set;
68
import java.util.concurrent.CountDownLatch;
69
import java.util.concurrent.ExecutionException;
70
import java.util.concurrent.ScheduledExecutorService;
71
import java.util.concurrent.TimeUnit;
72
import java.util.concurrent.atomic.AtomicBoolean;
73
import java.util.concurrent.atomic.AtomicReference;
74
import java.util.logging.Level;
75
import java.util.logging.Logger;
76
import javax.annotation.Nullable;
77

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

460
    private void updateSelector() {
461
      // This is regenerated in generateRoutingConfig() calls below.
462
      savedRdsRoutingConfigRef.clear();
1✔
463

464
      // Prepare server routing config map.
465
      ImmutableMap.Builder<FilterChain, AtomicReference<ServerRoutingConfig>> routingConfigs =
466
          ImmutableMap.builder();
1✔
467
      for (FilterChain filterChain: filterChains) {
1✔
468
        routingConfigs.put(filterChain, generateRoutingConfig(filterChain));
1✔
469
      }
1✔
470

471
      // Prepare the new selector.
472
      FilterChainSelector selector;
473
      if (defaultFilterChain != null) {
1✔
474
        selector = new FilterChainSelector(
1✔
475
            routingConfigs.build(),
1✔
476
            defaultFilterChain.sslContextProviderSupplier(),
1✔
477
            generateRoutingConfig(defaultFilterChain));
1✔
478
      } else {
479
        selector = new FilterChainSelector(routingConfigs.build(), null, new AtomicReference<>());
1✔
480
      }
481

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

485
      // Swap the selectors, initiate a graceful shutdown of the old one.
486
      logger.log(Level.FINEST, "Updating selector {0}", selector);
1✔
487
      filterChainSelectorManager.updateSelector(selector);
1✔
488

489
      // Release old resources.
490
      for (SslContextProviderSupplier supplier: oldSslSuppliers) {
1✔
491
        supplier.close();
1✔
492
      }
1✔
493

494
      // Now that we have valid Transport Socket config, we can start/restart listening on a port.
495
      startDelegateServer();
1✔
496
    }
1✔
497

498
    private AtomicReference<ServerRoutingConfig> generateRoutingConfig(FilterChain filterChain) {
499
      HttpConnectionManager hcm = filterChain.httpConnectionManager();
1✔
500
      ImmutableMap<Route, ServerInterceptor> interceptors;
501

502
      // Inlined routes.
503
      if (hcm.virtualHosts() != null) {
1✔
504
        interceptors = generatePerRouteInterceptors(hcm.httpFilterConfigs(), hcm.virtualHosts());
1✔
505
        return new AtomicReference<>(ServerRoutingConfig.create(hcm.virtualHosts(), interceptors));
1✔
506
      }
507

508
      // Routes from RDS.
509
      RouteDiscoveryState rds = routeDiscoveryStates.get(hcm.rdsName());
1✔
510
      checkNotNull(rds, "rds");
1✔
511

512
      ServerRoutingConfig routingConfig;
513
      ImmutableList<VirtualHost> savedVhosts = rds.savedVirtualHosts;
1✔
514
      if (savedVhosts != null) {
1✔
515
        interceptors = generatePerRouteInterceptors(hcm.httpFilterConfigs(), savedVhosts);
1✔
516
        routingConfig = ServerRoutingConfig.create(savedVhosts, interceptors);
1✔
517
      } else {
518
        routingConfig = ServerRoutingConfig.FAILING_ROUTING_CONFIG;
1✔
519
      }
520

521
      AtomicReference<ServerRoutingConfig> routingConfigRef = new AtomicReference<>(routingConfig);
1✔
522
      savedRdsRoutingConfigRef.put(filterChain, routingConfigRef);
1✔
523
      return routingConfigRef;
1✔
524
    }
525

526
    private ImmutableMap<Route, ServerInterceptor> generatePerRouteInterceptors(
527
        List<NamedFilterConfig> namedFilterConfigs, List<VirtualHost> virtualHosts) {
528
      ImmutableMap.Builder<Route, ServerInterceptor> perRouteInterceptors =
1✔
529
          new ImmutableMap.Builder<>();
530
      for (VirtualHost virtualHost : virtualHosts) {
1✔
531
        for (Route route : virtualHost.routes()) {
1✔
532
          List<ServerInterceptor> filterInterceptors = new ArrayList<>();
1✔
533
          Map<String, FilterConfig> selectedOverrideConfigs =
1✔
534
              new HashMap<>(virtualHost.filterConfigOverrides());
1✔
535
          selectedOverrideConfigs.putAll(route.filterConfigOverrides());
1✔
536
          if (namedFilterConfigs != null) {
1✔
537
            for (NamedFilterConfig namedFilterConfig : namedFilterConfigs) {
1✔
538
              FilterConfig filterConfig = namedFilterConfig.filterConfig;
1✔
539
              Filter filter = filterRegistry.get(filterConfig.typeUrl());
1✔
540
              if (filter instanceof ServerInterceptorBuilder) {
1✔
541
                ServerInterceptor interceptor =
1✔
542
                    ((ServerInterceptorBuilder) filter).buildServerInterceptor(
1✔
543
                        filterConfig, selectedOverrideConfigs.get(namedFilterConfig.name));
1✔
544
                if (interceptor != null) {
1✔
545
                  filterInterceptors.add(interceptor);
1✔
546
                }
547
              } else {
1✔
548
                logger.log(Level.WARNING, "HttpFilterConfig(type URL: "
×
549
                    + filterConfig.typeUrl() + ") is not supported on server-side. "
×
550
                    + "Probably a bug at ClientXdsClient verification.");
551
              }
552
            }
1✔
553
          }
554
          ServerInterceptor interceptor = combineInterceptors(filterInterceptors);
1✔
555
          perRouteInterceptors.put(route, interceptor);
1✔
556
        }
1✔
557
      }
1✔
558
      return perRouteInterceptors.buildOrThrow();
1✔
559
    }
560

561
    private ServerInterceptor combineInterceptors(final List<ServerInterceptor> interceptors) {
562
      if (interceptors.isEmpty()) {
1✔
563
        return noopInterceptor;
1✔
564
      }
565
      if (interceptors.size() == 1) {
1✔
566
        return interceptors.get(0);
×
567
      }
568
      return new ServerInterceptor() {
1✔
569
        @Override
570
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
571
            Metadata headers, ServerCallHandler<ReqT, RespT> next) {
572
          // intercept forward
573
          for (int i = interceptors.size() - 1; i >= 0; i--) {
1✔
574
            next = InternalServerInterceptors.interceptCallHandlerCreate(
1✔
575
                interceptors.get(i), next);
1✔
576
          }
577
          return next.startCall(call, headers);
1✔
578
        }
579
      };
580
    }
581

582
    private void handleConfigNotFound(StatusException exception) {
583
      cleanUpRouteDiscoveryStates();
1✔
584
      List<SslContextProviderSupplier> toRelease = getSuppliersInUse();
1✔
585
      filterChainSelectorManager.updateSelector(FilterChainSelector.NO_FILTER_CHAIN);
1✔
586
      for (SslContextProviderSupplier s: toRelease) {
1✔
587
        s.close();
1✔
588
      }
1✔
589
      if (restartTimer != null) {
1✔
590
        restartTimer.cancel();
1✔
591
      }
592
      if (!delegate.isShutdown()) {
1✔
593
        delegate.shutdown();  // let in-progress calls finish
1✔
594
      }
595
      isServing = false;
1✔
596
      listener.onNotServing(exception);
1✔
597
    }
1✔
598

599
    private void cleanUpRouteDiscoveryStates() {
600
      for (RouteDiscoveryState rdsState : routeDiscoveryStates.values()) {
1✔
601
        String rdsName = rdsState.resourceName;
1✔
602
        logger.log(Level.FINE, "Stop watching RDS resource {0}", rdsName);
1✔
603
        xdsClient.cancelXdsResourceWatch(XdsRouteConfigureResource.getInstance(), rdsName,
1✔
604
            rdsState);
605
      }
1✔
606
      routeDiscoveryStates.clear();
1✔
607
      savedRdsRoutingConfigRef.clear();
1✔
608
    }
1✔
609

610
    private List<SslContextProviderSupplier> getSuppliersInUse() {
611
      List<SslContextProviderSupplier> toRelease = new ArrayList<>();
1✔
612
      FilterChainSelector selector = filterChainSelectorManager.getSelectorToUpdateSelector();
1✔
613
      if (selector != null) {
1✔
614
        for (FilterChain f: selector.getRoutingConfigs().keySet()) {
1✔
615
          if (f.sslContextProviderSupplier() != null) {
1✔
616
            toRelease.add(f.sslContextProviderSupplier());
1✔
617
          }
618
        }
1✔
619
        SslContextProviderSupplier defaultSupplier =
1✔
620
                selector.getDefaultSslContextProviderSupplier();
1✔
621
        if (defaultSupplier != null) {
1✔
622
          toRelease.add(defaultSupplier);
1✔
623
        }
624
      }
625
      return toRelease;
1✔
626
    }
627

628
    private void releaseSuppliersInFlight() {
629
      SslContextProviderSupplier supplier;
630
      for (FilterChain filterChain : filterChains) {
1✔
631
        supplier = filterChain.sslContextProviderSupplier();
1✔
632
        if (supplier != null) {
1✔
633
          supplier.close();
1✔
634
        }
635
      }
1✔
636
      if (defaultFilterChain != null
1✔
637
              && (supplier = defaultFilterChain.sslContextProviderSupplier()) != null) {
1✔
638
        supplier.close();
1✔
639
      }
640
    }
1✔
641

642
    private final class RouteDiscoveryState implements ResourceWatcher<RdsUpdate> {
643
      private final String resourceName;
644
      private ImmutableList<VirtualHost> savedVirtualHosts;
645
      private boolean isPending = true;
1✔
646

647
      private RouteDiscoveryState(String resourceName) {
1✔
648
        this.resourceName = checkNotNull(resourceName, "resourceName");
1✔
649
      }
1✔
650

651
      @Override
652
      public void onChanged(final RdsUpdate update) {
653
        syncContext.execute(new Runnable() {
1✔
654
          @Override
655
          public void run() {
656
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
657
              return;
1✔
658
            }
659
            if (savedVirtualHosts == null && !isPending) {
1✔
660
              logger.log(Level.WARNING, "Received valid Rds {0} configuration.", resourceName);
1✔
661
            }
662
            savedVirtualHosts = ImmutableList.copyOf(update.virtualHosts);
1✔
663
            updateRdsRoutingConfig();
1✔
664
            maybeUpdateSelector();
1✔
665
          }
1✔
666
        });
667
      }
1✔
668

669
      @Override
670
      public void onResourceDoesNotExist(final String resourceName) {
671
        syncContext.execute(new Runnable() {
1✔
672
          @Override
673
          public void run() {
674
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
675
              return;
×
676
            }
677
            logger.log(Level.WARNING, "Rds {0} unavailable", resourceName);
1✔
678
            savedVirtualHosts = null;
1✔
679
            updateRdsRoutingConfig();
1✔
680
            maybeUpdateSelector();
1✔
681
          }
1✔
682
        });
683
      }
1✔
684

685
      @Override
686
      public void onError(final Status error) {
687
        syncContext.execute(new Runnable() {
1✔
688
          @Override
689
          public void run() {
690
            if (!routeDiscoveryStates.containsKey(resourceName)) {
1✔
691
              return;
×
692
            }
693
            String description = error.getDescription() == null ? "" : error.getDescription() + " ";
1✔
694
            Status errorWithNodeId = error.withDescription(
1✔
695
                    description + "xDS node ID: " + xdsClient.getBootstrapInfo().node().getId());
1✔
696
            logger.log(Level.WARNING, "Error loading RDS resource {0} from XdsClient: {1}.",
1✔
697
                    new Object[]{resourceName, errorWithNodeId});
1✔
698
            maybeUpdateSelector();
1✔
699
          }
1✔
700
        });
701
      }
1✔
702

703
      private void updateRdsRoutingConfig() {
704
        for (FilterChain filterChain : savedRdsRoutingConfigRef.keySet()) {
1✔
705
          if (resourceName.equals(filterChain.httpConnectionManager().rdsName())) {
1✔
706
            ServerRoutingConfig updatedRoutingConfig;
707
            if (savedVirtualHosts == null) {
1✔
708
              updatedRoutingConfig = ServerRoutingConfig.FAILING_ROUTING_CONFIG;
1✔
709
            } else {
710
              ImmutableMap<Route, ServerInterceptor> updatedInterceptors =
1✔
711
                  generatePerRouteInterceptors(
1✔
712
                      filterChain.httpConnectionManager().httpFilterConfigs(),
1✔
713
                      savedVirtualHosts);
714
              updatedRoutingConfig = ServerRoutingConfig.create(savedVirtualHosts,
1✔
715
                  updatedInterceptors);
716
            }
717
            logger.log(Level.FINEST, "Updating filter chain {0} rds routing config: {1}",
1✔
718
                new Object[]{filterChain.name(), updatedRoutingConfig});
1✔
719
            savedRdsRoutingConfigRef.get(filterChain).set(updatedRoutingConfig);
1✔
720
          }
721
        }
1✔
722
      }
1✔
723

724
      // Update the selector to use the most recently updated configs only after all rds have been
725
      // discovered for the first time. Later changes on rds will be applied through virtual host
726
      // list atomic ref.
727
      private void maybeUpdateSelector() {
728
        isPending = false;
1✔
729
        boolean isLastPending = pendingRds.remove(resourceName) && pendingRds.isEmpty();
1✔
730
        if (isLastPending) {
1✔
731
          updateSelector();
1✔
732
        }
733
      }
1✔
734
    }
735
  }
736

737
  @VisibleForTesting
738
  final class ConfigApplyingInterceptor implements ServerInterceptor {
1✔
739
    private final ServerInterceptor noopInterceptor = new ServerInterceptor() {
1✔
740
      @Override
741
      public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
742
          Metadata headers, ServerCallHandler<ReqT, RespT> next) {
743
        return next.startCall(call, headers);
×
744
      }
745
    };
746

747
    @Override
748
    public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
749
        Metadata headers, ServerCallHandler<ReqT, RespT> next) {
750
      AtomicReference<ServerRoutingConfig> routingConfigRef =
1✔
751
          call.getAttributes().get(ATTR_SERVER_ROUTING_CONFIG);
1✔
752
      ServerRoutingConfig routingConfig = routingConfigRef == null ? null :
1✔
753
          routingConfigRef.get();
1✔
754
      if (routingConfig == null || routingConfig == ServerRoutingConfig.FAILING_ROUTING_CONFIG) {
1✔
755
        String errorMsg = "Missing or broken xDS routing config: RDS config unavailable.";
1✔
756
        call.close(Status.UNAVAILABLE.withDescription(errorMsg), new Metadata());
1✔
757
        return new Listener<ReqT>() {};
1✔
758
      }
759
      List<VirtualHost> virtualHosts = routingConfig.virtualHosts();
1✔
760
      VirtualHost virtualHost = RoutingUtils.findVirtualHostForHostName(
1✔
761
          virtualHosts, call.getAuthority());
1✔
762
      if (virtualHost == null) {
1✔
763
        call.close(
1✔
764
            Status.UNAVAILABLE.withDescription("Could not find xDS virtual host matching RPC"),
1✔
765
            new Metadata());
766
        return new Listener<ReqT>() {};
1✔
767
      }
768
      Route selectedRoute = null;
1✔
769
      MethodDescriptor<ReqT, RespT> method = call.getMethodDescriptor();
1✔
770
      for (Route route : virtualHost.routes()) {
1✔
771
        if (RoutingUtils.matchRoute(
1✔
772
            route.routeMatch(), "/" + method.getFullMethodName(), headers, random)) {
1✔
773
          selectedRoute = route;
1✔
774
          break;
1✔
775
        }
776
      }
1✔
777
      if (selectedRoute == null) {
1✔
778
        call.close(Status.UNAVAILABLE.withDescription("Could not find xDS route matching RPC"),
1✔
779
            new Metadata());
780
        return new ServerCall.Listener<ReqT>() {};
1✔
781
      }
782
      if (selectedRoute.routeAction() != null) {
1✔
783
        call.close(Status.UNAVAILABLE.withDescription("Invalid xDS route action for matching "
1✔
784
            + "route: only Route.non_forwarding_action should be allowed."), new Metadata());
785
        return new ServerCall.Listener<ReqT>() {};
1✔
786
      }
787
      ServerInterceptor routeInterceptor = noopInterceptor;
1✔
788
      Map<Route, ServerInterceptor> perRouteInterceptors = routingConfig.interceptors();
1✔
789
      if (perRouteInterceptors != null && perRouteInterceptors.get(selectedRoute) != null) {
1✔
790
        routeInterceptor = perRouteInterceptors.get(selectedRoute);
1✔
791
      }
792
      return routeInterceptor.interceptCall(call, headers, next);
1✔
793
    }
794
  }
795

796
  /**
797
   * The HttpConnectionManager level configuration.
798
   */
799
  @AutoValue
800
  abstract static class ServerRoutingConfig {
1✔
801
    @VisibleForTesting
802
    static final ServerRoutingConfig FAILING_ROUTING_CONFIG = ServerRoutingConfig.create(
1✔
803
        ImmutableList.<VirtualHost>of(), ImmutableMap.<Route, ServerInterceptor>of());
1✔
804

805
    abstract ImmutableList<VirtualHost> virtualHosts();
806

807
    // Prebuilt per route server interceptors from http filter configs.
808
    abstract ImmutableMap<Route, ServerInterceptor> interceptors();
809

810
    /**
811
     * Server routing configuration.
812
     * */
813
    public static ServerRoutingConfig create(
814
        ImmutableList<VirtualHost> virtualHosts,
815
        ImmutableMap<Route, ServerInterceptor> interceptors) {
816
      checkNotNull(virtualHosts, "virtualHosts");
1✔
817
      checkNotNull(interceptors, "interceptors");
1✔
818
      return new AutoValue_XdsServerWrapper_ServerRoutingConfig(virtualHosts, interceptors);
1✔
819
    }
820
  }
821
}
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