Search in sources :

Example 31 with ChannelInitializer

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);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 32 with ChannelInitializer

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...
        }
    };
}
Also used : ReferenceCountedOpenSslEngine(io.netty.handler.ssl.ReferenceCountedOpenSslEngine) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 33 with ChannelInitializer

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();
        }
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ExecutorService(java.util.concurrent.ExecutorService) ChannelInitializer(io.netty.channel.ChannelInitializer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 34 with ChannelInitializer

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());
    }
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ServerStatusManager(com.netflix.netty.common.status.ServerStatusManager) InetSocketAddress(java.net.InetSocketAddress) IOUringSocketChannel(io.netty.incubator.channel.uring.IOUringSocketChannel) Channel(io.netty.channel.Channel) IOUringSocketChannel(io.netty.incubator.channel.uring.IOUringSocketChannel) EventLoopGroupMetrics(com.netflix.netty.common.metrics.EventLoopGroupMetrics) NoopRegistry(com.netflix.spectator.api.NoopRegistry) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 35 with ChannelInitializer

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);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) UpgradeCodecFactory(io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory) ChannelHandler(io.netty.channel.ChannelHandler) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClientTlsProtocolNegotiator(io.grpc.netty.ProtocolNegotiators.ClientTlsProtocolNegotiator) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)85 Channel (io.netty.channel.Channel)58 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)29 ChannelPipeline (io.netty.channel.ChannelPipeline)26 EventLoopGroup (io.netty.channel.EventLoopGroup)26 LocalServerChannel (io.netty.channel.local.LocalServerChannel)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 SocketChannel (io.netty.channel.socket.SocketChannel)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 CountDownLatch (java.util.concurrent.CountDownLatch)12 ChannelHandler (io.netty.channel.ChannelHandler)11