Search in sources :

Example 51 with ChannelInboundHandlerAdapter

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

the class ByteToMessageDecoderTest method testRemoveWhileInCallDecode.

// See https://github.com/netty/netty/issues/4635
@Test
public void testRemoveWhileInCallDecode() {
    final Object upgradeMessage = new Object();
    final ByteToMessageDecoder decoder = new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            assertEquals('a', in.readByte());
            out.add(upgradeMessage);
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(decoder, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg == upgradeMessage) {
                ctx.pipeline().remove(decoder);
                return;
            }
            ctx.fireChannelRead(msg);
        }
    });
    ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { 'a', 'b', 'c' });
    assertTrue(channel.writeInbound(buf.copy()));
    ByteBuf b = channel.readInbound();
    assertEquals(b, buf.skipBytes(1));
    assertFalse(channel.finish());
    buf.release();
    b.release();
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) UnpooledHeapByteBuf(io.netty.buffer.UnpooledHeapByteBuf) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 52 with ChannelInboundHandlerAdapter

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

the class DetectPeerCloseWithoutReadTest method clientCloseWithoutServerReadIsDetected0.

private void clientCloseWithoutServerReadIsDetected0(final boolean extraReadRequested) throws InterruptedException {
    EventLoopGroup serverGroup = null;
    EventLoopGroup clientGroup = null;
    Channel serverChannel = null;
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicInteger bytesRead = new AtomicInteger();
        final int expectedBytes = 100;
        serverGroup = newGroup();
        clientGroup = newGroup();
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup);
        sb.channel(serverChannel());
        // Ensure we read only one message per read() call and that we need multiple read()
        // calls to consume everything.
        sb.childOption(ChannelOption.AUTO_READ, false);
        sb.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);
        sb.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(expectedBytes / 10));
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(new TestHandler(bytesRead, extraReadRequested, latch));
            }
        });
        serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        Bootstrap cb = new Bootstrap();
        cb.group(serverGroup);
        cb.channel(clientChannel());
        cb.handler(new ChannelInboundHandlerAdapter());
        Channel clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        ByteBuf buf = clientChannel.alloc().buffer(expectedBytes);
        buf.writerIndex(buf.writerIndex() + expectedBytes);
        clientChannel.writeAndFlush(buf).addListener(ChannelFutureListener.CLOSE);
        latch.await();
        assertEquals(expectedBytes, bytesRead.get());
    } finally {
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        if (serverGroup != null) {
            serverGroup.shutdownGracefully();
        }
        if (clientGroup != null) {
            clientGroup.shutdownGracefully();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 53 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTest method outboundStreamShouldWriteResetFrameOnClose_headersSent.

@Test
public void outboundStreamShouldWriteResetFrameOnClose_headersSent() {
    ChannelHandler handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
            ctx.fireChannelActive();
        }
    };
    Http2StreamChannel childChannel = newOutboundStream(handler);
    assertTrue(childChannel.isActive());
    childChannel.close();
    verify(frameWriter).writeRstStream(eqCodecCtx(), eqStreamId(childChannel), eq(Http2Error.CANCEL.code()), anyChannelPromise());
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 54 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTest method endOfStreamDoesNotDiscardData.

@Test
public void endOfStreamDoesNotDiscardData() {
    AtomicInteger numReads = new AtomicInteger(1);
    final AtomicBoolean shouldDisableAutoRead = new AtomicBoolean();
    Consumer<ChannelHandlerContext> ctxConsumer = new Consumer<ChannelHandlerContext>() {

        @Override
        public void accept(ChannelHandlerContext obj) {
            if (shouldDisableAutoRead.get()) {
                obj.channel().config().setAutoRead(false);
            }
        }
    };
    LastInboundHandler inboundHandler = new LastInboundHandler(ctxConsumer);
    Http2StreamChannel childChannel = newInboundStream(3, false, numReads, inboundHandler);
    childChannel.config().setAutoRead(false);
    Http2DataFrame dataFrame1 = new DefaultHttp2DataFrame(bb("1")).stream(childChannel.stream());
    Http2DataFrame dataFrame2 = new DefaultHttp2DataFrame(bb("2")).stream(childChannel.stream());
    Http2DataFrame dataFrame3 = new DefaultHttp2DataFrame(bb("3")).stream(childChannel.stream());
    Http2DataFrame dataFrame4 = new DefaultHttp2DataFrame(bb("4")).stream(childChannel.stream());
    assertEquals(new DefaultHttp2HeadersFrame(request).stream(childChannel.stream()), inboundHandler.readInbound());
    ChannelHandler readCompleteSupressHandler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
        // We want to simulate the parent channel calling channelRead and delay calling channelReadComplete.
        }
    };
    parentChannel.pipeline().addFirst(readCompleteSupressHandler);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("1"), 0, false);
    assertEqualsAndRelease(dataFrame1, inboundHandler.<Http2DataFrame>readInbound());
    // Deliver frames, and then a stream closed while read is inactive.
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("2"), 0, false);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("3"), 0, false);
    frameInboundWriter.writeInboundData(childChannel.stream().id(), bb("4"), 0, false);
    shouldDisableAutoRead.set(true);
    childChannel.config().setAutoRead(true);
    numReads.set(1);
    frameInboundWriter.writeInboundRstStream(childChannel.stream().id(), Http2Error.NO_ERROR.code());
    // Detecting EOS should flush all pending data regardless of read calls.
    assertEqualsAndRelease(dataFrame2, inboundHandler.<Http2DataFrame>readInbound());
    assertNull(inboundHandler.readInbound());
    // As we limited the number to 1 we also need to call read() again.
    childChannel.read();
    assertEqualsAndRelease(dataFrame3, inboundHandler.<Http2DataFrame>readInbound());
    assertEqualsAndRelease(dataFrame4, inboundHandler.<Http2DataFrame>readInbound());
    Http2ResetFrame resetFrame = useUserEventForResetFrame() ? inboundHandler.<Http2ResetFrame>readUserEvent() : inboundHandler.<Http2ResetFrame>readInbound();
    assertEquals(childChannel.stream(), resetFrame.stream());
    assertEquals(Http2Error.NO_ERROR.code(), resetFrame.errorCode());
    assertNull(inboundHandler.readInbound());
    // Now we want to call channelReadComplete and simulate the end of the read loop.
    parentChannel.pipeline().remove(readCompleteSupressHandler);
    parentChannel.flushInbound();
    childChannel.closeFuture().syncUninterruptibly();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Consumer(io.netty.handler.codec.http2.LastInboundHandler.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 55 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTransportTest method asyncSettingsAck0.

private void asyncSettingsAck0(final Http2FrameCodec codec, final ChannelHandler multiplexer) throws InterruptedException {
    // The client expects 2 settings frames. One from the connection setup and one from this test.
    final CountDownLatch serverAckOneLatch = new CountDownLatch(1);
    final CountDownLatch serverAckAllLatch = new CountDownLatch(2);
    final CountDownLatch clientSettingsLatch = new CountDownLatch(2);
    final CountDownLatch serverConnectedChannelLatch = new CountDownLatch(1);
    final AtomicReference<Channel> serverConnectedChannelRef = new AtomicReference<Channel>();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(eventLoopGroup);
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) {
            ch.pipeline().addLast(codec);
            if (multiplexer != null) {
                ch.pipeline().addLast(multiplexer);
            }
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelActive(ChannelHandlerContext ctx) {
                    serverConnectedChannelRef.set(ctx.channel());
                    serverConnectedChannelLatch.countDown();
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    if (msg instanceof Http2SettingsAckFrame) {
                        serverAckOneLatch.countDown();
                        serverAckAllLatch.countDown();
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).awaitUninterruptibly().channel();
    Bootstrap bs = new Bootstrap();
    bs.group(eventLoopGroup);
    bs.channel(NioSocketChannel.class);
    bs.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) {
            ch.pipeline().addLast(Http2MultiplexCodecBuilder.forClient(DISCARD_HANDLER).autoAckSettingsFrame(false).build());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    if (msg instanceof Http2SettingsFrame) {
                        clientSettingsLatch.countDown();
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    clientChannel = bs.connect(serverChannel.localAddress()).awaitUninterruptibly().channel();
    serverConnectedChannelLatch.await();
    serverConnectedChannel = serverConnectedChannelRef.get();
    serverConnectedChannel.writeAndFlush(new DefaultHttp2SettingsFrame(new Http2Settings().maxConcurrentStreams(10))).sync();
    clientSettingsLatch.await();
    // We expect a timeout here because we want to asynchronously generate the SETTINGS ACK below.
    assertFalse(serverAckOneLatch.await(300, MILLISECONDS));
    // We expect 2 settings frames, the initial settings frame during connection establishment and the setting frame
    // written in this test. We should ack both of these settings frames.
    clientChannel.writeAndFlush(Http2SettingsAckFrame.INSTANCE).sync();
    clientChannel.writeAndFlush(Http2SettingsAckFrame.INSTANCE).sync();
    serverAckAllLatch.await();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) 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) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) 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