use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project netty by netty.
the class NettyBlockHoundIntegrationTest method testSslHandlerWrapAllowsBlockingCalls.
@Test
public void testSslHandlerWrapAllowsBlockingCalls() throws Exception {
final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
final EventLoopGroup group = new NioEventLoopGroup();
final CountDownLatch activeLatch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<>();
Channel sc = null;
Channel cc = null;
try {
sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(sslHandler);
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
activeLatch.countDown();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).cause() != null) {
Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
cause.printStackTrace();
error.set(cause);
}
ctx.fireUserEventTriggered(evt);
}
});
}
}).connect(sc.localAddress()).addListener((ChannelFutureListener) future -> future.channel().writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }))).syncUninterruptibly().channel();
assertTrue(activeLatch.await(5, TimeUnit.SECONDS));
assertNull(error.get());
} finally {
if (cc != null) {
cc.close().syncUninterruptibly();
}
if (sc != null) {
sc.close().syncUninterruptibly();
}
group.shutdownGracefully();
ReferenceCountUtil.release(sslClientCtx);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project netty by netty.
the class OcspServerExample method newServerHandler.
private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context, final OCSPResp response) {
return new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
SslHandler sslHandler = context.newHandler(ch.alloc());
if (response != null) {
ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
engine.setOcspResponse(response.getEncoded());
}
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslHandler);
// so on and so forth...
}
};
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project netty by netty.
the class CipherSuiteCanaryTest method testHandshake.
@ParameterizedTest(name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}, rfcCipherName = {2}, delegate = {3}")
@MethodSource("parameters")
public void testHandshake(SslProvider serverSslProvider, SslProvider clientSslProvider, String rfcCipherName, boolean delegate) throws Exception {
// Check if the cipher is supported at all which may not be the case for various JDK versions and OpenSSL API
// implementations.
assumeCipherAvailable(serverSslProvider, rfcCipherName);
assumeCipherAvailable(clientSslProvider, rfcCipherName);
List<String> ciphers = Collections.singletonList(rfcCipherName);
final SslContext sslServerContext = SslContextBuilder.forServer(CERT.certificate(), CERT.privateKey()).sslProvider(serverSslProvider).ciphers(ciphers).protocols(SslProtocols.TLS_v1_2).build();
final ExecutorService executorService = delegate ? Executors.newCachedThreadPool() : null;
try {
final SslContext sslClientContext = SslContextBuilder.forClient().sslProvider(clientSslProvider).ciphers(ciphers).protocols(SslProtocols.TLS_v1_2).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
try {
final Promise<Object> serverPromise = GROUP.next().newPromise();
final Promise<Object> clientPromise = GROUP.next().newPromise();
ChannelHandler serverHandler = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), executorService));
pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
serverPromise.cancel(true);
ctx.fireChannelInactive();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (serverPromise.trySuccess(null)) {
ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'O', 'N', 'G' }));
}
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!serverPromise.tryFailure(cause)) {
ctx.fireExceptionCaught(cause);
}
}
});
}
};
LocalAddress address = new LocalAddress("test-" + serverSslProvider + '-' + clientSslProvider + '-' + rfcCipherName);
Channel server = server(address, serverHandler);
try {
ChannelHandler clientHandler = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), executorService));
pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
clientPromise.cancel(true);
ctx.fireChannelInactive();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
clientPromise.trySuccess(null);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (!clientPromise.tryFailure(cause)) {
ctx.fireExceptionCaught(cause);
}
}
});
}
};
Channel client = client(server, clientHandler);
try {
client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'I', 'N', 'G' })).syncUninterruptibly();
assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
clientPromise.sync();
serverPromise.sync();
} finally {
client.close().sync();
}
} finally {
server.close().sync();
}
} finally {
ReferenceCountUtil.release(sslClientContext);
}
} finally {
ReferenceCountUtil.release(sslServerContext);
if (executorService != null) {
executorService.shutdown();
}
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project zuul by Netflix.
the class IoUringTest method exerciseIoUringServer.
private void exerciseIoUringServer() throws Exception {
IOUring.ensureAvailability();
ServerStatusManager ssm = mock(ServerStatusManager.class);
Map<NamedSocketAddress, ChannelInitializer<?>> initializers = new HashMap<>();
final List<IOUringSocketChannel> ioUringChannels = Collections.synchronizedList(new ArrayList<IOUringSocketChannel>());
ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
LOGGER.info("Channel: " + ch.getClass().getName() + ", isActive=" + ch.isActive() + ", isOpen=" + ch.isOpen());
if (ch instanceof IOUringSocketChannel) {
ioUringChannels.add((IOUringSocketChannel) ch);
}
}
};
initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init);
// The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same
initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init);
ClientConnectionsShutdown ccs = new ClientConnectionsShutdown(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, /* discoveryClient= */
null);
EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry());
EventLoopConfig elc = new EventLoopConfig() {
@Override
public int eventLoopCount() {
return 1;
}
@Override
public int acceptorCount() {
return 1;
}
};
Server s = new Server(new NoopRegistry(), ssm, initializers, ccs, elgm, elc);
s.start();
List<NamedSocketAddress> addresses = s.getListeningAddresses();
assertEquals(2, addresses.size());
addresses.forEach(address -> {
assertTrue(address.unwrap() instanceof InetSocketAddress);
InetSocketAddress inetAddress = ((InetSocketAddress) address.unwrap());
assertNotEquals(inetAddress.getPort(), 0);
checkConnection(inetAddress.getPort());
});
await().atMost(1, SECONDS).until(() -> ioUringChannels.size() == 2);
s.stop();
assertEquals(2, ioUringChannels.size());
for (IOUringSocketChannel ch : ioUringChannels) {
assertTrue("isShutdown", ch.isShutdown());
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project grpc-java by grpc.
the class ProtocolNegotiatorsTest method plaintextUpgradeNegotiator.
@Test
public void plaintextUpgradeNegotiator() throws Exception {
LocalAddress addr = new LocalAddress("plaintextUpgradeNegotiator");
UpgradeCodecFactory ucf = new UpgradeCodecFactory() {
@Override
public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
return new Http2ServerUpgradeCodec(FakeGrpcHttp2ConnectionHandler.newHandler());
}
};
final HttpServerCodec serverCodec = new HttpServerCodec();
final HttpServerUpgradeHandler serverUpgradeHandler = new HttpServerUpgradeHandler(serverCodec, ucf);
Channel serverChannel = new ServerBootstrap().group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(serverCodec, serverUpgradeHandler);
}
}).bind(addr).sync().channel();
FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler();
ProtocolNegotiator nego = ProtocolNegotiators.plaintextUpgrade();
ChannelHandler ch = nego.newHandler(gh);
WriteBufferingAndExceptionHandler wbaeh = new WriteBufferingAndExceptionHandler(ch);
Channel channel = new Bootstrap().group(group).channel(LocalChannel.class).handler(wbaeh).register().sync().channel();
ChannelFuture write = channel.writeAndFlush(NettyClientHandler.NOOP_MESSAGE);
channel.connect(serverChannel.localAddress());
boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!completed) {
assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
// sync should fail if we are in this block.
write.sync();
throw new AssertionError("neither wrote nor negotiated");
}
channel.close().sync();
serverChannel.close();
assertThat(gh.securityInfo).isNull();
assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.NONE);
assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr);
}
Aggregations