Search in sources :

Example 56 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTransportTest method testFireChannelReadAfterHandshakeSuccess.

private void testFireChannelReadAfterHandshakeSuccess(SslProvider provider) throws Exception {
    SelfSignedCertificate ssc = null;
    try {
        ssc = new SelfSignedCertificate();
        final SslContext serverCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE).applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)).build();
        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(serverCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                    @Override
                    protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                        ctx.pipeline().addLast(new Http2FrameCodecBuilder(true).build());
                        ctx.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter() {

                            @Override
                            public void channelRead(final ChannelHandlerContext ctx, Object msg) {
                                if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) {
                                    ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false)).addListener(new ChannelFutureListener() {

                                        @Override
                                        public void operationComplete(ChannelFuture future) {
                                            ctx.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.copiedBuffer("Hello World", CharsetUtil.US_ASCII), true));
                                        }
                                    });
                                }
                                ReferenceCountUtil.release(msg);
                            }
                        }));
                    }
                });
            }
        });
        serverChannel = sb.bind(new InetSocketAddress(NetUtil.LOCALHOST, 0)).sync().channel();
        final SslContext clientCtx = SslContextBuilder.forClient().sslProvider(provider).ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE).trustManager(InsecureTrustManagerFactory.INSTANCE).applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)).build();
        final CountDownLatch latch = new CountDownLatch(1);
        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(clientCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new Http2FrameCodecBuilder(false).build());
                ch.pipeline().addLast(new Http2MultiplexHandler(DISCARD_HANDLER));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslHandshakeCompletionEvent) {
                            SslHandshakeCompletionEvent handshakeCompletionEvent = (SslHandshakeCompletionEvent) evt;
                            if (handshakeCompletionEvent.isSuccess()) {
                                Http2StreamChannelBootstrap h2Bootstrap = new Http2StreamChannelBootstrap(clientChannel);
                                h2Bootstrap.handler(new ChannelInboundHandlerAdapter() {

                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                        if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) {
                                            latch.countDown();
                                        }
                                        ReferenceCountUtil.release(msg);
                                    }
                                });
                                h2Bootstrap.open().addListener(new FutureListener<Channel>() {

                                    @Override
                                    public void operationComplete(Future<Channel> future) {
                                        if (future.isSuccess()) {
                                            future.getNow().writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), true));
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
            }
        });
        clientChannel = bs.connect(serverChannel.localAddress()).sync().channel();
        latch.await();
    } finally {
        if (ssc != null) {
            ssc.delete();
        }
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 57 with ChannelInboundHandlerAdapter

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

the class HttpToHttp2ConnectionHandlerTest method bootstrapEnv.

private void bootstrapEnv(int requestCountDown, int serverSettingsAckCount, int trailersCount) throws Exception {
    final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(serverSettingsAckCount);
    trailersLatch = trailersCount == 0 ? null : new CountDownLatch(trailersCount);
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new DefaultEventLoopGroup());
    sb.channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            serverConnectedChannel = ch;
            ChannelPipeline p = ch.pipeline();
            serverFrameCountDown = new FrameCountDown(serverListener, serverSettingsAckLatch, requestLatch, null, trailersLatch);
            p.addLast(new HttpToHttp2ConnectionHandlerBuilder().server(true).frameListener(serverFrameCountDown).httpScheme(HttpScheme.HTTP).build());
            serverChannelLatch.countDown();
        }
    });
    cb.group(new DefaultEventLoopGroup());
    cb.channel(LocalChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            HttpToHttp2ConnectionHandler handler = new HttpToHttp2ConnectionHandlerBuilder().server(false).frameListener(clientListener).gracefulShutdownTimeoutMillis(0).build();
            p.addLast(handler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) {
                        prefaceWrittenLatch.countDown();
                        ctx.pipeline().remove(this);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new LocalAddress("HttpToHttp2ConnectionHandlerTest")).sync().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    assertTrue(prefaceWrittenLatch.await(5, SECONDS));
    assertTrue(serverChannelLatch.await(WAIT_TIME_SECONDS, SECONDS));
}
Also used : FrameCountDown(io.netty.handler.codec.http2.Http2TestUtil.FrameCountDown) ChannelFuture(io.netty.channel.ChannelFuture) 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) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 58 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter 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 59 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTest method writabilityOfParentIsRespected.

@Test
public void writabilityOfParentIsRespected() {
    Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter());
    childChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(2048, 4096));
    parentChannel.config().setWriteBufferWaterMark(new WriteBufferWaterMark(256, 512));
    assertTrue(childChannel.isWritable());
    assertTrue(parentChannel.isActive());
    childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
    parentChannel.flush();
    assertTrue(childChannel.isWritable());
    childChannel.write(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(256)));
    assertTrue(childChannel.isWritable());
    childChannel.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero(512)));
    long bytesBeforeUnwritable = childChannel.bytesBeforeUnwritable();
    assertNotEquals(0, bytesBeforeUnwritable);
    // Add something to the ChannelOutboundBuffer of the parent to simulate queuing in the parents channel buffer
    // and verify that this only affect the writability of the parent channel while the child stays writable
    // until it used all of its credits.
    parentChannel.unsafe().outboundBuffer().addMessage(Unpooled.buffer().writeZero(800), 800, parentChannel.voidPromise());
    assertFalse(parentChannel.isWritable());
    assertTrue(childChannel.isWritable());
    assertEquals(4096, childChannel.bytesBeforeUnwritable());
    // Flush everything which simulate writing everything to the socket.
    parentChannel.flush();
    assertTrue(parentChannel.isWritable());
    assertTrue(childChannel.isWritable());
    assertEquals(bytesBeforeUnwritable, childChannel.bytesBeforeUnwritable());
    ChannelFuture future = childChannel.writeAndFlush(new DefaultHttp2DataFrame(Unpooled.buffer().writeZero((int) bytesBeforeUnwritable)));
    assertFalse(childChannel.isWritable());
    assertTrue(parentChannel.isWritable());
    parentChannel.flush();
    assertFalse(future.isDone());
    assertTrue(parentChannel.isWritable());
    assertFalse(childChannel.isWritable());
    // Now write an window update frame for the stream which then should ensure we will flush the bytes that were
    // queued in the RemoteFlowController before for the stream.
    frameInboundWriter.writeInboundWindowUpdate(childChannel.stream().id(), (int) bytesBeforeUnwritable);
    assertTrue(childChannel.isWritable());
    assertTrue(future.isDone());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 60 with ChannelInboundHandlerAdapter

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

the class Http2MultiplexTest method outboundStreamShouldNotWriteResetFrameOnClose_IfStreamDidntExist.

@Test
public void outboundStreamShouldNotWriteResetFrameOnClose_IfStreamDidntExist() {
    when(frameWriter.writeHeaders(eqCodecCtx(), anyInt(), any(Http2Headers.class), anyInt(), anyBoolean(), any(ChannelPromise.class))).thenAnswer(new Answer<ChannelFuture>() {

        private boolean headersWritten;

        @Override
        public ChannelFuture answer(InvocationOnMock invocationOnMock) {
            // refuses to allocate a new stream due to having received a GOAWAY.
            if (!headersWritten) {
                headersWritten = true;
                return ((ChannelPromise) invocationOnMock.getArgument(5)).setFailure(new Exception("boom"));
            }
            return ((ChannelPromise) invocationOnMock.getArgument(5)).setSuccess();
        }
    });
    Http2StreamChannel childChannel = newOutboundStream(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
            ctx.fireChannelActive();
        }
    });
    assertFalse(childChannel.isActive());
    childChannel.close();
    parentChannel.runPendingTasks();
    // The channel was never active so we should not generate a RST frame.
    verify(frameWriter, never()).writeRstStream(eqCodecCtx(), eqStreamId(childChannel), anyLong(), anyChannelPromise());
    assertTrue(parentChannel.outboundMessages().isEmpty());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelPromise(io.netty.channel.ChannelPromise) Http2TestUtil.anyChannelPromise(io.netty.handler.codec.http2.Http2TestUtil.anyChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException) ClosedChannelException(java.nio.channels.ClosedChannelException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

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