Search in sources :

Example 66 with ChannelFutureListener

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

the class Http2FrameCodecTest method upgradeWithoutFlowControlling.

@Test
public void upgradeWithoutFlowControlling() throws Exception {
    channel.pipeline().addAfter(frameCodec.ctx.name(), null, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof Http2DataFrame) {
                // Simulate consuming the frame and update the flow-controller.
                Http2DataFrame data = (Http2DataFrame) msg;
                ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(data.initialFlowControlledBytes()).stream(data.stream())).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        Throwable cause = future.cause();
                        if (cause != null) {
                            ctx.fireExceptionCaught(cause);
                        }
                    }
                });
            }
            ReferenceCountUtil.release(msg);
        }
    });
    frameInboundWriter.writeInboundHeaders(Http2CodecUtil.HTTP_UPGRADE_STREAM_ID, request, 31, false);
    // Using reflect as the constructor is package-private and the class is final.
    Constructor<UpgradeEvent> constructor = UpgradeEvent.class.getDeclaredConstructor(CharSequence.class, FullHttpRequest.class);
    // Check if we could make it accessible which may fail on java9.
    Assumptions.assumeTrue(ReflectionUtil.trySetAccessible(constructor, true) == null);
    String longString = new String(new char[70000]).replace("\0", "*");
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/", bb(longString));
    HttpServerUpgradeHandler.UpgradeEvent upgradeEvent = constructor.newInstance("HTTP/2", request);
    channel.pipeline().fireUserEventTriggered(upgradeEvent);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AsciiString(io.netty.util.AsciiString) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelFutureListener(io.netty.channel.ChannelFutureListener) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) UpgradeEvent(io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeEvent) UpgradeEvent(io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeEvent) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 67 with ChannelFutureListener

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

the class Http2FrameCodecTest method newOutboundStream.

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void newOutboundStream() {
    final Http2FrameStream stream = frameCodec.newStream();
    assertNotNull(stream);
    assertFalse(isStreamIdValid(stream.id()));
    final Promise<Void> listenerExecuted = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE);
    channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false).stream(stream)).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            assertTrue(future.isSuccess());
            assertTrue(isStreamIdValid(stream.id()));
            listenerExecuted.setSuccess(null);
        }
    });
    ByteBuf data = Unpooled.buffer().writeZero(100);
    ChannelFuture f = channel.writeAndFlush(new DefaultHttp2DataFrame(data).stream(stream));
    assertTrue(f.isSuccess());
    listenerExecuted.syncUninterruptibly();
    assertTrue(listenerExecuted.isSuccess());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultPromise(io.netty.util.concurrent.DefaultPromise) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 68 with ChannelFutureListener

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

the class Http2ConnectionRoundtripTest method listenerExceptionShouldCloseConnection.

@Test
public void listenerExceptionShouldCloseConnection() throws Exception {
    final Http2Headers headers = dummyHeaders();
    doThrow(new RuntimeException("Fake Exception")).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(headers), eq(0), eq((short) 16), eq(false), eq(0), eq(false));
    bootstrapEnv(1, 0, 1, 1);
    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            closeLatch.countDown();
        }
    });
    // Create a single stream by sending a HEADERS frame to the server.
    runInChannel(clientChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
            http2Client.flush(ctx());
        }
    });
    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    // Wait for the close to occur.
    assertTrue(closeLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertFalse(clientChannel.isOpen());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Example 69 with ChannelFutureListener

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

the class Http2ConnectionRoundtripTest method encodeViolatesMaxHeaderListSizeCanStillUseConnection.

@Test
public void encodeViolatesMaxHeaderListSizeCanStillUseConnection() throws Exception {
    bootstrapEnv(1, 2, 1, 0, 0);
    final CountDownLatch serverSettingsAckLatch1 = new CountDownLatch(2);
    final CountDownLatch serverSettingsAckLatch2 = new CountDownLatch(3);
    final CountDownLatch clientSettingsLatch1 = new CountDownLatch(3);
    final CountDownLatch serverRevHeadersLatch = new CountDownLatch(1);
    final CountDownLatch clientHeadersLatch = new CountDownLatch(1);
    final CountDownLatch clientDataWrite = new CountDownLatch(1);
    final AtomicReference<Throwable> clientHeadersWriteException = new AtomicReference<Throwable>();
    final AtomicReference<Throwable> clientHeadersWriteException2 = new AtomicReference<Throwable>();
    final AtomicReference<Throwable> clientDataWriteException = new AtomicReference<Throwable>();
    final Http2Headers headers = dummyHeaders();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            serverSettingsAckLatch1.countDown();
            serverSettingsAckLatch2.countDown();
            return null;
        }
    }).when(serverListener).onSettingsAckRead(any(ChannelHandlerContext.class));
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            clientSettingsLatch1.countDown();
            return null;
        }
    }).when(clientListener).onSettingsRead(any(ChannelHandlerContext.class), any(Http2Settings.class));
    // Manually add a listener for when we receive the expected headers on the server.
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            serverRevHeadersLatch.countDown();
            return null;
        }
    }).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), eq(headers), anyInt(), anyShort(), anyBoolean(), eq(0), eq(true));
    // Set the maxHeaderListSize to 100 so we may be able to write some headers, but not all. We want to verify
    // that we don't corrupt state if some can be written but not all.
    runInChannel(serverConnectedChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Server.encoder().writeSettings(serverCtx(), new Http2Settings().copyFrom(http2Server.decoder().localSettings()).maxHeaderListSize(100), serverNewPromise());
            http2Server.flush(serverCtx());
        }
    });
    assertTrue(serverSettingsAckLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    runInChannel(clientChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, false, newPromise()).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    clientHeadersWriteException.set(future.cause());
                }
            });
            // It is expected that this write should fail locally and the remote peer will never see this.
            http2Client.encoder().writeData(ctx(), 3, Unpooled.buffer(), 0, true, newPromise()).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    clientDataWriteException.set(future.cause());
                    clientDataWrite.countDown();
                }
            });
            http2Client.flush(ctx());
        }
    });
    assertTrue(clientDataWrite.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertNotNull(clientHeadersWriteException.get(), "Header encode should have exceeded maxHeaderListSize!");
    assertNotNull(clientDataWriteException.get(), "Data on closed stream should fail!");
    // Set the maxHeaderListSize to the max value so we can send the headers.
    runInChannel(serverConnectedChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Server.encoder().writeSettings(serverCtx(), new Http2Settings().copyFrom(http2Server.decoder().localSettings()).maxHeaderListSize(Http2CodecUtil.MAX_HEADER_LIST_SIZE), serverNewPromise());
            http2Server.flush(serverCtx());
        }
    });
    assertTrue(clientSettingsLatch1.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertTrue(serverSettingsAckLatch2.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    runInChannel(clientChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Client.encoder().writeHeaders(ctx(), 5, headers, 0, true, newPromise()).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    clientHeadersWriteException2.set(future.cause());
                    clientHeadersLatch.countDown();
                }
            });
            http2Client.flush(ctx());
        }
    });
    assertTrue(clientHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertNull(clientHeadersWriteException2.get(), "Client write of headers should succeed with increased header list size!");
    assertTrue(serverRevHeadersLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    verify(serverListener, never()).onDataRead(any(ChannelHandlerContext.class), anyInt(), any(ByteBuf.class), anyInt(), anyBoolean());
    // Verify that no errors have been received.
    verify(serverListener, never()).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class));
    verify(serverListener, never()).onRstStreamRead(any(ChannelHandlerContext.class), anyInt(), anyLong());
    verify(clientListener, never()).onGoAwayRead(any(ChannelHandlerContext.class), anyInt(), anyLong(), any(ByteBuf.class));
    verify(clientListener, never()).onRstStreamRead(any(ChannelHandlerContext.class), anyInt(), anyLong());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.jupiter.api.Test)

Example 70 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener 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)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17