mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 00:56:50 +00:00
Move omnibus h2 connection logic into a factory
This commit is contained in:
1 parent
27980ed25d
commit
2220f750dd
9 files changed
+363
-237
No files matched your search
@@ -33,10 +33,11 @@ import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -193,11 +194,13 @@ import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.H2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
@@ -726,7 +729,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> dnsResolutionEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
@@ -1196,8 +1200,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusLocalEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory()));
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusNioEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
|
||||
final ServerBuilder<?> serverBuilder = NettyServerBuilder
|
||||
.forAddress(grpcLocalAddress)
|
||||
@@ -1214,10 +1220,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final H2ConnectionFactory grpcH2ConnectionFactory = new UnpooledH2ConnectionFactory(grpcLocalAddress, omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
websocketServletPath, websocketH2ConnectionFactory,
|
||||
provisioningWebsocketServletPath, websocketH2ConnectionFactory),
|
||||
grpcH2ConnectionFactory);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
|
||||
@@ -1226,7 +1234,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
omnibusNioEventLoopGroup.getEventLoopGroup(),
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup(),
|
||||
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
|
||||
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
|
||||
config.getGrpc().idleTimeout());
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.EventLoop;
|
||||
import java.net.SocketAddress;
|
||||
|
||||
/// A factory that creates h2 connections to some configured target address
|
||||
public interface H2ConnectionFactory {
|
||||
|
||||
/// Retrieve a h2 connection to [#address()]
|
||||
///
|
||||
/// @param callerEventLoop The event loop of the channel making this call
|
||||
ChannelFuture getConnection(final EventLoop callerEventLoop);
|
||||
|
||||
/// @return The [SocketAddress] that this factory targets
|
||||
SocketAddress address();
|
||||
}
|
||||
+6
-10
@@ -14,9 +14,9 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.DecoderException;
|
||||
@@ -67,8 +67,7 @@ public class OmnibusH2Server implements Managed {
|
||||
private final OmnibusRouter router;
|
||||
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
|
||||
private final Duration idleTimeout;
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
private final EventLoopGroup nioEventLoopGroup;
|
||||
private final SocketAddress bindAddress;
|
||||
|
||||
private Channel serverChannel;
|
||||
@@ -77,16 +76,14 @@ public class OmnibusH2Server implements Managed {
|
||||
///
|
||||
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
|
||||
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
|
||||
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
|
||||
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
|
||||
/// @param nioEventLoopGroup An Event loop with a [NioIoHandler#newFactory()] to use for all NIO channel pipelines
|
||||
/// @param bindAddress The address the server should listen on
|
||||
/// @param router How the server should select backends based on request paths
|
||||
/// @param configurationSupplier Dynamic configuration supplier
|
||||
/// @param idleTimeout How long to wait before terminating idle TCP connections
|
||||
public OmnibusH2Server(
|
||||
final @Nullable Mapping<String, SslContext> sslContextBySni,
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final EventLoopGroup nioEventLoopGroup,
|
||||
final SocketAddress bindAddress,
|
||||
final OmnibusRouter router,
|
||||
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
|
||||
@@ -94,7 +91,6 @@ public class OmnibusH2Server implements Managed {
|
||||
this.sslContextBySni = sslContextBySni;
|
||||
this.configurationSupplier = configurationSupplier;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.bindAddress = bindAddress;
|
||||
this.router = router;
|
||||
this.idleTimeout = idleTimeout;
|
||||
@@ -184,7 +180,7 @@ public class OmnibusH2Server implements Managed {
|
||||
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(nioEventLoopGroup, localEventLoopGroup, router));
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(router));
|
||||
}
|
||||
}));
|
||||
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
|
||||
|
||||
+7
-78
@@ -7,36 +7,22 @@ package org.whispersystems.textsecuregcm.grpc.net;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2Headers;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannel;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.ReferenceCounted;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -56,25 +42,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2StreamHandler.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_STREAM_COUNTER_NAME = name(OmnibusH2StreamHandler.class, "backendStream");
|
||||
private static final String BACKEND_CONNECT_DURATION_NAME = name(OmnibusH2StreamHandler.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
private final OmnibusRouter router;
|
||||
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
|
||||
public OmnibusH2StreamHandler(
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final OmnibusRouter router) {
|
||||
public OmnibusH2StreamHandler(final OmnibusRouter router) {
|
||||
this.router = router;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,8 +70,8 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
// Select the target backend based on the path
|
||||
final String path = Optional.ofNullable(headersFrame.headers().path()).map(CharSequence::toString).orElse("");
|
||||
final SocketAddress target = router.match(path);
|
||||
final String backendTag = target.toString();
|
||||
final H2ConnectionFactory connectionFactory = router.match(path);
|
||||
final String backendTag = connectionFactory.address().toString();
|
||||
|
||||
Metrics.counter(BACKEND_STREAM_COUNTER_NAME, BACKEND_TAG, backendTag).increment();
|
||||
|
||||
@@ -109,32 +83,12 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
? proxyRemoteAddress.getHostAddress()
|
||||
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
|
||||
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
new Bootstrap()
|
||||
.group(selectEventLoop(ctx, target))
|
||||
.channel(target instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(target)
|
||||
// Make an H2 connection to the target backend
|
||||
connectionFactory.getConnection(ctx.channel().eventLoop())
|
||||
.addListener((ChannelFuture connectFuture) -> {
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_DURATION_NAME)
|
||||
.tag(BACKEND_TAG, backendTag)
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
if (!connectFuture.isSuccess()) {
|
||||
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
|
||||
logger.warn("Failed to connect to backend {}", target, connectFuture.cause());
|
||||
logger.warn("Failed to connect to backend {}", backendTag, connectFuture.cause());
|
||||
ctx.channel()
|
||||
.writeAndFlush(new DefaultHttp2HeadersFrame(
|
||||
new DefaultHttp2Headers().status("502"), true))
|
||||
@@ -143,7 +97,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
}
|
||||
|
||||
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", backendTag);
|
||||
final Channel backendConnection = connectFuture.channel();
|
||||
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
|
||||
});
|
||||
@@ -204,29 +158,4 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private EventLoopGroup selectEventLoop(final ChannelHandlerContext inboundCtx, SocketAddress target) {
|
||||
final boolean localInbound = inboundCtx.channel() instanceof LocalChannel;
|
||||
final boolean localTarget = target instanceof LocalAddress;
|
||||
|
||||
// If the inbound eventloop matches the target type, we can just reuse the inbound's event loop
|
||||
if (localInbound == localTarget) {
|
||||
return inboundCtx.channel().eventLoop();
|
||||
}
|
||||
|
||||
return localTarget ? this.localEventLoopGroup : this.nioEventLoopGroup;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,21 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
|
||||
public class OmnibusRouter {
|
||||
|
||||
private final Map<String, SocketAddress> routes;
|
||||
private final SocketAddress defaultBackend;
|
||||
private final Map<String, H2ConnectionFactory> routesByPath;
|
||||
private final H2ConnectionFactory defaultBackend;
|
||||
|
||||
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
|
||||
this.routes = routes;
|
||||
public OmnibusRouter(final Map<String, H2ConnectionFactory> routesByPath, final H2ConnectionFactory defaultBackend) {
|
||||
this.routesByPath = routesByPath;
|
||||
this.defaultBackend = defaultBackend;
|
||||
}
|
||||
|
||||
SocketAddress match(final String fullPath) {
|
||||
H2ConnectionFactory match(final String fullPath) {
|
||||
final int queryIndex = fullPath.indexOf('?');
|
||||
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
|
||||
return routes.getOrDefault(path, defaultBackend);
|
||||
return routesByPath.getOrDefault(path, defaultBackend);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.util.concurrent.EventExecutor;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UnpooledH2ConnectionFactory.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_CONNECT_TIMER_NAME = name(UnpooledH2ConnectionFactory.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
|
||||
private final SocketAddress targetAddress;
|
||||
private final Class<? extends Channel> channelClass;
|
||||
private final EventLoopGroup eventLoopGroup;
|
||||
private final Set<EventExecutor> eventLoops;
|
||||
|
||||
public UnpooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
|
||||
this.targetAddress = targetAddress;
|
||||
this.channelClass = targetAddress instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class;
|
||||
this.eventLoopGroup = eventLoopGroup;
|
||||
this.eventLoops = ImmutableSet.copyOf(eventLoopGroup);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelFuture getConnection(final EventLoop callerEventLoop) {
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
|
||||
return new Bootstrap()
|
||||
// If the caller is already on one of our event loops, connect on that loop so this connection runs on the
|
||||
// caller's thread
|
||||
.group(eventLoops.contains(callerEventLoop) ? callerEventLoop : eventLoopGroup)
|
||||
.channel(channelClass)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(targetAddress)
|
||||
.addListener((ChannelFuture connectFuture) ->
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_TIMER_NAME)
|
||||
.tag(BACKEND_TAG, targetAddress.toString())
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress address() {
|
||||
return targetAddress;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
+196
-126
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
@@ -16,12 +17,13 @@ import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioChannelOption;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
@@ -66,7 +68,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -114,8 +116,8 @@ class OmnibusH2ServerTest {
|
||||
|
||||
private static final String TEST_DOMAIN = "foo.example.com";
|
||||
|
||||
private static NioEventLoopGroup nioEventLoopGroup;
|
||||
private static DefaultEventLoopGroup localEventLoopGroup;
|
||||
private static EventLoopGroup nioEventLoopGroup;
|
||||
private static EventLoopGroup localEventLoopGroup;
|
||||
|
||||
private static Mapping<String, SslContext> sniMapping;
|
||||
|
||||
@@ -147,8 +149,8 @@ class OmnibusH2ServerTest {
|
||||
sniMapping = SniMapper.buildSniMapping(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()),
|
||||
new String(keyStorePassword), SslProvider.OPENSSL);
|
||||
|
||||
nioEventLoopGroup = new NioEventLoopGroup();
|
||||
localEventLoopGroup = new DefaultEventLoopGroup();
|
||||
nioEventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
|
||||
localEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -177,9 +179,10 @@ class OmnibusH2ServerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void defaultBackend(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.start();
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
|
||||
assertEquals(DEFAULT_BACKEND_IDENTITY, response);
|
||||
}
|
||||
@@ -191,7 +194,7 @@ class OmnibusH2ServerTest {
|
||||
final HAProxyMessage proxyMessage = usePpv2
|
||||
? new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, expectedSource, "127.0.0.2", 1234, 5678)
|
||||
: null;
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer().start();
|
||||
final Channel h2Connection = connectToOmnibus(server, proxyMessage);
|
||||
final String xForwardedFor = sendRequestThroughOmnibus(h2Connection, "/forwarded-for");
|
||||
assertEquals(expectedSource, xForwardedFor);
|
||||
@@ -201,9 +204,9 @@ class OmnibusH2ServerTest {
|
||||
void pathBackend(
|
||||
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/v1/path/", "/v1/path/?foo=bar", "/v1/path/?foo=bar&baz=quux"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.start();
|
||||
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
|
||||
assertEquals(PATH_BACKEND_IDENTITY, response);
|
||||
}
|
||||
@@ -212,9 +215,10 @@ class OmnibusH2ServerTest {
|
||||
void multipleStreamsOnSameConnection(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean defaultLocalChannel,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean prefixLocalChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(prefixLocalChannel, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(defaultLocalChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().localChannel(prefixLocalChannel).identity(PATH_BACKEND_IDENTITY))
|
||||
.addDefault(backendServer().localChannel(defaultLocalChannel))
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final int numStreams = 10;
|
||||
|
||||
@@ -239,11 +243,11 @@ class OmnibusH2ServerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void backendDownStreamReset(final boolean localChannel) throws Exception {
|
||||
final Channel backend = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY);
|
||||
final OmnibusH2Server server = startOmnibusServer(backend);
|
||||
final BackendServerBuilder backend = backendServer().localChannel(localChannel);
|
||||
final OmnibusH2Server server = omnibusServer().addDefault(backend).start();
|
||||
|
||||
// Kill the default backend so connection attempts from the omnibus fail
|
||||
backend.close().syncUninterruptibly();
|
||||
backend.channel().close().syncUninterruptibly();
|
||||
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<Http2HeadersFrame> headersFuture = new CompletableFuture<>();
|
||||
@@ -275,7 +279,7 @@ class OmnibusH2ServerTest {
|
||||
void backendCloseClosesClientStream(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
|
||||
@CartesianTest.Values(strings = {"/goaway", "/reset"}) final String path) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer().addDefault(backendServer().localChannel(localChannel)).start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final CompletableFuture<Http2ResetFrame> resetFuture = new CompletableFuture<>();
|
||||
@@ -301,7 +305,7 @@ class OmnibusH2ServerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void queuedDataFrames(final boolean localChannel) throws Exception {
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer().addDefault(backendServer().localChannel(localChannel)).start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
|
||||
@@ -341,8 +345,11 @@ class OmnibusH2ServerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void clientDisconnectClosesBackendConnections(final boolean localChannel) throws Exception {
|
||||
final CompletableFuture<Channel> backendH2Connection = new CompletableFuture<>();
|
||||
final Channel backendServerChannel = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY, backendH2Connection::complete, _ -> {});
|
||||
final OmnibusH2Server server = startOmnibusServer(backendServerChannel);
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.h2ChannelInit(backendH2Connection::complete))
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
|
||||
@@ -373,12 +380,15 @@ class OmnibusH2ServerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void requestBackpressure(final boolean localChannel) throws Exception {
|
||||
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
|
||||
final Channel backendServer = startBackendServer(localChannel, "request-backpressure", _ -> {
|
||||
}, ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
backendStreamChannel.set(ch);
|
||||
});
|
||||
final OmnibusH2Server omnibusH2Server = startOmnibusServer(backendServer);
|
||||
final OmnibusH2Server omnibusH2Server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.identity("request-backpressure")
|
||||
.h2StreamInit(ch -> {
|
||||
ch.config().setAutoRead(false);
|
||||
backendStreamChannel.set(ch);
|
||||
}))
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(omnibusH2Server, null);
|
||||
|
||||
// We'll take the client channel becoming unwritable as backpressure signal
|
||||
@@ -457,21 +467,25 @@ class OmnibusH2ServerTest {
|
||||
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
|
||||
final AtomicLong pendingWhenUnwritable = new AtomicLong();
|
||||
|
||||
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, "response-backpressure",
|
||||
_ -> {}, ch -> {
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
|
||||
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
|
||||
// A change in writability on the backend stream means we introduced backpressure
|
||||
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
|
||||
backendStreamUnwritable.countDown();
|
||||
}
|
||||
backendStreamCtx.fireChannelWritabilityChanged();
|
||||
}
|
||||
});
|
||||
backendStreamInitialized.countDown();
|
||||
}));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addDefault(backendServer()
|
||||
.localChannel(localChannel)
|
||||
.identity("response-backpressure")
|
||||
.h2StreamInit(ch -> {
|
||||
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
|
||||
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
|
||||
// A change in writability on the backend stream means we introduced backpressure
|
||||
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
|
||||
backendStreamUnwritable.countDown();
|
||||
}
|
||||
backendStreamCtx.fireChannelWritabilityChanged();
|
||||
}
|
||||
});
|
||||
backendStreamInitialized.countDown();
|
||||
}))
|
||||
.start();
|
||||
final Channel h2Connection = connectToOmnibus(server);
|
||||
|
||||
final AtomicReference<Http2StreamChannel> clientStream = new AtomicReference<>();
|
||||
@@ -503,8 +517,10 @@ class OmnibusH2ServerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void idleTest(final boolean localChannel) throws Exception {
|
||||
final Duration timeout = Duration.ofMillis(500);
|
||||
final OmnibusH2Server timeoutServer =
|
||||
startOmnibusServer(Collections.emptyMap(), startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY), timeout);
|
||||
final OmnibusH2Server timeoutServer = omnibusServer()
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.idleTimeout(timeout)
|
||||
.start();
|
||||
final Channel channel = connectToOmnibus(timeoutServer, null);
|
||||
|
||||
// Send a request to make sure idleTimeouts work even after a stream / backend connection has been established
|
||||
@@ -519,9 +535,9 @@ class OmnibusH2ServerTest {
|
||||
@Test
|
||||
void loadShed() throws Exception {
|
||||
dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE));
|
||||
final OmnibusH2Server server = startOmnibusServer(
|
||||
Map.of(PATH, startBackendServer(true, PATH_BACKEND_IDENTITY)),
|
||||
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.addRoute(PATH, backendServer().identity(PATH_BACKEND_IDENTITY))
|
||||
.start();
|
||||
|
||||
final CompletableFuture<Http2GoAwayFrame> goAwayFuture = new CompletableFuture<>();
|
||||
final Bootstrap clientBootstrap = new Bootstrap()
|
||||
@@ -570,8 +586,8 @@ class OmnibusH2ServerTest {
|
||||
@CartesianTest.Values(ints = {10}) final int repetitions) throws Exception {
|
||||
|
||||
// Use two threads to make sure that our connections are working concurrently
|
||||
final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(2);
|
||||
final DefaultEventLoopGroup localEventLoopGroup = new DefaultEventLoopGroup(2);
|
||||
final EventLoopGroup nioEventLoopGroup = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
|
||||
final EventLoopGroup localEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
|
||||
|
||||
groupsToShutDown.add(nioEventLoopGroup);
|
||||
groupsToShutDown.add(localEventLoopGroup);
|
||||
@@ -581,11 +597,10 @@ class OmnibusH2ServerTest {
|
||||
try {
|
||||
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
|
||||
|
||||
final OmnibusH2Server server = startOmnibusServer(nioEventLoopGroup, localEventLoopGroup,
|
||||
Collections.emptyMap(),
|
||||
startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup, localChannel,
|
||||
DEFAULT_BACKEND_IDENTITY, _ -> {}, _ -> {}),
|
||||
Duration.ofMinutes(1));
|
||||
final OmnibusH2Server server = omnibusServer()
|
||||
.eventLoopGroups(nioEventLoopGroup, localEventLoopGroup)
|
||||
.addDefault(backendServer().localChannel(localChannel))
|
||||
.start();
|
||||
|
||||
for (int i = 0; i < connections; i++) {
|
||||
clientConnections.add(connectToOmnibus(server));
|
||||
@@ -650,85 +665,140 @@ class OmnibusH2ServerTest {
|
||||
return body;
|
||||
}
|
||||
|
||||
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
|
||||
///
|
||||
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
|
||||
/// @param defaultBackend The target backend if no prefix routes match the request path
|
||||
/// @param timeout The omnibus idle timeout
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
|
||||
return startOmnibusServer(nioEventLoopGroup, localEventLoopGroup, routes, defaultBackend, timeout);
|
||||
/// A builder for an OmnibusH2Server. The started server and its backends will be torn down in [#tearDown()]
|
||||
private OmnibusServerBuilder omnibusServer() {
|
||||
return new OmnibusServerBuilder();
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final Map<String, Channel> routes,
|
||||
final Channel defaultBackend,
|
||||
final Duration timeout) throws Exception {
|
||||
backendChannelsToShutDown.addAll(routes.values());
|
||||
backendChannelsToShutDown.add(defaultBackend);
|
||||
private class OmnibusServerBuilder {
|
||||
|
||||
final OmnibusH2Server server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
nioEventLoopGroup,
|
||||
localEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> e.getValue().localAddress())),
|
||||
defaultBackend.localAddress()),
|
||||
dynamicConfiguration::get,
|
||||
timeout);
|
||||
server.start();
|
||||
omnibusH2ServersToShutDown.add(server);
|
||||
return server;
|
||||
private final Map<String, BackendServerBuilder> routes = new HashMap<>();
|
||||
private BackendServerBuilder defaultBackend = backendServer();
|
||||
private Duration idleTimeout = Duration.ofMinutes(1);
|
||||
private EventLoopGroup nioEventLoopGroup = OmnibusH2ServerTest.nioEventLoopGroup;
|
||||
private EventLoopGroup localEventLoopGroup = OmnibusH2ServerTest.localEventLoopGroup;
|
||||
|
||||
/// Requests with paths starting with `prefix` will go to `backend`
|
||||
OmnibusServerBuilder addRoute(final String prefix, final BackendServerBuilder backend) {
|
||||
routes.put(prefix, backend);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Requests that don't match any route will go to `backend`. Defaults to [#backendServer()].
|
||||
OmnibusServerBuilder addDefault(final BackendServerBuilder backend) {
|
||||
this.defaultBackend = backend;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Defaults to 1 minute
|
||||
OmnibusServerBuilder idleTimeout(final Duration idleTimeout) {
|
||||
this.idleTimeout = idleTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// The event loop groups used by the omnibus and its backends. Defaults to the shared event loop groups.
|
||||
OmnibusServerBuilder eventLoopGroups(final EventLoopGroup nioEventLoopGroup,
|
||||
final EventLoopGroup localEventLoopGroup) {
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Start the backends and then the omnibus
|
||||
OmnibusH2Server start() throws Exception {
|
||||
final OmnibusRouter router = new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> startBackend(e.getValue()))),
|
||||
startBackend(defaultBackend));
|
||||
|
||||
final OmnibusH2Server server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
nioEventLoopGroup,
|
||||
new InetSocketAddress("127.0.0.1", 0),
|
||||
router,
|
||||
dynamicConfiguration::get,
|
||||
idleTimeout);
|
||||
server.start();
|
||||
omnibusH2ServersToShutDown.add(server);
|
||||
return server;
|
||||
}
|
||||
|
||||
private H2ConnectionFactory startBackend(final BackendServerBuilder backend) {
|
||||
final EventLoopGroup eventLoopGroup = backend.localChannel ? localEventLoopGroup : nioEventLoopGroup;
|
||||
final Channel channel = backend.start(eventLoopGroup);
|
||||
backendChannelsToShutDown.add(channel);
|
||||
return new UnpooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup);
|
||||
}
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(Collections.emptyMap(), defaultBackend, Duration.ofMinutes(1));
|
||||
/// A builder for a h2c server that can be used as a target of the omnibus. The server is started by
|
||||
/// [OmnibusServerBuilder#start()].
|
||||
private BackendServerBuilder backendServer() {
|
||||
return new BackendServerBuilder();
|
||||
}
|
||||
|
||||
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend) throws Exception {
|
||||
return startOmnibusServer(routes, defaultBackend, Duration.ofMinutes(1));
|
||||
}
|
||||
private class BackendServerBuilder {
|
||||
|
||||
/// Start a h2c server that can be used as a target of the omnibus
|
||||
///
|
||||
/// @param localChannel whether the omnibus should target this backend via a LocalChannel or an NioChannel
|
||||
/// @param identity how the backend should respond to identity requests
|
||||
/// @param h2ChannelInit a Consumer that will be called every time a new HTTP/2 connection is made to this server
|
||||
/// @param h2StreamInit a Consumer that will be called every time a new HTTP/2 stream is created on this server
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
|
||||
return startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup,
|
||||
localChannel, identity, h2ChannelInit, h2StreamInit);
|
||||
}
|
||||
private boolean localChannel = true;
|
||||
private String identity = DEFAULT_BACKEND_IDENTITY;
|
||||
private Consumer<Channel> h2ChannelInit = _ -> {};
|
||||
private Consumer<Channel> h2StreamInit = _ -> {};
|
||||
@Nullable
|
||||
private Channel channel = null;
|
||||
|
||||
private Channel startBackendServer(final EventLoopGroup eventLoopGroup, final boolean localChannel,
|
||||
final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
|
||||
return new ServerBootstrap()
|
||||
.group(eventLoopGroup, eventLoopGroup)
|
||||
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
h2ChannelInit.accept(ch);
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
h2StreamInit.accept(ch);
|
||||
ch.pipeline().addLast(new TestHandler(identity));
|
||||
}
|
||||
}));
|
||||
}
|
||||
})
|
||||
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
}
|
||||
/// Whether the omnibus should target this backend via a LocalChannel or an NioChannel. Defaults to true.
|
||||
BackendServerBuilder localChannel(final boolean localChannel) {
|
||||
this.localChannel = localChannel;
|
||||
return this;
|
||||
}
|
||||
|
||||
private Channel startBackendServer(final boolean localChannel, final String identity) {
|
||||
return startBackendServer(localChannel, identity, _ -> {}, _ -> {});
|
||||
/// How the backend should respond to identity requests. Defaults to [#DEFAULT_BACKEND_IDENTITY].
|
||||
BackendServerBuilder identity(final String identity) {
|
||||
this.identity = identity;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// A Consumer that will be called every time a new HTTP/2 connection is made to this server
|
||||
BackendServerBuilder h2ChannelInit(final Consumer<Channel> h2ChannelInit) {
|
||||
this.h2ChannelInit = h2ChannelInit;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// A Consumer that will be called every time a new HTTP/2 stream is created on this server
|
||||
BackendServerBuilder h2StreamInit(final Consumer<Channel> h2StreamInit) {
|
||||
this.h2StreamInit = h2StreamInit;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// The backend's server channel, once it has started
|
||||
Channel channel() {
|
||||
assertNotNull(channel, "backend has not started");
|
||||
return channel;
|
||||
}
|
||||
|
||||
private Channel start(final EventLoopGroup eventLoopGroup) {
|
||||
channel = new ServerBootstrap()
|
||||
.group(eventLoopGroup, eventLoopGroup)
|
||||
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
h2ChannelInit.accept(ch);
|
||||
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
h2StreamInit.accept(ch);
|
||||
ch.pipeline().addLast(new TestHandler(identity));
|
||||
}
|
||||
}));
|
||||
}
|
||||
})
|
||||
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
|
||||
.syncUninterruptibly()
|
||||
.channel();
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes an H2 connection to the omnibus at `server` on which new H2 streams can be opened
|
||||
|
||||
@@ -15,10 +15,12 @@ import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.handler.ssl.SniHandler;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -73,7 +75,7 @@ class SniMapperTest {
|
||||
CertificateBuilder.Algorithm.rsa2048
|
||||
};
|
||||
|
||||
private static DefaultEventLoopGroup eventLoopGroup;
|
||||
private static EventLoopGroup eventLoopGroup;
|
||||
private static final Map<SslProvider, Mapping<String, SslContext>> sniMappingsByProvider =
|
||||
new EnumMap<>(SslProvider.class);
|
||||
|
||||
@@ -113,7 +115,7 @@ class SniMapperTest {
|
||||
new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), new String(keyStorePassword), sslProvider));
|
||||
}
|
||||
|
||||
eventLoopGroup = new DefaultEventLoopGroup();
|
||||
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
private void startServer(final SslProvider sslProvider) throws InterruptedException {
|
||||
|
||||
+5
-4
@@ -18,10 +18,11 @@ import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultithreadEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.handler.ssl.SniHandler;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -62,7 +63,7 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
|
||||
private static final String DOMAIN = "example.org";
|
||||
|
||||
private static MultithreadEventLoopGroup eventLoopGroup;
|
||||
private static EventLoopGroup eventLoopGroup;
|
||||
private static byte[] keyStoreBytes;
|
||||
private static String keyStorePassword;
|
||||
|
||||
@@ -94,7 +95,7 @@ class TlsHandshakeMetricsHandlerTest {
|
||||
keyStoreBytes = byteArrayOutputStream.toByteArray();
|
||||
keyStorePassword = new String(password);
|
||||
|
||||
eventLoopGroup = new DefaultEventLoopGroup();
|
||||
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
|
||||
Reference in new issue
Block a user