Search in sources :

Example 26 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class CompositeBufferGatheringWriteTest method testCompositeBufferPartialWriteDoesNotCorruptData.

public void testCompositeBufferPartialWriteDoesNotCorruptData(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    // The scenario is the following:
    // Limit SO_SNDBUF so that a single buffer can be written, and part of a CompositeByteBuf at the same time.
    // We then write the single buffer, the CompositeByteBuf, and another single buffer and verify the data is not
    // corrupted when we read it on the other side.
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        Random r = new Random();
        final int soSndBuf = 1024;
        ByteBufAllocator alloc = ByteBufAllocator.DEFAULT;
        final ByteBuf expectedContent = alloc.buffer(soSndBuf * 2);
        expectedContent.writeBytes(newRandomBytes(expectedContent.writableBytes(), r));
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Object> clientReceived = new AtomicReference<Object>();
        sb.childOption(ChannelOption.SO_SNDBUF, soSndBuf).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        compositeBufferPartialWriteDoesNotCorruptDataInitServerConfig(ctx.channel().config(), soSndBuf);
                        // First single write
                        int offset = soSndBuf - 100;
                        ctx.write(expectedContent.retainedSlice(expectedContent.readerIndex(), offset));
                        // Build and write CompositeByteBuf
                        CompositeByteBuf compositeByteBuf = ctx.alloc().compositeBuffer();
                        compositeByteBuf.addComponent(true, expectedContent.retainedSlice(expectedContent.readerIndex() + offset, 50));
                        offset += 50;
                        compositeByteBuf.addComponent(true, expectedContent.retainedSlice(expectedContent.readerIndex() + offset, 200));
                        offset += 200;
                        ctx.write(compositeByteBuf);
                        // Write a single buffer that is smaller than the second component of the CompositeByteBuf
                        // above but small enough to fit in the remaining space allowed by the soSndBuf amount.
                        ctx.write(expectedContent.retainedSlice(expectedContent.readerIndex() + offset, 50));
                        offset += 50;
                        // Write the remainder of the content
                        ctx.writeAndFlush(expectedContent.retainedSlice(expectedContent.readerIndex() + offset, expectedContent.readableBytes() - expectedContent.readerIndex() - offset)).addListener(ChannelFutureListener.CLOSE);
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        // IOException is fine as it will also close the channel and may just be a connection reset.
                        if (!(cause instanceof IOException)) {
                            clientReceived.set(cause);
                            latch.countDown();
                        }
                    }
                });
            }
        });
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    private ByteBuf aggregator;

                    @Override
                    public void handlerAdded(ChannelHandlerContext ctx) {
                        aggregator = ctx.alloc().buffer(expectedContent.readableBytes());
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                        try {
                            if (msg instanceof ByteBuf) {
                                aggregator.writeBytes((ByteBuf) msg);
                            }
                        } finally {
                            ReferenceCountUtil.release(msg);
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        // IOException is fine as it will also close the channel and may just be a connection reset.
                        if (!(cause instanceof IOException)) {
                            clientReceived.set(cause);
                            latch.countDown();
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        if (clientReceived.compareAndSet(null, aggregator)) {
                            try {
                                assertEquals(expectedContent.readableBytes(), aggregator.readableBytes());
                            } catch (Throwable cause) {
                                aggregator.release();
                                aggregator = null;
                                clientReceived.set(cause);
                            } finally {
                                latch.countDown();
                            }
                        }
                    }
                });
            }
        });
        serverChannel = sb.bind().syncUninterruptibly().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        latch.await();
        Object received = clientReceived.get();
        if (received instanceof ByteBuf) {
            ByteBuf actual = (ByteBuf) received;
            assertEquals(expectedContent, actual);
            expectedContent.release();
            actual.release();
        } else {
            expectedContent.release();
            throw (Throwable) received;
        }
    } finally {
        if (clientChannel != null) {
            clientChannel.close().sync();
        }
        if (serverChannel != null) {
            serverChannel.close().sync();
        }
    }
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) Random(java.util.Random) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 27 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class CompositeBufferGatheringWriteTest method testSingleCompositeBufferWrite.

public void testSingleCompositeBufferWrite(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Object> clientReceived = new AtomicReference<Object>();
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        ctx.writeAndFlush(newCompositeBuffer(ctx.alloc())).addListener(ChannelFutureListener.CLOSE);
                    }
                });
            }
        });
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    private ByteBuf aggregator;

                    @Override
                    public void handlerAdded(ChannelHandlerContext ctx) {
                        aggregator = ctx.alloc().buffer(EXPECTED_BYTES);
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                        try {
                            if (msg instanceof ByteBuf) {
                                aggregator.writeBytes((ByteBuf) msg);
                            }
                        } finally {
                            ReferenceCountUtil.release(msg);
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        // IOException is fine as it will also close the channel and may just be a connection reset.
                        if (!(cause instanceof IOException)) {
                            clientReceived.set(cause);
                            latch.countDown();
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        if (clientReceived.compareAndSet(null, aggregator)) {
                            try {
                                assertEquals(EXPECTED_BYTES, aggregator.readableBytes());
                            } catch (Throwable cause) {
                                aggregator.release();
                                aggregator = null;
                                clientReceived.set(cause);
                            } finally {
                                latch.countDown();
                            }
                        }
                    }
                });
            }
        });
        serverChannel = sb.bind().syncUninterruptibly().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        ByteBuf expected = newCompositeBuffer(clientChannel.alloc());
        latch.await();
        Object received = clientReceived.get();
        if (received instanceof ByteBuf) {
            ByteBuf actual = (ByteBuf) received;
            assertEquals(expected, actual);
            expected.release();
            actual.release();
        } else {
            expected.release();
            throw (Throwable) received;
        }
    } finally {
        if (clientChannel != null) {
            clientChannel.close().sync();
        }
        if (serverChannel != null) {
            serverChannel.close().sync();
        }
    }
}
Also used : Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 28 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class ReplayingDecoderTest method testFireChannelReadCompleteOnInactive.

@Test
public void testFireChannelReadCompleteOnInactive() throws InterruptedException {
    final BlockingQueue<Integer> queue = new LinkedBlockingDeque<Integer>();
    final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[] { 'a', 'b' });
    EmbeddedChannel channel = new EmbeddedChannel(new ReplayingDecoder<Integer>() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int readable = in.readableBytes();
            assertTrue(readable > 0);
            in.skipBytes(readable);
            out.add("data");
        }

        @Override
        protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            assertFalse(in.isReadable());
            out.add("data");
        }
    }, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            queue.add(3);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            queue.add(1);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            if (!ctx.channel().isActive()) {
                queue.add(2);
            }
        }
    });
    assertFalse(channel.writeInbound(buf));
    channel.finish();
    assertEquals(1, (int) queue.take());
    assertEquals(1, (int) queue.take());
    assertEquals(2, (int) queue.take());
    assertEquals(3, (int) queue.take());
    assertTrue(queue.isEmpty());
}
Also used : LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 29 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SslHandlerTest method testHandshakeFailureOnlyFireExceptionOnce.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(new X509ExtendedTrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            failVerification();
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return EmptyArrays.EMPTY_X509_CERTIFICATES;
        }

        private void failVerification() throws CertificateException {
            throw new CertificateException();
        }
    }).sslProvider(SslProvider.JDK).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    try {
        final Object terminalEvent = new Object();
        final BlockingQueue<Object> errorQueue = new LinkedBlockingQueue<Object>();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(serverSslHandler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) {
                        errorQueue.add(cause);
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) {
                        errorQueue.add(terminalEvent);
                    }
                });
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        final ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(clientSslHandler);
            }
        }).connect(sc.localAddress());
        future.syncUninterruptibly();
        clientSslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {

            @Override
            public void operationComplete(Future<Channel> f) {
                future.channel().close();
            }
        });
        assertFalse(clientSslHandler.handshakeFuture().await().isSuccess());
        assertFalse(serverSslHandler.handshakeFuture().await().isSuccess());
        Object error = errorQueue.take();
        assertThat(error, Matchers.instanceOf(DecoderException.class));
        assertThat(((Throwable) error).getCause(), Matchers.<Throwable>instanceOf(SSLException.class));
        Object terminal = errorQueue.take();
        assertSame(terminalEvent, terminal);
        assertNull(errorQueue.poll(1, TimeUnit.MILLISECONDS));
    } finally {
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) InetSocketAddress(java.net.InetSocketAddress) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 30 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SslHandlerTest method newHandler.

private static ChannelHandler newHandler(final SslContext sslCtx, final Promise<Void> promise) {
    return new ChannelInitializer() {

        @Override
        protected void initChannel(final Channel ch) {
            final SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
            sslHandler.setHandshakeTimeoutMillis(1000);
            ch.pipeline().addFirst(sslHandler);
            sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {

                @Override
                public void operationComplete(final Future<Channel> future) {
                    ch.pipeline().remove(sslHandler);
                    // Schedule the close so removal has time to propagate exception if any.
                    ch.eventLoop().execute(new Runnable() {

                        @Override
                        public void run() {
                            ch.close();
                        }
                    });
                }
            });
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    if (cause instanceof CodecException) {
                        cause = cause.getCause();
                    }
                    if (cause instanceof IllegalReferenceCountException) {
                        promise.setFailure(cause);
                    }
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    promise.trySuccess(null);
                }
            });
        }
    };
}
Also used : LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CodecException(io.netty.handler.codec.CodecException) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)248 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)192 Channel (io.netty.channel.Channel)132 Bootstrap (io.netty.bootstrap.Bootstrap)109 Test (org.junit.jupiter.api.Test)102 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)99 ChannelFuture (io.netty.channel.ChannelFuture)71 CountDownLatch (java.util.concurrent.CountDownLatch)70 InetSocketAddress (java.net.InetSocketAddress)66 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)54 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)53 EventLoopGroup (io.netty.channel.EventLoopGroup)52 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)51 ByteBuf (io.netty.buffer.ByteBuf)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)46 ClosedChannelException (java.nio.channels.ClosedChannelException)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)44 LocalChannel (io.netty.channel.local.LocalChannel)42 SocketChannel (io.netty.channel.socket.SocketChannel)39